diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..92bbe0bfc5296fd0716c6d6b7ec59624f831ac12 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "c2db1a5d5faa728cd7c8fe1be739d7f8148826bedd46b3f662ecfe05ad46b67c", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "5075546c92574660c0edb039ff5b78c267c9dfbb372ca89a9b7487ab43947e01", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d", + "source_completion_sha256": "535fea9c295e324b6614c71eeb6e56f8304ee8d168dddd724d93149020a06dba", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "22a97bfee4be839b24bba2990225421f6864528da5588ad59d23cafae4a7bf4b", + "is_fork": true, + "learner_path": "tasks/cfbfcdb7704d2b47a19931a3/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "82c507cd8533e0f0975e86b6f20aa802f9f5e23726bf98648e36e5ffb2a57f11", + "provenance_path": "tasks/cfbfcdb7704d2b47a19931a3/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "847515f1ec7cf0a3e76b4e89f1c26198c4cf0519", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky", + "task_sha256": "28af98c3ad20f79631e694193f4fd20fc4dd73f46175235e3b283a5216a4323e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/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/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71d9a28ed9c8876a69a6ac310593fd6cb26c5744 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/instruction.md @@ -0,0 +1,38 @@ +Array index extraction returns incorrect tokens + +#### Description + +When parsing SQL identifiers with array indices, the `get_array_indices()` method returns incorrect tokens. Instead of extracting just the content inside square brackets, it's including the opening bracket and excluding the closing bracket. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple array index +p = sqlparse.parse('col[1]')[0].tokens +identifier = p[0] +indices = list(identifier.get_array_indices()) +print("Expected: '1'") +print(f"Actual: '{indices[0][0].value}'") + +# Schema qualified array index +p = sqlparse.parse('schema.col[1]')[0].tokens +identifier = p[0] +indices = list(identifier.get_array_indices()) +print("Expected: '1'") +print(f"Actual: '{indices[0][0].value}'") + +# Aliased array index +p = sqlparse.parse('col[1] x')[0].tokens +identifier = p[0] +indices = list(identifier.get_array_indices()) +print("Expected: '1'") +print(f"Actual: '{indices[0][0].value}'") +``` + +The method should return the tokens representing the array index content (e.g., '1'), but instead returns tokens that include the opening bracket. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..6eabaa9a3862367f4ffab849fa53c2956210aaa9 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "847515f1ec7cf0a3e76b4e89f1c26198c4cf0519", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_format.py", + "/testbed/tests/test_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_regressions.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_parse.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": [ + "sqlparse/sql.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 923190, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "22a97bfee4be839b24bba2990225421f6864528da5588ad59d23cafae4a7bf4b", + "is_fork": true, + "learner_path": "tasks/cfbfcdb7704d2b47a19931a3/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "82c507cd8533e0f0975e86b6f20aa802f9f5e23726bf98648e36e5ffb2a57f11", + "provenance_path": "tasks/cfbfcdb7704d2b47a19931a3/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "847515f1ec7cf0a3e76b4e89f1c26198c4cf0519", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky", + "task_sha256": "28af98c3ad20f79631e694193f4fd20fc4dd73f46175235e3b283a5216a4323e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..7632fb4c575a5b6de76e6d2495e16254994167c0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "c2db1a5d5faa728cd7c8fe1be739d7f8148826bedd46b3f662ecfe05ad46b67c", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "535fea9c295e324b6614c71eeb6e56f8304ee8d168dddd724d93149020a06dba", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "8cec1a84eb63090a7ace3c4260fe6ab38a1f3c6853a76f62548e414a36d29d69", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "22a97bfee4be839b24bba2990225421f6864528da5588ad59d23cafae4a7bf4b", + "is_fork": true, + "learner_path": "tasks/cfbfcdb7704d2b47a19931a3/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "82c507cd8533e0f0975e86b6f20aa802f9f5e23726bf98648e36e5ffb2a57f11", + "provenance_path": "tasks/cfbfcdb7704d2b47a19931a3/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d2dc9af40ebbd7e109b5c549fd80de8e9bcbee2d", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "847515f1ec7cf0a3e76b4e89f1c26198c4cf0519", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky", + "task_sha256": "28af98c3ad20f79631e694193f4fd20fc4dd73f46175235e3b283a5216a4323e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..b3fa0856b57540a674f5e4ed7a874034162c053d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/provided-gold.diff @@ -0,0 +1,15 @@ +diff --git a/sqlparse/sql.py b/sqlparse/sql.py +index 76f7f9caabd3583f7deec7a5698b731e962c13af..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -472,8 +472,8 @@ + + for token in self.tokens: + if isinstance(token, SquareBrackets): +- # Use incorrect slicing to alter the extraction logic +- yield token.tokens[0:-2] ++ # Use [1:-1] index to discard the square brackets ++ yield token.tokens[1:-1] + + + class IdentifierList(TokenList): diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c0b7c74e0bd25036047598f9f2c5d8a995cec172 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/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/sqlparse/sql.py b/sqlparse/sql.py +index 76f7f9caabd3583f7deec7a5698b731e962c13af..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -472,8 +472,8 @@ + + for token in self.tokens: + if isinstance(token, SquareBrackets): +- # Use incorrect slicing to alter the extraction logic +- yield token.tokens[0:-2] ++ # Use [1:-1] index to discard the square brackets ++ yield token.tokens[1:-1] + + + class IdentifierList(TokenList): +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/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e220927ed3eb50b4364ee632791c6446e187fa6f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/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:4768b096a82c07f82dfe781c4846d60bca52b7d8427d0543a8452d457d4f0fb2" +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/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/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/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..22f54c8933766aaed115ecd8dfa0961d8972f29f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/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/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/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/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0zb7o5ky/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..7c66675e79f0c7339adb4a5de0637632f8e4059f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "3c81cc2ef276b925c517242e9d19129e9906877d0200f487d14bb9a2fdcd5bed", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "c236f121e6c24379d4705aceee5ccdeb8ec86952b1a4f06a5e89f83cc1ff95cf", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "b86a3f678686d78a782f5d5ec526a84a70546983", + "source_completion_sha256": "ce6e6cd20a26072d7e7866aeb6966ffa5792eb15ba2e32827d66a72a8e64e007", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__157dald0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f7d6a320a218cbb2e9429d5a1c7964440eccb242bf11f0232e92504d2a323022", + "is_fork": true, + "learner_path": "tasks/670d4fb884f2f745f52aa91e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/b86a3f678686d78a782f5d5ec526a84a70546983/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "2443a27500dc87c566f20dc626a7eb6b7256e3ac992317c25b24cb6dda44b243", + "provenance_path": "tasks/670d4fb884f2f745f52aa91e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b86a3f678686d78a782f5d5ec526a84a70546983", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "da5f664f8d87cb8782bc1a19ca06427d54248be7", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__157dald0", + "task_sha256": "e70a6c58a86e8a35295dd362dd6ac71301ea956d9a6ea1b3f7d1273fb8cc5bd5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__157dald0", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/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/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9c959f421dc3b26f45eed3a9d46ac1e17bd27c62 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/instruction.md @@ -0,0 +1,29 @@ +Identifier.get_ordering() returns empty string instead of None when no ordering is present + +#### Description + +When calling `get_ordering()` on an identifier that doesn't have an ordering clause, the method returns an empty string `''` instead of `None`. This breaks existing code that expects `None` when no ordering is specified. + +#### Steps/Code to Reproduce + +```python +import sqlparse +from sqlparse import sql + +# Parse a query with mixed ordering +p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] +ids = list(p.tokens[-1].get_identifiers()) + +# This should return None for identifiers without ordering +print("c2 ordering:", repr(ids[1].get_ordering())) # Expected: None, Actual: '' +print("c3 ordering:", repr(ids[2].get_ordering())) # Expected: None, Actual: '' + +# Compare with identifier that has ordering +print("c1 ordering:", repr(ids[0].get_ordering())) # Expected: 'DESC', Actual: 'desc' +``` + +The method now returns an empty string for identifiers without ordering instead of the expected `None` value. This change in behavior can break code that relies on checking for `None` to determine if an ordering clause is present. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..c2173cb35f0fe7d98ddc16e0665e4347b01a6ce7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_grouping.py::test_identifier_consumes_ordering" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "da5f664f8d87cb8782bc1a19ca06427d54248be7", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "b86a3f678686d78a782f5d5ec526a84a70546983" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_format.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_parse.py", + "/testbed/tests/test_regressions.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/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": [ + "sqlparse/sql.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 917556, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__157dald0", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__157dald0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f7d6a320a218cbb2e9429d5a1c7964440eccb242bf11f0232e92504d2a323022", + "is_fork": true, + "learner_path": "tasks/670d4fb884f2f745f52aa91e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/b86a3f678686d78a782f5d5ec526a84a70546983/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "2443a27500dc87c566f20dc626a7eb6b7256e3ac992317c25b24cb6dda44b243", + "provenance_path": "tasks/670d4fb884f2f745f52aa91e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b86a3f678686d78a782f5d5ec526a84a70546983", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "da5f664f8d87cb8782bc1a19ca06427d54248be7", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__157dald0", + "task_sha256": "e70a6c58a86e8a35295dd362dd6ac71301ea956d9a6ea1b3f7d1273fb8cc5bd5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..4c76138cb08e4d4a242dd63fdc15be14c5549e36 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "3c81cc2ef276b925c517242e9d19129e9906877d0200f487d14bb9a2fdcd5bed", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/b86a3f678686d78a782f5d5ec526a84a70546983/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "ce6e6cd20a26072d7e7866aeb6966ffa5792eb15ba2e32827d66a72a8e64e007", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "4ba807687588cdd6acf9b589cc88d9c1fcb3e5be9c1eba2232c35baf2919594e", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__157dald0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f7d6a320a218cbb2e9429d5a1c7964440eccb242bf11f0232e92504d2a323022", + "is_fork": true, + "learner_path": "tasks/670d4fb884f2f745f52aa91e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/b86a3f678686d78a782f5d5ec526a84a70546983/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "2443a27500dc87c566f20dc626a7eb6b7256e3ac992317c25b24cb6dda44b243", + "provenance_path": "tasks/670d4fb884f2f745f52aa91e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b86a3f678686d78a782f5d5ec526a84a70546983", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "da5f664f8d87cb8782bc1a19ca06427d54248be7", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__157dald0", + "task_sha256": "e70a6c58a86e8a35295dd362dd6ac71301ea956d9a6ea1b3f7d1273fb8cc5bd5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..1095c413b2df8f6e928b7c44cbd2a21dd8c4a28c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/sqlparse/sql.py b/sqlparse/sql.py +index 26fb1ec717790fc904c1f00fd653a55e5938e631..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -465,7 +465,7 @@ + def get_ordering(self): + """Returns the ordering or ``None`` as uppercase string.""" + _, ordering = self.token_next_by(t=T.Keyword.Order) +- return ordering.normalized.lower() if ordering else '' ++ return ordering.normalized if ordering else None + + def get_array_indices(self): + """Returns an iterator of index token lists""" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..51ce503547824b271bae584f33d2ff6522a3dab4 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/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/sqlparse/sql.py b/sqlparse/sql.py +index 26fb1ec717790fc904c1f00fd653a55e5938e631..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -465,7 +465,7 @@ + def get_ordering(self): + """Returns the ordering or ``None`` as uppercase string.""" + _, ordering = self.token_next_by(t=T.Keyword.Order) +- return ordering.normalized.lower() if ordering else '' ++ return ordering.normalized if ordering else None + + def get_array_indices(self): + """Returns an iterator of index token lists""" +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/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf2730da8cb70963f72ddfe99a7026e26164cdfe --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/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:632b2ae72d6a7bc4d24daaaa04c49579531efeffa4b7c8df37d659fc79f0b264" +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/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/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/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..a13d856a4585bec335c21570d994c58aedd399cd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_grouping.py::test_identifier_consumes_ordering" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/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/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/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/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__157dald0/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..6e1bf2fcd564b8164398a4e5c7b535f6470d141c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "880fde9e5c05693ae78321b95e9740f5bcdb8cc3a494dc7b247976cd166a414c", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "6ad4d6b3bfb027e5fc352d85eff025c142fd1584b753d728d963a4837df4ef52", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "dc43a3452988dace961c4432a73c14315e123f76", + "source_completion_sha256": "f590719bad12fa99c47bc68c3cad0f16aca76864558b24206ed9a414561f58f9", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f8a802b0742d306f3fe5cfb220c239075b82ff961a443be395ec7ad1fe2257ce", + "is_fork": true, + "learner_path": "tasks/2a68436645b4c5c49c890c25/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/dc43a3452988dace961c4432a73c14315e123f76/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "11f355e92eb7f150911e95785ed2ec85c61731ec67329b60146348377d94b4dc", + "provenance_path": "tasks/2a68436645b4c5c49c890c25/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "dc43a3452988dace961c4432a73c14315e123f76", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "43a4c0310e0686d3715125967b170e6e45f3265b", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx", + "task_sha256": "c250ad6abf257ca2d881541cb62ed6a9fa01e345c8b4405c2a0efe5a93378dc4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/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/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb26e0d7a0aac63f1fb2cfe6c438d0cba1e116bb --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/instruction.md @@ -0,0 +1,32 @@ +SQL function parsing broken after recent changes + +#### Description + +SQL function parsing appears to be completely broken. Simple queries with function calls are not being parsed correctly anymore. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple function call parsing +sql = "SELECT COUNT(*) FROM table" +parsed = sqlparse.parse(sql)[0] +print(parsed.tokens) + +# Function with alias +sql2 = "SELECT COUNT(*) as total FROM table" +parsed2 = sqlparse.parse(sql2)[0] +print(parsed2.tokens) + +# More complex function usage +sql3 = "select 'abc' as foo, coalesce(col1, col2)||col3 as bar,col3 from my_table" +formatted = sqlparse.format(sql3, reindent=True) +print(formatted) +``` + +The function parsing logic seems to have regressed and is not identifying function calls properly. This affects basic SQL parsing functionality across the board. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..3fcc41bfa1bad98d391f718cff3e6e7b6bba3cc8 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_tokenize.py::test_parse_window_as" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "43a4c0310e0686d3715125967b170e6e45f3265b", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "dc43a3452988dace961c4432a73c14315e123f76" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_format.py", + "tests/test_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.py", + "tests/test_tokenize.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": [ + "sqlparse/engine/grouping.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 849523, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f8a802b0742d306f3fe5cfb220c239075b82ff961a443be395ec7ad1fe2257ce", + "is_fork": true, + "learner_path": "tasks/2a68436645b4c5c49c890c25/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/dc43a3452988dace961c4432a73c14315e123f76/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "11f355e92eb7f150911e95785ed2ec85c61731ec67329b60146348377d94b4dc", + "provenance_path": "tasks/2a68436645b4c5c49c890c25/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "dc43a3452988dace961c4432a73c14315e123f76", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "43a4c0310e0686d3715125967b170e6e45f3265b", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx", + "task_sha256": "c250ad6abf257ca2d881541cb62ed6a9fa01e345c8b4405c2a0efe5a93378dc4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..a142981f2c72e5476dd7575ff093d007c63b3902 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "880fde9e5c05693ae78321b95e9740f5bcdb8cc3a494dc7b247976cd166a414c", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/dc43a3452988dace961c4432a73c14315e123f76/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "f590719bad12fa99c47bc68c3cad0f16aca76864558b24206ed9a414561f58f9", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "1dd120a78a788b5e62fcf50ece66e066565609b75369060e120768f8d79c71aa", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f8a802b0742d306f3fe5cfb220c239075b82ff961a443be395ec7ad1fe2257ce", + "is_fork": true, + "learner_path": "tasks/2a68436645b4c5c49c890c25/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/dc43a3452988dace961c4432a73c14315e123f76/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "11f355e92eb7f150911e95785ed2ec85c61731ec67329b60146348377d94b4dc", + "provenance_path": "tasks/2a68436645b4c5c49c890c25/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "dc43a3452988dace961c4432a73c14315e123f76", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "43a4c0310e0686d3715125967b170e6e45f3265b", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx", + "task_sha256": "c250ad6abf257ca2d881541cb62ed6a9fa01e345c8b4405c2a0efe5a93378dc4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..d93929d4e53ccb2dfa5ebb5f4afa34a0701a1b13 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/provided-gold.diff @@ -0,0 +1,39 @@ +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 2123a8f5dc23dd86db5f5278f82b417474df4b43..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -356,27 +356,27 @@ + def group_functions(tlist): + has_create = False + has_table = False +- has_as = True ++ has_as = False + for tmp_token in tlist.tokens: + if tmp_token.value.upper() == 'CREATE': + has_create = True + if tmp_token.value.upper() == 'TABLE': + has_table = True +- if tmp_token.value.upper() == 'AS': +- has_as = False +- if has_create or has_table or has_as: ++ if tmp_token.value == 'AS': ++ has_as = True ++ if has_create and has_table and not has_as: + return + + tidx, token = tlist.token_next_by(t=T.Name) + while token: + nidx, next_ = tlist.token_next(tidx) +- if not isinstance(next_, sql.Parenthesis): ++ if isinstance(next_, sql.Parenthesis): + over_idx, over = tlist.token_next(nidx) +- if over and isinstance(over, sql.Function): ++ if over and isinstance(over, sql.Over): + eidx = over_idx + else: + eidx = nidx +- tlist.group_tokens(sql.Over, tidx, eidx) ++ tlist.group_tokens(sql.Function, tidx, eidx) + tidx, token = tlist.token_next_by(t=T.Name, idx=tidx) + + diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..83edd7af36457c3946ff5f8a98f00bc35419ccc5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/solution/solve.sh @@ -0,0 +1,45 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 2123a8f5dc23dd86db5f5278f82b417474df4b43..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -356,27 +356,27 @@ + def group_functions(tlist): + has_create = False + has_table = False +- has_as = True ++ has_as = False + for tmp_token in tlist.tokens: + if tmp_token.value.upper() == 'CREATE': + has_create = True + if tmp_token.value.upper() == 'TABLE': + has_table = True +- if tmp_token.value.upper() == 'AS': +- has_as = False +- if has_create or has_table or has_as: ++ if tmp_token.value == 'AS': ++ has_as = True ++ if has_create and has_table and not has_as: + return + + tidx, token = tlist.token_next_by(t=T.Name) + while token: + nidx, next_ = tlist.token_next(tidx) +- if not isinstance(next_, sql.Parenthesis): ++ if isinstance(next_, sql.Parenthesis): + over_idx, over = tlist.token_next(nidx) +- if over and isinstance(over, sql.Function): ++ if over and isinstance(over, sql.Over): + eidx = over_idx + else: + eidx = nidx +- tlist.group_tokens(sql.Over, tidx, eidx) ++ tlist.group_tokens(sql.Function, tidx, eidx) + tidx, token = tlist.token_next_by(t=T.Name, idx=tidx) + + +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/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..540830402b46e057c36e24ed375222ef59dc19c9 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/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:0f385188f9283936cdd36f2890580d32ac98fa7b8fa09314d11cd75d068d6114" +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/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/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/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..b8958255b88c555355f42e9765ddedb04b1b88f9 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_tokenize.py::test_parse_window_as" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/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/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/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/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18agwlyx/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..60c699277862e506f7aaa31881ca6680119f4f5e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "9185bcdc27194418fb0fb531cb69eb5069c96e9ea67b7bd9a0b898ef9fa16952", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "cdf1bb740002e4500987991e9a552da46e9f6efc072b8b46a863f4cf1e48460a", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "cc2442bd28cacebe5bbb32216988166030c25a95", + "source_completion_sha256": "d5564566733c2ee27738d2c7810aad5586f2203dff254dfa1042f501a675ee47", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "5d877486bfb00b4427925701f82e95d02e0044d95e103b0f7c8e5f145c51874e", + "is_fork": true, + "learner_path": "tasks/2c54df91df874928e24665d2/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/cc2442bd28cacebe5bbb32216988166030c25a95/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "b9d06895c19d17336bf0a349d9c2476bb362dd06a8acfe09869c8c026baaf0ce", + "provenance_path": "tasks/2c54df91df874928e24665d2/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "cc2442bd28cacebe5bbb32216988166030c25a95", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "759f8971885aa4caab181eeba67f1b606a7e593c", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l", + "task_sha256": "bdea37becf9d00c0c5abc2006695cf2814ae62e068b559fb8b412f9ec01f9793", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/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/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db1b470a06d37d26531b4155d8473e9ac2a85927 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/instruction.md @@ -0,0 +1,24 @@ +Token.has_ancestor() method returns incorrect results + +Description + +The `has_ancestor()` method in the `Token` class appears to be returning incorrect results when checking if a token is in another token's ancestry. + +For example, when checking if a token has a specific ancestor in a parsed SQL statement: + +```python +s = 'foo or (bar, baz)' +p = sqlparse.parse(s)[0] +baz = p.tokens[-1].tokens[1].tokens[-1] +print(baz.has_ancestor(p.tokens[-1].tokens[1])) # Should be True, returns False +print(baz.has_ancestor(p.tokens[-1])) # Should be True, returns False +print(baz.has_ancestor(p)) # Should be True, returns False +``` + +The method is returning `False` for all checks, even though the token is clearly in the ancestry chain. This breaks code that relies on proper ancestry checking. + +The issue appears to be in the implementation of the `has_ancestor()` method, which is not correctly traversing the parent chain. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..b0ee864bd505799e90715a38cfdb4095cc0f0c21 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_parse.py::test_parse_has_ancestor" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "759f8971885aa4caab181eeba67f1b606a7e593c", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "cc2442bd28cacebe5bbb32216988166030c25a95" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_format.py", + "/testbed/tests/test_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_regressions.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_parse.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": [ + "sqlparse/sql.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 923182, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "5d877486bfb00b4427925701f82e95d02e0044d95e103b0f7c8e5f145c51874e", + "is_fork": true, + "learner_path": "tasks/2c54df91df874928e24665d2/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/cc2442bd28cacebe5bbb32216988166030c25a95/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "b9d06895c19d17336bf0a349d9c2476bb362dd06a8acfe09869c8c026baaf0ce", + "provenance_path": "tasks/2c54df91df874928e24665d2/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "cc2442bd28cacebe5bbb32216988166030c25a95", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "759f8971885aa4caab181eeba67f1b606a7e593c", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l", + "task_sha256": "bdea37becf9d00c0c5abc2006695cf2814ae62e068b559fb8b412f9ec01f9793", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..98a7828a4ffb2a47f482ed9c3c90d94824303e1b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "9185bcdc27194418fb0fb531cb69eb5069c96e9ea67b7bd9a0b898ef9fa16952", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/cc2442bd28cacebe5bbb32216988166030c25a95/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "d5564566733c2ee27738d2c7810aad5586f2203dff254dfa1042f501a675ee47", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "22ca1c425036a2fa5f653e607e565f655cf7ab295b850a0c224a1c1c3d35ccfc", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "5d877486bfb00b4427925701f82e95d02e0044d95e103b0f7c8e5f145c51874e", + "is_fork": true, + "learner_path": "tasks/2c54df91df874928e24665d2/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/cc2442bd28cacebe5bbb32216988166030c25a95/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "b9d06895c19d17336bf0a349d9c2476bb362dd06a8acfe09869c8c026baaf0ce", + "provenance_path": "tasks/2c54df91df874928e24665d2/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "cc2442bd28cacebe5bbb32216988166030c25a95", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "759f8971885aa4caab181eeba67f1b606a7e593c", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l", + "task_sha256": "bdea37becf9d00c0c5abc2006695cf2814ae62e068b559fb8b412f9ec01f9793", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..1f039944e8d88084e1c4938500f11e21945fbc24 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/provided-gold.diff @@ -0,0 +1,18 @@ +diff --git a/sqlparse/sql.py b/sqlparse/sql.py +index 3e89fec297a433df4c6a1dfe864fc105428c09b8..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -142,10 +142,10 @@ + """Returns ``True`` if *other* is in this tokens ancestry.""" + parent = self.parent + while parent: +- if parent != other: +- return False ++ if parent == other: ++ return True + parent = parent.parent +- return True ++ return False + + + class TokenList(Token): diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c565a1409d481625aca6ca8eaef1076bdd89944d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/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/sqlparse/sql.py b/sqlparse/sql.py +index 3e89fec297a433df4c6a1dfe864fc105428c09b8..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -142,10 +142,10 @@ + """Returns ``True`` if *other* is in this tokens ancestry.""" + parent = self.parent + while parent: +- if parent != other: +- return False ++ if parent == other: ++ return True + parent = parent.parent +- return True ++ return False + + + class TokenList(Token): +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/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dfbfd2dbe199e66a163088fd50083bb233e84cb8 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/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:8c5d124e8b82dbf12f7e9327985b6d3acd5c9e23aaaaed7d1cdd92cba2aa0271" +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/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/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/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..758b7815aa5e15817a9a6af1c2c5a58f2b5517dd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_parse.py::test_parse_has_ancestor" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/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/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/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/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__18nuk53l/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..837a92dea5bac3a3d3c9f8b2e6e7d5fd04a05618 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "15f62007c13de540a7901f5ceb545f5286b7f5655c46e91640e5b6e0f3123cf7", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "2cf144c192d8a1ca87edeb33f82270efaa97f3219d973651e688859ce3a27153", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0", + "source_completion_sha256": "d811abe12103b0fdcae1800cb13346f4844848290624ddc8e9093a4659e75d89", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "527d26ff3479846d9e17a8e78bb3f2dfc2eeea0265f60a516c0b7368a9ecbc67", + "is_fork": true, + "learner_path": "tasks/be61703b2a6904b7d9411c3b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "2e830482c4110f6d4103e090b8356fc0b87f480e15f8a9b2a713d54410e56ea0", + "provenance_path": "tasks/be61703b2a6904b7d9411c3b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ee7aa8e920afcd46475b3713a20bfe543f2a7460", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf", + "task_sha256": "0d62ab09567f97f786bc5fd8ffb5d15a706b59e0a40190bba2a4fb4809bb6d2e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/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/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..808e9a46ae572527418c6a62e9cf741503c7203b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/instruction.md @@ -0,0 +1,37 @@ +AlignedIndentFilter produces incorrect indentation with extra spaces + +#### Description + +The AlignedIndentFilter is adding too many spaces when formatting SQL statements, causing misaligned output that doesn't match expected formatting. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +sql = """ +select a, +case when a = 0 +then 1 +when bb = 1 then 1 +when c = 2 then 2 +else 0 end as d, +extra_col +from table +where c is true +and b between 3 and 4 +""" + +formatted = sqlparse.format(sql, reindent_aligned=True) +print(formatted) +``` + +The output has excessive indentation with extra spaces compared to what should be expected for aligned formatting. + +#### Expected vs Actual + +Expected aligned formatting should have consistent spacing, but the current output includes additional spaces that break the alignment pattern. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..974b3cba19c60aaef6200e194e29d735de4b0e8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "ee7aa8e920afcd46475b3713a20bfe543f2a7460", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_parse.py", + "/testbed/tests/test_regressions.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_format.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": [ + "sqlparse/filters/aligned_indent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 912883, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "527d26ff3479846d9e17a8e78bb3f2dfc2eeea0265f60a516c0b7368a9ecbc67", + "is_fork": true, + "learner_path": "tasks/be61703b2a6904b7d9411c3b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "2e830482c4110f6d4103e090b8356fc0b87f480e15f8a9b2a713d54410e56ea0", + "provenance_path": "tasks/be61703b2a6904b7d9411c3b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ee7aa8e920afcd46475b3713a20bfe543f2a7460", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf", + "task_sha256": "0d62ab09567f97f786bc5fd8ffb5d15a706b59e0a40190bba2a4fb4809bb6d2e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..4900c3504f65f72182c725d0391ff258094b3069 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "15f62007c13de540a7901f5ceb545f5286b7f5655c46e91640e5b6e0f3123cf7", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "d811abe12103b0fdcae1800cb13346f4844848290624ddc8e9093a4659e75d89", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "663ecdb0696bccadafe1e800e6038da46205e91db2a060442e8fc5c3f00d047f", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "527d26ff3479846d9e17a8e78bb3f2dfc2eeea0265f60a516c0b7368a9ecbc67", + "is_fork": true, + "learner_path": "tasks/be61703b2a6904b7d9411c3b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "2e830482c4110f6d4103e090b8356fc0b87f480e15f8a9b2a713d54410e56ea0", + "provenance_path": "tasks/be61703b2a6904b7d9411c3b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "587216c69e4a8cf0ffaa804b0d0a26b7bc1bf3c0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ee7aa8e920afcd46475b3713a20bfe543f2a7460", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf", + "task_sha256": "0d62ab09567f97f786bc5fd8ffb5d15a706b59e0a40190bba2a4fb4809bb6d2e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..da2573e68b0564404a3a5228417a9c7a0cd71ba6 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/provided-gold.diff @@ -0,0 +1,21 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 65997c98f367b44a7e22b8507b7a56d1e28520a8..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -29,11 +29,13 @@ + self._max_kwd_len = len('select') + + def nl(self, offset=1): +- offset = len(offset) if not isinstance(offset, int) else offset +- indent = (self.indent + 1) * (2 + self._max_kwd_len) ++ # offset = 1 represent a single space after SELECT ++ offset = -len(offset) if not isinstance(offset, int) else offset ++ # add two for the space and parenthesis ++ indent = self.indent * (2 + self._max_kwd_len) + + return sql.Token(T.Whitespace, self.n + self.char * ( +- self._max_kwd_len + offset + indent + self.offset + 1)) ++ self._max_kwd_len + offset + indent + self.offset)) + + def _process_statement(self, tlist): + if len(tlist.tokens) > 0 and tlist.tokens[0].is_whitespace \ diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..787d235dd4a26c02546a45f8271e4d646273fbee --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/solution/solve.sh @@ -0,0 +1,27 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 65997c98f367b44a7e22b8507b7a56d1e28520a8..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -29,11 +29,13 @@ + self._max_kwd_len = len('select') + + def nl(self, offset=1): +- offset = len(offset) if not isinstance(offset, int) else offset +- indent = (self.indent + 1) * (2 + self._max_kwd_len) ++ # offset = 1 represent a single space after SELECT ++ offset = -len(offset) if not isinstance(offset, int) else offset ++ # add two for the space and parenthesis ++ indent = self.indent * (2 + self._max_kwd_len) + + return sql.Token(T.Whitespace, self.n + self.char * ( +- self._max_kwd_len + offset + indent + self.offset + 1)) ++ self._max_kwd_len + offset + indent + self.offset)) + + def _process_statement(self, tlist): + if len(tlist.tokens) > 0 and tlist.tokens[0].is_whitespace \ +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/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5417c317414314c7265e6459a4d101ab56af6457 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/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:3ad6e3e8aa83e1be4d86b63eff073da81b6b3b23e69ff92a5369643fa36fc68d" +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/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/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/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..1887a69c8aec2a77471092fd24f61667c2a39b29 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/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/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/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/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__19lkwbhf/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..e55fd8e9dc9006628de2f7a10db7f99b60558b06 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "98ad02a6b3b1679ad288f327c58707a539a3ce3648052901cecf3c280233c667", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "f82c8b0c11961aa054d265aa3d43611befc63147b36ca57b6fea802a857e60b1", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "9ae46029a04322ece79d5ca9f300375ac9a98f40", + "source_completion_sha256": "27f3c9ec61660eee8981a13954de074a1577e151e72f94f15101dc82490aaeb4", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "ae959604ef7fc5c3a8c5b8863b150e9d7ff6ae6f5d3dc50a78b370413423f109", + "is_fork": true, + "learner_path": "tasks/bb858325f0d0f5924fbdd16b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/9ae46029a04322ece79d5ca9f300375ac9a98f40/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "69b520de2f250a0cb18ca0dba8bcba7ad48c31eaef262bfb3cace8ab47f18a08", + "provenance_path": "tasks/bb858325f0d0f5924fbdd16b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9ae46029a04322ece79d5ca9f300375ac9a98f40", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e5f6e6ccf8f278661fd808c3dc8bda5698876adb", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj", + "task_sha256": "d7d338c7645030594223d6c6bfe22f0742668777c61a2afb29447c55efee784d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/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/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0b4ee1cc934aea5bab330a467158e8ed205685e0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/instruction.md @@ -0,0 +1,55 @@ +# Pretty-print tree representation is broken in TokenList._pprint_tree + +## Description + +I've noticed that the pretty-print tree representation in `TokenList._pprint_tree` is not working correctly. The tree structure is displayed incorrectly and the representation of tokens is mixed up. + +Given the following SQL: + +```sql +SELECT * FROM users WHERE id = 1 +``` + +When I try to pretty-print the parsed SQL tree, the output is incorrect. The class name and value are swapped, and the tree structure doesn't display properly. + +## Steps to reproduce + +```python +import sqlparse +from io import StringIO + +sql = "SELECT * FROM users WHERE id = 1" +parsed = sqlparse.parse(sql)[0] + +# Print the tree representation +output = StringIO() +parsed._pprint_tree(max_depth=None, depth=0, f=output) +print(output.getvalue()) +``` + +## Expected behavior + +The output should show a properly formatted tree with correct indentation and structure, where: +- The class name and value are displayed correctly +- The tree structure uses the correct characters (`|-` for non-last items and `` `- `` for the last item) +- The parent-child relationships are properly indented + +## Actual behavior + +The output shows: +- Class name and value are swapped +- The tree structure is incorrect with wrong indentation +- The parent-child relationships are not properly displayed +- The quotes around values are not consistently applied + +Additionally, when traversing deeper into the tree, the depth calculation seems to be incorrect, causing the tree to be truncated or displayed improperly. + +## Environment + +- sqlparse version: [version] +- Python version: [version] +- OS: [operating system] + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..069eb2cf91de6b6cd2803b2ebda088971bf20c86 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_parse.py::test_pprint" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "e5f6e6ccf8f278661fd808c3dc8bda5698876adb", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "9ae46029a04322ece79d5ca9f300375ac9a98f40" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_format.py", + "/testbed/tests/test_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_regressions.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_parse.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": [ + "sqlparse/sql.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 923144, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "ae959604ef7fc5c3a8c5b8863b150e9d7ff6ae6f5d3dc50a78b370413423f109", + "is_fork": true, + "learner_path": "tasks/bb858325f0d0f5924fbdd16b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/9ae46029a04322ece79d5ca9f300375ac9a98f40/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "69b520de2f250a0cb18ca0dba8bcba7ad48c31eaef262bfb3cace8ab47f18a08", + "provenance_path": "tasks/bb858325f0d0f5924fbdd16b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9ae46029a04322ece79d5ca9f300375ac9a98f40", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e5f6e6ccf8f278661fd808c3dc8bda5698876adb", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj", + "task_sha256": "d7d338c7645030594223d6c6bfe22f0742668777c61a2afb29447c55efee784d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..c7056b1530120fa877728497fc2f07df01b2749e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "98ad02a6b3b1679ad288f327c58707a539a3ce3648052901cecf3c280233c667", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/9ae46029a04322ece79d5ca9f300375ac9a98f40/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "27f3c9ec61660eee8981a13954de074a1577e151e72f94f15101dc82490aaeb4", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "c5c918bdff293af5f92f905882dd299927bde39bafb14d67222ca0956448a013", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "ae959604ef7fc5c3a8c5b8863b150e9d7ff6ae6f5d3dc50a78b370413423f109", + "is_fork": true, + "learner_path": "tasks/bb858325f0d0f5924fbdd16b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/9ae46029a04322ece79d5ca9f300375ac9a98f40/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "69b520de2f250a0cb18ca0dba8bcba7ad48c31eaef262bfb3cace8ab47f18a08", + "provenance_path": "tasks/bb858325f0d0f5924fbdd16b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9ae46029a04322ece79d5ca9f300375ac9a98f40", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e5f6e6ccf8f278661fd808c3dc8bda5698876adb", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj", + "task_sha256": "d7d338c7645030594223d6c6bfe22f0742668777c61a2afb29447c55efee784d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..ab1efb4ba99a2258fd50e384807ef26dfa6ae145 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/provided-gold.diff @@ -0,0 +1,34 @@ +diff --git a/sqlparse/sql.py b/sqlparse/sql.py +index 437e2465a1b671acb2a957c61e39af1cd2261621..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -183,19 +183,19 @@ + """Pretty-print the object tree.""" + token_count = len(self.tokens) + for idx, token in enumerate(self.tokens): +- cls = token._get_repr_value() +- value = token._get_repr_name() +- +- last = idx != (token_count - 1) +- pre = '|- ' if last else '`- ' +- +- q = '"' if value.startswith("'") else "'" ++ cls = token._get_repr_name() ++ value = token._get_repr_value() ++ ++ last = idx == (token_count - 1) ++ pre = '`- ' if last else '|- ' ++ ++ q = '"' if value.startswith("'") and value.endswith("'") else "'" + print("{_pre}{pre}{idx} {cls} {q}{value}{q}" + .format(**locals()), file=f) + +- if token.is_group and (max_depth is not None and depth < max_depth): +- parent_pre = '| ' if last else ' ' +- token._pprint_tree(max_depth, depth - 1, f, _pre + parent_pre) ++ if token.is_group and (max_depth is None or depth < max_depth): ++ parent_pre = ' ' if last else '| ' ++ token._pprint_tree(max_depth, depth + 1, f, _pre + parent_pre) + + def get_token_at_offset(self, offset): + """Returns the token that is on position offset.""" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b00be6e52364fb5bee3589ef4b164e1c300b4367 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/solution/solve.sh @@ -0,0 +1,40 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/sql.py b/sqlparse/sql.py +index 437e2465a1b671acb2a957c61e39af1cd2261621..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -183,19 +183,19 @@ + """Pretty-print the object tree.""" + token_count = len(self.tokens) + for idx, token in enumerate(self.tokens): +- cls = token._get_repr_value() +- value = token._get_repr_name() +- +- last = idx != (token_count - 1) +- pre = '|- ' if last else '`- ' +- +- q = '"' if value.startswith("'") else "'" ++ cls = token._get_repr_name() ++ value = token._get_repr_value() ++ ++ last = idx == (token_count - 1) ++ pre = '`- ' if last else '|- ' ++ ++ q = '"' if value.startswith("'") and value.endswith("'") else "'" + print("{_pre}{pre}{idx} {cls} {q}{value}{q}" + .format(**locals()), file=f) + +- if token.is_group and (max_depth is not None and depth < max_depth): +- parent_pre = '| ' if last else ' ' +- token._pprint_tree(max_depth, depth - 1, f, _pre + parent_pre) ++ if token.is_group and (max_depth is None or depth < max_depth): ++ parent_pre = ' ' if last else '| ' ++ token._pprint_tree(max_depth, depth + 1, f, _pre + parent_pre) + + def get_token_at_offset(self, offset): + """Returns the token that is on position offset.""" +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/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0ac17d07307bbfcdd69a3a3f62abbe62bc2c6708 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/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:4274ba63028789a42087a3c1c6edba9bde5feeee7f3e83d2782ac5242b062535" +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/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/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/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..189ef4020bffe6fa8a7ecf747a2086b61da3db86 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_parse.py::test_pprint" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/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/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/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/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1ivqwigj/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..9d98bcead2308d513f2252a7794f80e08090916d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "9b506af2c37927ad081f48f660c7989474ff449cfa176f897e58b0ed3e812347", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "ab546f72518983bc63091b5fbcd14c9c048edcc074bf80e9bb3309305c73c094", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "48b1883e9f117b04b154ec9afda1fc48eb7aab32", + "source_completion_sha256": "a4282bff13f4e42c1028f3ae8edcda43546054f119f3be8c311e759ac2c6678c", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "5aef3c8a8f2727a07e9caa680474130a79fb8019da15e0790f4106fab660e8c4", + "is_fork": true, + "learner_path": "tasks/972b5f20406dc33975b540d0/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/48b1883e9f117b04b154ec9afda1fc48eb7aab32/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "63b64aeea4f46d2dcd62d887d12af9874a7bb9034cad54e2ed8a76999b2521f4", + "provenance_path": "tasks/972b5f20406dc33975b540d0/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "48b1883e9f117b04b154ec9afda1fc48eb7aab32", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b04cac46c1012b406ee30cc6c3312c7de8d3898d", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s", + "task_sha256": "8165833964fdacd6b3fbc369e172d1a4505f992488bda35323b97628cce2a205", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/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/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71888fc30ebfe86d893b7f25bd83b494251db684 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/instruction.md @@ -0,0 +1,28 @@ +Token string representation adds unwanted trailing space + +#### Description + +When converting Token objects to strings, an extra space is being appended to the token value. This affects SQL formatting and parsing output. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple token string conversion +token = sqlparse.Token(sqlparse.tokens.Keyword, 'SELECT') +print(repr(str(token))) # Shows extra space + +# SQL formatting is affected +sql = "select foo from bar" +formatted = sqlparse.format(sql, reindent=True) +print(repr(formatted)) # Shows extra spaces throughout +``` + +Expected output should not have trailing spaces on tokens, but currently tokens are being converted to strings with an extra space character appended. + +This impacts all SQL formatting operations and token string representations throughout the library. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..7d41b4bc079ba3d12832a19db11a9ef7933170cd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_parse.py::test_pprint", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_single_quotes" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "b04cac46c1012b406ee30cc6c3312c7de8d3898d", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "48b1883e9f117b04b154ec9afda1fc48eb7aab32" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_format.py", + "tests/test_parse.py", + "tests/test_regressions.py", + "tests/test_tokenize.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": [ + "sqlparse/sql.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 873506, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "5aef3c8a8f2727a07e9caa680474130a79fb8019da15e0790f4106fab660e8c4", + "is_fork": true, + "learner_path": "tasks/972b5f20406dc33975b540d0/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/48b1883e9f117b04b154ec9afda1fc48eb7aab32/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "63b64aeea4f46d2dcd62d887d12af9874a7bb9034cad54e2ed8a76999b2521f4", + "provenance_path": "tasks/972b5f20406dc33975b540d0/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "48b1883e9f117b04b154ec9afda1fc48eb7aab32", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b04cac46c1012b406ee30cc6c3312c7de8d3898d", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s", + "task_sha256": "8165833964fdacd6b3fbc369e172d1a4505f992488bda35323b97628cce2a205", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..e596c76b6882def3c46afda14e29e62aeee22e8e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "9b506af2c37927ad081f48f660c7989474ff449cfa176f897e58b0ed3e812347", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/48b1883e9f117b04b154ec9afda1fc48eb7aab32/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "a4282bff13f4e42c1028f3ae8edcda43546054f119f3be8c311e759ac2c6678c", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "19d7b4fe1f8dfec0c92b4bf6c961dacccf477f765af9206cc9831a61a71670d4", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "5aef3c8a8f2727a07e9caa680474130a79fb8019da15e0790f4106fab660e8c4", + "is_fork": true, + "learner_path": "tasks/972b5f20406dc33975b540d0/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/48b1883e9f117b04b154ec9afda1fc48eb7aab32/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "63b64aeea4f46d2dcd62d887d12af9874a7bb9034cad54e2ed8a76999b2521f4", + "provenance_path": "tasks/972b5f20406dc33975b540d0/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "48b1883e9f117b04b154ec9afda1fc48eb7aab32", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b04cac46c1012b406ee30cc6c3312c7de8d3898d", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s", + "task_sha256": "8165833964fdacd6b3fbc369e172d1a4505f992488bda35323b97628cce2a205", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..2ad4fb8e1d313bae2f97bc2bc53162ede844414a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/sqlparse/sql.py b/sqlparse/sql.py +index ac26f7662695c5169d1dad3d234b1211d1eb910c..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -60,7 +60,7 @@ + self.normalized = value.upper() if self.is_keyword else value + + def __str__(self): +- return str(self.value) + " " ++ return self.value + + # Pending tokenlist __len__ bug fix + # def __len__(self): diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..db4974120c8b5bc9a8aeefc8a759961adb61cc56 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/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/sqlparse/sql.py b/sqlparse/sql.py +index ac26f7662695c5169d1dad3d234b1211d1eb910c..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -60,7 +60,7 @@ + self.normalized = value.upper() if self.is_keyword else value + + def __str__(self): +- return str(self.value) + " " ++ return self.value + + # Pending tokenlist __len__ bug fix + # def __len__(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/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0a495b340190301a227a4a689e62b36bc8a9fcc --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/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:89a6a76eb376749e2fc230cfdad751fc62af0431cc33151f44d2c9c08c5187d7" +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/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/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/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..4e047ade69605a69eaefd118e7b7666deb5c07ef --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_parse.py::test_pprint", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_single_quotes" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/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/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/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/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1pqgl36s/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..7dfc095762978d9999b78012e2871c631462c4d3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "5c6932fdf10c00a4229ee9e3ee7a0706864eae73ae6b2257f701a72d3044c16d", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "8b983fa32ac6e211339e0120456ae42ef1528194c6e763d15c9890a44976951e", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "9fb2b2816ebc1eebd3ade3017aa6e2de9e356031", + "source_completion_sha256": "9507d627fa70e7083de9fa2e0d079042270e5fe36aaba28e0f50484a61d5182a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "eb9fe3de40408ddb9238e4d126e536d2e967da1368f896be3660bbe3b5d25ba2", + "is_fork": true, + "learner_path": "tasks/094604b761e805e076207cd2/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/9fb2b2816ebc1eebd3ade3017aa6e2de9e356031/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "9710b03b8cc8d0954259809efa556f871aa50022836ca3bf89f7fb37e7cc894a", + "provenance_path": "tasks/094604b761e805e076207cd2/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9fb2b2816ebc1eebd3ade3017aa6e2de9e356031", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e8d2329a43d5ba311536a6a7cd2aea9613eb8981", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7", + "task_sha256": "951403b3ae464f481e92b65bf351c975be5df622df7eafe00449b8a538d45e93", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/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/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..81c825846e8608c336f8350a6db60e82831d9978 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/instruction.md @@ -0,0 +1,31 @@ +SQL keyword recognition broken - all keywords treated as identifiers + +#### Description + +SQL keywords are no longer being recognized properly by the lexer. All SQL keywords like SELECT, FROM, WHERE, etc. are being treated as regular identifiers instead of their proper keyword token types. + +#### Steps/Code to Reproduce + +```python +import sqlparse +from sqlparse import tokens as T + +# Simple SELECT statement +parsed = sqlparse.parse('SELECT * FROM table')[0] +print("Tokens:") +for token in parsed.flatten(): + print(f" {token.ttype}: '{token.value}'") + +# Expected: SELECT should be T.Keyword.DML, FROM should be T.Keyword +# Actual: Both are treated as T.Name (identifiers) +``` + +This affects all SQL parsing functionality since keywords are fundamental to SQL syntax recognition. Functions like `sqlparse.split()` and proper statement parsing fail because keywords aren't being identified correctly. + +#### Expected Behavior + +Keywords like SELECT, FROM, WHERE, INSERT, etc. should be recognized as their appropriate keyword token types (T.Keyword.DML, T.Keyword, etc.) rather than being treated as regular name tokens. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..f0e0fa14bbeb1226bac2a9b80593d1aec22f0af3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_script", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_qualified_function", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "e8d2329a43d5ba311536a6a7cd2aea9613eb8981", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "9fb2b2816ebc1eebd3ade3017aa6e2de9e356031" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_cli.py", + "tests/test_format.py", + "tests/test_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.py", + "tests/test_split.py", + "tests/test_tokenize.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": [ + "sqlparse/lexer.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 840101, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "eb9fe3de40408ddb9238e4d126e536d2e967da1368f896be3660bbe3b5d25ba2", + "is_fork": true, + "learner_path": "tasks/094604b761e805e076207cd2/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/9fb2b2816ebc1eebd3ade3017aa6e2de9e356031/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "9710b03b8cc8d0954259809efa556f871aa50022836ca3bf89f7fb37e7cc894a", + "provenance_path": "tasks/094604b761e805e076207cd2/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9fb2b2816ebc1eebd3ade3017aa6e2de9e356031", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e8d2329a43d5ba311536a6a7cd2aea9613eb8981", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7", + "task_sha256": "951403b3ae464f481e92b65bf351c975be5df622df7eafe00449b8a538d45e93", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..8124fe9917bb05c05cf302ba9a47cae8526a5c8a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "5c6932fdf10c00a4229ee9e3ee7a0706864eae73ae6b2257f701a72d3044c16d", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/9fb2b2816ebc1eebd3ade3017aa6e2de9e356031/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "9507d627fa70e7083de9fa2e0d079042270e5fe36aaba28e0f50484a61d5182a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "2c03aae03eb822f52f0ba9bcdff5aa1157515b76f6d49e92d0c071e8a6482c47", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "eb9fe3de40408ddb9238e4d126e536d2e967da1368f896be3660bbe3b5d25ba2", + "is_fork": true, + "learner_path": "tasks/094604b761e805e076207cd2/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/9fb2b2816ebc1eebd3ade3017aa6e2de9e356031/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "9710b03b8cc8d0954259809efa556f871aa50022836ca3bf89f7fb37e7cc894a", + "provenance_path": "tasks/094604b761e805e076207cd2/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9fb2b2816ebc1eebd3ade3017aa6e2de9e356031", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e8d2329a43d5ba311536a6a7cd2aea9613eb8981", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7", + "task_sha256": "951403b3ae464f481e92b65bf351c975be5df622df7eafe00449b8a538d45e93", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..90af5715d5d1200de40b63046b555e6a9a6132b7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/provided-gold.diff @@ -0,0 +1,20 @@ +diff --git a/sqlparse/lexer.py b/sqlparse/lexer.py +index 43828548fcd2221c02173a6315b808234cb48fc2..8f88d1715a6bd3a72c5d1313f40cb4b83da6c836 100644 +--- a/sqlparse/lexer.py ++++ b/sqlparse/lexer.py +@@ -97,12 +97,12 @@ + If the given value is in one of the KEYWORDS_* dictionary + it's considered a keyword. Otherwise, tokens.Name is returned. + """ +- val = value.lower() # Changed upper() to lower() ++ val = value.upper() + for kwdict in self._keywords: + if val in kwdict: +- return tokens.Name, value # Changed to always return tokens.Name when found ++ return kwdict[val], value + else: +- return kwdict[val], value # Altered to return kwdict[val] when not found ++ return tokens.Name, value + + def get_tokens(self, text, encoding=None): + """ diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..94d4c44aac6cb09c31666c66e1ed77827e95b79c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/solution/solve.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/lexer.py b/sqlparse/lexer.py +index 43828548fcd2221c02173a6315b808234cb48fc2..8f88d1715a6bd3a72c5d1313f40cb4b83da6c836 100644 +--- a/sqlparse/lexer.py ++++ b/sqlparse/lexer.py +@@ -97,12 +97,12 @@ + If the given value is in one of the KEYWORDS_* dictionary + it's considered a keyword. Otherwise, tokens.Name is returned. + """ +- val = value.lower() # Changed upper() to lower() ++ val = value.upper() + for kwdict in self._keywords: + if val in kwdict: +- return tokens.Name, value # Changed to always return tokens.Name when found ++ return kwdict[val], value + else: +- return kwdict[val], value # Altered to return kwdict[val] when not found ++ return tokens.Name, value + + def get_tokens(self, text, encoding=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/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..19e5689b2d9c9be175106d6b1a10699f473166bf --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/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:f5206d59d07eeb56f1f1e51d49665ad6905432064edee3803571202dd0279d62" +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/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/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/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..dcc5eb18c5b984eca8409b1f359f157fbefb0e37 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_script", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_qualified_function", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/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/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/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/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1upjaqs7/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..483b5290e32370989cf53a30c2c07419d8cc8d1c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "45a55fceed8188ceee8199be318ae5fbdd282af3446ff03f0da3be986382f65c", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "5165b4586c0416ba901cc0f3cd760059545ec3dfb3f053f15603b03b42717910", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f", + "source_completion_sha256": "91c161826db9efc69255c9708205cd791831ad227a7d701d2abe8a7c28f426a1", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "7f9db142ae8c7699d7fc7eea889e3928bb828f0755d0b19fe6578d82ff7ebce3", + "is_fork": true, + "learner_path": "tasks/36cbd9fe14a7ab6f1d921775/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "117db71e0861886a4428c0e379f07473692806d74331a3afa796602bd6ac2d81", + "provenance_path": "tasks/36cbd9fe14a7ab6f1d921775/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ac630103cc0e2b6a5033fca46ed5a7e19b04968f", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl", + "task_sha256": "e5445b1e8de2ea2a79e1dcc51b96ba38c23d2c72ab0a269febc34adf7ad8802b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/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/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..df43ed649fc1e5eb21d2390d99e7b3e63d5ba935 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/instruction.md @@ -0,0 +1,54 @@ +# CASE statement formatting broken in AlignedIndentFilter + +When using the AlignedIndentFilter to format SQL with CASE statements, the indentation and alignment are completely broken. + +## Description + +The CASE statement formatting in AlignedIndentFilter is not working correctly. The indentation and alignment of WHEN clauses are completely messed up, and the END keyword is not properly aligned. + +## Steps to reproduce + +```python +from sqlparse import format + +sql = """ +select a, +case when a = 0 +then 1 +when bb = 1 then 1 +when c = 2 then 2 +else 0 end as d, +extra_col +from table +where c is true +and b between 3 and 4 +""" + +formatted = format(sql, reindent=True, reindent_aligned=True) +print(formatted) +``` + +## Expected output + +``` +select a, + case when a = 0 then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 + end as d, + extra_col + from table + where c is true + and b between 3 and 4 +``` + +## Actual output + +The output has incorrect indentation, with WHEN clauses misaligned and the END keyword not properly positioned. The spacing between conditions and THEN keywords is also inconsistent. + +This issue also affects CASE statements with BETWEEN conditions in the WHEN clauses. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..b9b41537930d435d29ce7094e73c50f68bf64587 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "ac630103cc0e2b6a5033fca46ed5a7e19b04968f", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_parse.py", + "/testbed/tests/test_regressions.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_format.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": [ + "sqlparse/filters/aligned_indent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 913811, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "7f9db142ae8c7699d7fc7eea889e3928bb828f0755d0b19fe6578d82ff7ebce3", + "is_fork": true, + "learner_path": "tasks/36cbd9fe14a7ab6f1d921775/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "117db71e0861886a4428c0e379f07473692806d74331a3afa796602bd6ac2d81", + "provenance_path": "tasks/36cbd9fe14a7ab6f1d921775/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ac630103cc0e2b6a5033fca46ed5a7e19b04968f", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl", + "task_sha256": "e5445b1e8de2ea2a79e1dcc51b96ba38c23d2c72ab0a269febc34adf7ad8802b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ef9932c0b7972e4765561df9d8576d585878e551 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "45a55fceed8188ceee8199be318ae5fbdd282af3446ff03f0da3be986382f65c", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "91c161826db9efc69255c9708205cd791831ad227a7d701d2abe8a7c28f426a1", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "1963e3518908d1b87ab3c78d2009cb7e1b897b20d8d47d0f86bc6c8063dc7659", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "7f9db142ae8c7699d7fc7eea889e3928bb828f0755d0b19fe6578d82ff7ebce3", + "is_fork": true, + "learner_path": "tasks/36cbd9fe14a7ab6f1d921775/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "117db71e0861886a4428c0e379f07473692806d74331a3afa796602bd6ac2d81", + "provenance_path": "tasks/36cbd9fe14a7ab6f1d921775/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "70bef4e6aeaaccfc5da788bdb57e5165a4d72c8f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ac630103cc0e2b6a5033fca46ed5a7e19b04968f", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl", + "task_sha256": "e5445b1e8de2ea2a79e1dcc51b96ba38c23d2c72ab0a269febc34adf7ad8802b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..04a1c295e5b2b3d174d4c1c735fdc54f3e44824d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/provided-gold.diff @@ -0,0 +1,40 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index b69e8c053fce57c07137821f66c1159a07370557..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -65,26 +65,26 @@ + self._process_default(tlist) + + def _process_case(self, tlist): +- offset_ = len('case') + len('when') # Removed spaces in length calculations +- cases = tlist.get_cases(skip_ws=False) # Changed skip_ws=True to skip_ws=False ++ offset_ = len('case ') + len('when ') ++ cases = tlist.get_cases(skip_ws=True) + # align the end as well +- end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[0] # Altered index from 1 to 0 ++ end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] + cases.append((None, [end_token])) + +- condition_width = [len(' '.join(map(str, cond))) + 1 if cond else 0 # Added +1 to the length calculation ++ condition_width = [len(' '.join(map(str, cond))) if cond else 0 + for cond, _ in cases] +- max_cond_width = min(condition_width) # Changed max to min in the width determination ++ max_cond_width = max(condition_width) + + for i, (cond, value) in enumerate(cases): + # cond is None when 'else or end' +- stmt = value[0] if cond else cond[0] # Swapped cond and value ordering ++ stmt = cond[0] if cond else value[0] + +- if i < 1: # Changed condition from i > 0 to i < 1 ++ if i > 0: + tlist.insert_before(stmt, self.nl(offset_ - len(str(stmt)))) + if cond: + ws = sql.Token(T.Whitespace, self.char * ( +- max_cond_width + condition_width[i])) # Changed subtraction to addition +- tlist.insert_before(cond[-1], ws) # Changed method from insert_after to insert_before ++ max_cond_width - condition_width[i])) ++ tlist.insert_after(cond[-1], ws) + + def _next_token(self, tlist, idx=-1): + split_words = T.Keyword, self.split_words, True diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ea6bc82853a4119f69f805c9a5110de01d8c8476 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/solution/solve.sh @@ -0,0 +1,46 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index b69e8c053fce57c07137821f66c1159a07370557..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -65,26 +65,26 @@ + self._process_default(tlist) + + def _process_case(self, tlist): +- offset_ = len('case') + len('when') # Removed spaces in length calculations +- cases = tlist.get_cases(skip_ws=False) # Changed skip_ws=True to skip_ws=False ++ offset_ = len('case ') + len('when ') ++ cases = tlist.get_cases(skip_ws=True) + # align the end as well +- end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[0] # Altered index from 1 to 0 ++ end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] + cases.append((None, [end_token])) + +- condition_width = [len(' '.join(map(str, cond))) + 1 if cond else 0 # Added +1 to the length calculation ++ condition_width = [len(' '.join(map(str, cond))) if cond else 0 + for cond, _ in cases] +- max_cond_width = min(condition_width) # Changed max to min in the width determination ++ max_cond_width = max(condition_width) + + for i, (cond, value) in enumerate(cases): + # cond is None when 'else or end' +- stmt = value[0] if cond else cond[0] # Swapped cond and value ordering ++ stmt = cond[0] if cond else value[0] + +- if i < 1: # Changed condition from i > 0 to i < 1 ++ if i > 0: + tlist.insert_before(stmt, self.nl(offset_ - len(str(stmt)))) + if cond: + ws = sql.Token(T.Whitespace, self.char * ( +- max_cond_width + condition_width[i])) # Changed subtraction to addition +- tlist.insert_before(cond[-1], ws) # Changed method from insert_after to insert_before ++ max_cond_width - condition_width[i])) ++ tlist.insert_after(cond[-1], ws) + + def _next_token(self, tlist, idx=-1): + split_words = T.Keyword, self.split_words, True +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/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..94077b19ec4b665eb2d644473bbde1ddecef06e0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/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:eb444c80c76fe13000ba2fe8f700de1d6d117a6bae1a267438eaf4776b2f6c0c" +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/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/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/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..e8797053341166c115268ffbc9b7a729f4481917 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/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/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/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/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__1yfxmddl/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..c7d976e0d04e0d8b7a25c558a7c7c43ad8ee2bb0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "7509eb24736e6d24b2b46aecd2a359c2edaf46a6128038162b75482d3b1bf7e6", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "cd57943776798b6fae6b7de865f3e2d8bcbf1806f5c88fb3650e0d7cc1d7b1d3", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "592e563b0747f381f559528ffd79b648e9dedb71", + "source_completion_sha256": "e4605683de9b4c5e169c47a269c95f6efa6e27bd65986a72c05bf6a693e719f2", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__27d1num9", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "05f1178ad742dfde2f0edabb9d1a4a3a3dd623e02c2d157986f02920a01bcfdb", + "is_fork": true, + "learner_path": "tasks/ec78a02a32d8d8b8a74e9072/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/592e563b0747f381f559528ffd79b648e9dedb71/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "0e213a5ebddcd8b2f31c13adfe2eaf76b28b26ad6d6bae776eb410eaefcf782d", + "provenance_path": "tasks/ec78a02a32d8d8b8a74e9072/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "592e563b0747f381f559528ffd79b648e9dedb71", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "65805a3c75707dc1bd49afde25c6d613370b69e0", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__27d1num9", + "task_sha256": "dcde72c01966c83d447861bf438a6ab3761e14f6203a6d77bc35289416a6330b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__27d1num9", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/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/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f8981870d4d8ba2abab41fe116c575d2fb8b34e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/instruction.md @@ -0,0 +1,29 @@ +Array indexing parsing broken after recent changes + +#### Description + +Array indexing syntax in SQL statements is no longer being parsed correctly. When parsing SQL with array indices like `col[1]` or `col[x][(y+1)*2]`, the parser fails to properly group the square brackets with their preceding identifiers. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple array index +p = sqlparse.parse('col[1]')[0].tokens +print(f"Expected 1 token, got {len(p)}") + +# 2D array index +p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens +print(f"Expected 1 token, got {len(p)}") + +# Array literal +p = sqlparse.parse('ARRAY[%s, %s]')[0] +print(f"Expected 2 tokens, got {len(p.tokens)}") +``` + +The parser should group array indices with their preceding identifiers into single tokens, but instead they're being parsed as separate tokens. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..89dcceed24d6743964c4bfad3957713d1af831ed --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "65805a3c75707dc1bd49afde25c6d613370b69e0", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "592e563b0747f381f559528ffd79b648e9dedb71" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_format.py", + "/testbed/tests/test_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_regressions.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_parse.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": [ + "sqlparse/engine/grouping.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 923182, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__27d1num9", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__27d1num9", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "05f1178ad742dfde2f0edabb9d1a4a3a3dd623e02c2d157986f02920a01bcfdb", + "is_fork": true, + "learner_path": "tasks/ec78a02a32d8d8b8a74e9072/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/592e563b0747f381f559528ffd79b648e9dedb71/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "0e213a5ebddcd8b2f31c13adfe2eaf76b28b26ad6d6bae776eb410eaefcf782d", + "provenance_path": "tasks/ec78a02a32d8d8b8a74e9072/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "592e563b0747f381f559528ffd79b648e9dedb71", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "65805a3c75707dc1bd49afde25c6d613370b69e0", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__27d1num9", + "task_sha256": "dcde72c01966c83d447861bf438a6ab3761e14f6203a6d77bc35289416a6330b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ee2ac39db02cb8d3d5c63ca713fd7e970aeeb36a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "7509eb24736e6d24b2b46aecd2a359c2edaf46a6128038162b75482d3b1bf7e6", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/592e563b0747f381f559528ffd79b648e9dedb71/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "e4605683de9b4c5e169c47a269c95f6efa6e27bd65986a72c05bf6a693e719f2", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "906e88a5f89e5af745d00679c6e8d701236ba1c9cdb465dd4a8fc470f405f179", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__27d1num9", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "05f1178ad742dfde2f0edabb9d1a4a3a3dd623e02c2d157986f02920a01bcfdb", + "is_fork": true, + "learner_path": "tasks/ec78a02a32d8d8b8a74e9072/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/592e563b0747f381f559528ffd79b648e9dedb71/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "0e213a5ebddcd8b2f31c13adfe2eaf76b28b26ad6d6bae776eb410eaefcf782d", + "provenance_path": "tasks/ec78a02a32d8d8b8a74e9072/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "592e563b0747f381f559528ffd79b648e9dedb71", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "65805a3c75707dc1bd49afde25c6d613370b69e0", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__27d1num9", + "task_sha256": "dcde72c01966c83d447861bf438a6ab3761e14f6203a6d77bc35289416a6330b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..e34fcd6c5f3b4cfb5d70de292052eae2a4f86a1b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 836ab70b6bc2dfc21058b202e3b8d8b1a5d26a24..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -253,7 +253,7 @@ + return isinstance(token, sql.SquareBrackets) + + def valid_prev(token): +- return imt(token, i=ttypes, t=sqlcls) ++ return imt(token, i=sqlcls, t=ttypes) + + def valid_next(token): + return True diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e46c10978e187adfa9efde5b57b54db74bbecc48 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/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/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 836ab70b6bc2dfc21058b202e3b8d8b1a5d26a24..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -253,7 +253,7 @@ + return isinstance(token, sql.SquareBrackets) + + def valid_prev(token): +- return imt(token, i=ttypes, t=sqlcls) ++ return imt(token, i=sqlcls, t=ttypes) + + def valid_next(token): + return True +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/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..798c71219a17e0bf35c564c8c016826a3cc479ec --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/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:54c20878ea5cf3f493a10899b5048c346a0afb655f263d9c6a9c3075b2eb996a" +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/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/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/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..3003154ba480f7ebe7628b1326eb5d98deff2a66 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/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/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/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/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__27d1num9/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..2fe3d3ef825ce6009a07b19fcb761372ca3c3f20 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "87c619f0df1af791a850845c05786ba2fd7cfd4e6ea9c6a8940f21588a7a8a24", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "3fb41b3f4d43d045d8611a8a0e079882af49cbb6d01fc5124cf337de02d35cd7", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "06aaf33a5c1548892a4c438b36b8cbacb2b2fd83", + "source_completion_sha256": "b7d7253c0c0b5332f0f305dc2f3d7a04710c933daa320a18f650ee6c651c22ae", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "3b4a66063d51aaa19a0dda078543967fa83af365a4ef928d20d2a30b560759ee", + "is_fork": true, + "learner_path": "tasks/8c5b4501d9d9e6529c688fba/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/06aaf33a5c1548892a4c438b36b8cbacb2b2fd83/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "dada8f8aa5313caa6b57cd11245f43027860afc0a7515c8947c8ac52242d7016", + "provenance_path": "tasks/8c5b4501d9d9e6529c688fba/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "06aaf33a5c1548892a4c438b36b8cbacb2b2fd83", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "886910f68706d862b7d19c10880b4c4e0694c763", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp", + "task_sha256": "7cef196e35fcd881a529dba836773602845dc2077c1fff6e9fc14b0d82230d8c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/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/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7721714c720330aa18a148fad1b917fb178a1b3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/instruction.md @@ -0,0 +1,38 @@ +SQL parsing broken for identifiers with dots and PostgreSQL operators + +#### Description + +After a recent change, SQL parsing is completely broken for queries containing identifiers with dots (like `table.column`) and PostgreSQL JSON operators (`->` and `->>`). The parser now incorrectly groups these tokens, causing identifier parsing to fail. + +#### Steps/Code to Reproduce + +```python +import sqlparse +from sqlparse import sql + +# Simple dot notation fails +parsed = sqlparse.parse('select x.y as "z" from foo')[0] +identifier = parsed.tokens[2] +print(f"Expected: Identifier, Got: {type(identifier)}") +print(f"Expected name: z, Got: {identifier.get_name() if hasattr(identifier, 'get_name') else 'N/A'}") + +# PostgreSQL JSON operators also broken +parsed2 = sqlparse.parse("SELECT data->>'name' FROM users")[0] +print(f"Parsed tokens: {[str(t) for t in parsed2.tokens]}") +``` + +The above code should work correctly but now fails to properly identify the `x.y` as an identifier and breaks on PostgreSQL JSON operators. + +#### Expected Behavior + +- `x.y` should be parsed as a single `Identifier` token +- The identifier should have `get_name()` return `"z"` and `get_real_name()` return `"y"` +- PostgreSQL operators `->` and `->>` should be handled correctly + +#### Actual Behavior + +The parser fails to group dot-separated identifiers correctly and also breaks on PostgreSQL JSON operators, causing widespread parsing failures across many SQL constructs. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..95bc14e6aa741ce53fbe3ad03a17f1bec993da0e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::test_format_column_ordering", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_parse_window_as" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "886910f68706d862b7d19c10880b4c4e0694c763", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "06aaf33a5c1548892a4c438b36b8cbacb2b2fd83" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_format.py", + "tests/test_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.py", + "tests/test_tokenize.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": [ + "sqlparse/engine/grouping.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 849511, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "3b4a66063d51aaa19a0dda078543967fa83af365a4ef928d20d2a30b560759ee", + "is_fork": true, + "learner_path": "tasks/8c5b4501d9d9e6529c688fba/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/06aaf33a5c1548892a4c438b36b8cbacb2b2fd83/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "dada8f8aa5313caa6b57cd11245f43027860afc0a7515c8947c8ac52242d7016", + "provenance_path": "tasks/8c5b4501d9d9e6529c688fba/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "06aaf33a5c1548892a4c438b36b8cbacb2b2fd83", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "886910f68706d862b7d19c10880b4c4e0694c763", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp", + "task_sha256": "7cef196e35fcd881a529dba836773602845dc2077c1fff6e9fc14b0d82230d8c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..3d62adf76d6a1ca85ab73c8b80fe3c36117f3603 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "87c619f0df1af791a850845c05786ba2fd7cfd4e6ea9c6a8940f21588a7a8a24", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/06aaf33a5c1548892a4c438b36b8cbacb2b2fd83/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "b7d7253c0c0b5332f0f305dc2f3d7a04710c933daa320a18f650ee6c651c22ae", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "059c6595b66e2a9ef3e841944858ef425667efdf101bb75ebfc5bd78b9b33b95", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "3b4a66063d51aaa19a0dda078543967fa83af365a4ef928d20d2a30b560759ee", + "is_fork": true, + "learner_path": "tasks/8c5b4501d9d9e6529c688fba/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/06aaf33a5c1548892a4c438b36b8cbacb2b2fd83/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "dada8f8aa5313caa6b57cd11245f43027860afc0a7515c8947c8ac52242d7016", + "provenance_path": "tasks/8c5b4501d9d9e6529c688fba/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "06aaf33a5c1548892a4c438b36b8cbacb2b2fd83", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "886910f68706d862b7d19c10880b4c4e0694c763", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp", + "task_sha256": "7cef196e35fcd881a529dba836773602845dc2077c1fff6e9fc14b0d82230d8c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..1c5f416b5aeca9852a87e179fe7dc169cbda975e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/provided-gold.diff @@ -0,0 +1,22 @@ +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 0a361f6242fd53b05aff05d9eb33bc6b7027039b..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -139,12 +139,12 @@ + + def group_period(tlist): + def match(token): +- for ttype, value in ((T.Operator, '->'), +- (T.Operator, '->>'), +- (T.Punctuation, '.')): ++ for ttype, value in ((T.Punctuation, '.'), ++ (T.Operator, '->'), ++ (T.Operator, '->>')): + if token.match(ttype, value): +- return False +- return True ++ return True ++ return False + + def valid_prev(token): + sqlcls = sql.SquareBrackets, sql.Identifier diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f284d20b34e1006ce9f9c9bd8d6e5c04cc0e54a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 0a361f6242fd53b05aff05d9eb33bc6b7027039b..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -139,12 +139,12 @@ + + def group_period(tlist): + def match(token): +- for ttype, value in ((T.Operator, '->'), +- (T.Operator, '->>'), +- (T.Punctuation, '.')): ++ for ttype, value in ((T.Punctuation, '.'), ++ (T.Operator, '->'), ++ (T.Operator, '->>')): + if token.match(ttype, value): +- return False +- return True ++ return True ++ return False + + def valid_prev(token): + sqlcls = sql.SquareBrackets, sql.Identifier +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/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b81e6e39f5f742100b2743782aca3d3821e14a1b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/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:a96ba3efc5ae31b56bcb463a0d8a1f710971cfd1f2654a1baf7c77e0b34964dc" +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/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/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/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..6beea9300509c6daad16c3112c99c1ed0c1754f1 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::test_format_column_ordering", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_parse_window_as" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/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/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/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/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__29qulsnp/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f8f488074bb55ef0317dea0293a498592eccb728 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "b5d2420bcc966e7535dd02ef17a0b96e99125be1abbe02b28e9cd87c3f15dfbd", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "bd4fcbf1059ecf76c60b7cb945afa371b7dcbd571684b8dd1fc061d7970f66b2", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "f378c249b12450557c94eacb1170477004792cc9", + "source_completion_sha256": "f3b18ac50fb3ad9dd8013a189025b1c64166a3a91d5d2e5dd172b0bfe90ffd67", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "dd6b601fd9a9e212fa6a87f80d2f31d47ce7a8190bc05299ba71c25c991f8bce", + "is_fork": true, + "learner_path": "tasks/633b27fba7f923e1cbc6e3e6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/f378c249b12450557c94eacb1170477004792cc9/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "bc9f4fcc277c00c024b6a357d76ce34b8d93b829c1f5d4e5b9727f146168cdb2", + "provenance_path": "tasks/633b27fba7f923e1cbc6e3e6/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f378c249b12450557c94eacb1170477004792cc9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "77b8499e133300cd5a89b22c8122c91ed5cd21fe", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh", + "task_sha256": "9abcadb47a695ee632dfd9247cf3f6f64837aa349a5f5da846fc991eb9dcb14d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/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/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51f7d1457c56af6014757c631766543dad49d618 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/instruction.md @@ -0,0 +1,30 @@ +get_real_name() returns None for simple identifiers without dots + +#### Description + +When calling `get_real_name()` on identifiers that don't contain dots, the method now returns `None` instead of the identifier name. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple identifier without dot +p = sqlparse.parse('foo bar')[0].tokens[0] +print(p.get_real_name()) # Expected: 'foo', Actual: None + +# Function call +p = sqlparse.parse('foo()')[0].tokens[0] +print(p.get_real_name()) # Expected: 'foo', Actual: None + +# Update statement with alias +s = 'update a t set t.b=1' +stmts = sqlparse.parse(s) +print(stmts[0].tokens[2].get_real_name()) # Expected: 'a', Actual: None +``` + +This affects various SQL parsing scenarios where simple identifiers (without schema/table prefixes) are used. The method should return the identifier name itself when there's no dot separator, but currently returns `None`. + +## 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/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..2c4efa93066a0ab1ccda237c4a406bb3f1e11456 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_get_real_name", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue489_tzcasts" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "77b8499e133300cd5a89b22c8122c91ed5cd21fe", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "f378c249b12450557c94eacb1170477004792cc9" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_format.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.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": [ + "sqlparse/sql.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 884419, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "dd6b601fd9a9e212fa6a87f80d2f31d47ce7a8190bc05299ba71c25c991f8bce", + "is_fork": true, + "learner_path": "tasks/633b27fba7f923e1cbc6e3e6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/f378c249b12450557c94eacb1170477004792cc9/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "bc9f4fcc277c00c024b6a357d76ce34b8d93b829c1f5d4e5b9727f146168cdb2", + "provenance_path": "tasks/633b27fba7f923e1cbc6e3e6/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f378c249b12450557c94eacb1170477004792cc9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "77b8499e133300cd5a89b22c8122c91ed5cd21fe", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh", + "task_sha256": "9abcadb47a695ee632dfd9247cf3f6f64837aa349a5f5da846fc991eb9dcb14d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..7072bf4bd0f0d0a8722318477e632d1b3055c148 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "b5d2420bcc966e7535dd02ef17a0b96e99125be1abbe02b28e9cd87c3f15dfbd", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/f378c249b12450557c94eacb1170477004792cc9/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "f3b18ac50fb3ad9dd8013a189025b1c64166a3a91d5d2e5dd172b0bfe90ffd67", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "8d0751b70e474dcc477be2a93ddfe00cf3f0faf92bef58f2445a80dc9d3f4959", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "dd6b601fd9a9e212fa6a87f80d2f31d47ce7a8190bc05299ba71c25c991f8bce", + "is_fork": true, + "learner_path": "tasks/633b27fba7f923e1cbc6e3e6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/f378c249b12450557c94eacb1170477004792cc9/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "bc9f4fcc277c00c024b6a357d76ce34b8d93b829c1f5d4e5b9727f146168cdb2", + "provenance_path": "tasks/633b27fba7f923e1cbc6e3e6/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f378c249b12450557c94eacb1170477004792cc9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "77b8499e133300cd5a89b22c8122c91ed5cd21fe", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh", + "task_sha256": "9abcadb47a695ee632dfd9247cf3f6f64837aa349a5f5da846fc991eb9dcb14d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..512e2d38ac8047fe9488559e8a6b7f0d57caf21d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/provided-gold.diff @@ -0,0 +1,15 @@ +diff --git a/sqlparse/sql.py b/sqlparse/sql.py +index 9dabbc7b6dbcfc8ad5c3d3949be2ccc84019331f..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -21,9 +21,7 @@ + """Returns the real name (object name) of this identifier.""" + # a.b + dot_idx, _ = self.token_next_by(m=(T.Punctuation, '.')) +- if dot_idx is None: +- return None +- return self._get_first_name(dot_idx, real_name=False) ++ return self._get_first_name(dot_idx, real_name=True) + + def get_alias(self): + """Returns the alias for this identifier or ``None``.""" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..30231e1c270fbd8a241d5c102590461692a1b796 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/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/sqlparse/sql.py b/sqlparse/sql.py +index 9dabbc7b6dbcfc8ad5c3d3949be2ccc84019331f..10373751335ee0e59f6efe5f6e7da5a74b50e41a 100644 +--- a/sqlparse/sql.py ++++ b/sqlparse/sql.py +@@ -21,9 +21,7 @@ + """Returns the real name (object name) of this identifier.""" + # a.b + dot_idx, _ = self.token_next_by(m=(T.Punctuation, '.')) +- if dot_idx is None: +- return None +- return self._get_first_name(dot_idx, real_name=False) ++ return self._get_first_name(dot_idx, real_name=True) + + def get_alias(self): + """Returns the alias for this identifier or ``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/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6a7b95fcc664b8dbec2d1e25b0d3b24db2ebb831 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/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:0e0f176d2656c0efd3e58012b3fffbf009bd48cc36f9856b47239c43fb6ad265" +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/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/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/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..3bc86dfc7d2e675fee22ce7f8479cd4f20ca69f5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_get_real_name", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue489_tzcasts" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/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/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/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/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2ppbv0uh/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..e1645172c9eea5c365f3500a694c6939ea311ad6 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "e1cf023ea72a55878b43523d6ce6c7e1c5a7f9c064ec027d94bc8f845066bfbb", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "97635f16ef0bdd80fc68d4e8e16f7905311a91c860eea3173f527fb3125cc1cc", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "c14095620e762d33ad30a16ffc0a95cbb13d4e90", + "source_completion_sha256": "3e4c19d11e57ac7528a063a89de41dc607eee773173e8450484704950dcdbb9a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "138a3041b82f4b265e799becc1a0da500d602fd1a9e8148ff6fe69c374fd61f2", + "is_fork": true, + "learner_path": "tasks/55bf4e6aaa8db8508d79f1d7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/c14095620e762d33ad30a16ffc0a95cbb13d4e90/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "9da537673de6897f372153d2325c9400e08d1d8b517121d8e089c4aca040b3a1", + "provenance_path": "tasks/55bf4e6aaa8db8508d79f1d7/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "c14095620e762d33ad30a16ffc0a95cbb13d4e90", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f15c436fb0515ba12fc01acf4169b860d0878c60", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31", + "task_sha256": "682175e596b762ac580fafe15d325d89a00849a7b7b17020ed40dd3eadd531d7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/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/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d9d2718f71f86f34511849072f2655855d1464c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/instruction.md @@ -0,0 +1,33 @@ +parsestream function broken after recent changes + +#### Description + +The `parsestream` function is not working correctly and throws AttributeError when trying to parse SQL from a stream. This affects any code that uses `sqlparse.parsestream()` to parse SQL from file-like objects. + +#### Steps/Code to Reproduce + +```python +import sqlparse +from io import StringIO + +# Create a simple SQL stream +sql_stream = StringIO("SELECT * FROM users WHERE id = 1;") + +# This should work but throws an error +result = sqlparse.parsestream(sql_stream) +list(result) # Try to consume the generator +``` + +The error occurs when trying to use parsestream with any stream input. The function seems to have issues with its internal filter stack configuration. + +#### Expected Behavior + +The parsestream function should successfully parse SQL from stream objects and return a generator of Statement instances, just like the regular parse function but for streams. + +#### Actual Behavior + +Getting AttributeError when trying to use parsestream function. The function appears to have problems with its filter stack setup that prevents it from processing streams 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/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..bf5b2885906ca6857aa2c537c31e3bc9982b52bf --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "f15c436fb0515ba12fc01acf4169b860d0878c60", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "c14095620e762d33ad30a16ffc0a95cbb13d4e90" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_format.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.py", + "tests/test_split.py", + "tests/test_tokenize.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": [ + "sqlparse/__init__.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 872024, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "138a3041b82f4b265e799becc1a0da500d602fd1a9e8148ff6fe69c374fd61f2", + "is_fork": true, + "learner_path": "tasks/55bf4e6aaa8db8508d79f1d7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/c14095620e762d33ad30a16ffc0a95cbb13d4e90/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "9da537673de6897f372153d2325c9400e08d1d8b517121d8e089c4aca040b3a1", + "provenance_path": "tasks/55bf4e6aaa8db8508d79f1d7/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "c14095620e762d33ad30a16ffc0a95cbb13d4e90", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f15c436fb0515ba12fc01acf4169b860d0878c60", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31", + "task_sha256": "682175e596b762ac580fafe15d325d89a00849a7b7b17020ed40dd3eadd531d7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ffd880d84314d152ff77cc678bcc09c343d92b76 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "e1cf023ea72a55878b43523d6ce6c7e1c5a7f9c064ec027d94bc8f845066bfbb", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/c14095620e762d33ad30a16ffc0a95cbb13d4e90/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "3e4c19d11e57ac7528a063a89de41dc607eee773173e8450484704950dcdbb9a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "0c1239abf78088af3eb2de9a14ced2f1cf75d3f8ab06db3a0278857535c01d2c", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "138a3041b82f4b265e799becc1a0da500d602fd1a9e8148ff6fe69c374fd61f2", + "is_fork": true, + "learner_path": "tasks/55bf4e6aaa8db8508d79f1d7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/c14095620e762d33ad30a16ffc0a95cbb13d4e90/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "9da537673de6897f372153d2325c9400e08d1d8b517121d8e089c4aca040b3a1", + "provenance_path": "tasks/55bf4e6aaa8db8508d79f1d7/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "c14095620e762d33ad30a16ffc0a95cbb13d4e90", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f15c436fb0515ba12fc01acf4169b860d0878c60", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31", + "task_sha256": "682175e596b762ac580fafe15d325d89a00849a7b7b17020ed40dd3eadd531d7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a22b801b16f0120053ea2bad2da7bdd600ad9247 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/provided-gold.diff @@ -0,0 +1,17 @@ +diff --git a/sqlparse/__init__.py b/sqlparse/__init__.py +index 9b99210e06c5bea9546144633ccfecc44079e9fd..23507b73455f3624580f06cf7b11acea16f1f79b 100644 +--- a/sqlparse/__init__.py ++++ b/sqlparse/__init__.py +@@ -38,10 +38,8 @@ + :returns: A generator of :class:`~sqlparse.sql.Statement` instances. + """ + stack = engine.FilterStack() +- # Disable grouping instead of enabling it +- stack.disable_grouping() +- # Pass encoding as a positional argument instead of keyword +- return stack.run(encoding, stream) ++ stack.enable_grouping() ++ return stack.run(stream, encoding) + + + def format(sql, encoding=None, **options): diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..63ea2b587112192d408d19870eba4b8e82eaa185 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/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/sqlparse/__init__.py b/sqlparse/__init__.py +index 9b99210e06c5bea9546144633ccfecc44079e9fd..23507b73455f3624580f06cf7b11acea16f1f79b 100644 +--- a/sqlparse/__init__.py ++++ b/sqlparse/__init__.py +@@ -38,10 +38,8 @@ + :returns: A generator of :class:`~sqlparse.sql.Statement` instances. + """ + stack = engine.FilterStack() +- # Disable grouping instead of enabling it +- stack.disable_grouping() +- # Pass encoding as a positional argument instead of keyword +- return stack.run(encoding, stream) ++ stack.enable_grouping() ++ return stack.run(stream, encoding) + + + def format(sql, encoding=None, **options): +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/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..46730a6ee365bfec4bad9206078f73aa71d5859e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/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:e9461e20a28099cb0e83d50ab38bdfffdf2d61af4ddde9e217740738d3873658" +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/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/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/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..ed4aa94b9788fabae892f032c3310accfdf617a6 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/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/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/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/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__2z5qpz31/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " +All rights reserved. + +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. + * Neither the name of the authors nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..a66165a0f1625cd08749f2f90dbc00bf6fc08321 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", + "gold_patch_sha256": "11e42f381e1076b2841d5c785101fccccbe32cad2743a291760348a121287d92", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "b8a7b05fb5aaf0e3f8749821ae45a524a14e7bb9364faee6d22989a64c4d6b42", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "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/andialbrecht__sqlparse.e57923b3.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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "644e7c4302179788aba450d2e463a67e5fd586df", + "source_completion_sha256": "b059b239e825e2c9fc8b8c8211e5c0841bb9431e6f498e7acc581898dd9a6c48", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "9285ea5e1852ad0a2b8ad88cab9ef0280ea6bb5d49a5a73b387c5b9df6bb6372", + "is_fork": true, + "learner_path": "tasks/02ce0398e33974f7e82c9d3b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/644e7c4302179788aba450d2e463a67e5fd586df/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "86623e7c1d2dc0ef228f8503825d5218b9cfe061205f30d9e5b3f7eb652d24ea", + "provenance_path": "tasks/02ce0398e33974f7e82c9d3b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "644e7c4302179788aba450d2e463a67e5fd586df", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ce6ebdb67a0206f626113362e2c702fa735ee2c1", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o", + "task_sha256": "50b951cd7a98ed22c96564b9271b6dcbf0893157ba8d59686ecc6ca695799664", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "symlink_submodule_changes_supported": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/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 pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/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/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37e4bf649e9d10d3831a8c00ca284056d5119bb7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/instruction.md @@ -0,0 +1,31 @@ +Parenthesis grouping broken after recent changes + +#### Description + +SQL parsing is producing incorrect results when parentheses are involved. The parser seems to be processing tokens in the wrong order, causing various grouping and parsing operations to fail. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple parenthesis parsing fails +s = '(col1, col2)' +p = sqlparse.parse(s)[0] +print(p.tokens[0].tokens[1]) # Should work but raises AttributeError + +# Whitespace stripping in groups broken +formatted = sqlparse.format('( where foo = bar ) from', strip_whitespace=True) +print(f"Got: '{formatted}'") +print(f"Expected: '(where foo = bar) from'") + +# Comparison grouping inside parentheses fails +p = sqlparse.parse('(a=1)')[0] +print(isinstance(p.tokens[0].tokens[1], sqlparse.sql.Comparison)) # Should be True +``` + +The above code produces errors or unexpected results. Various SQL constructs with parentheses are not being parsed correctly, affecting formatting, token access, and grouping 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/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..50efd149d6fea423993005fa051828092bee9b72 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/metadata.json @@ -0,0 +1,533 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632" + ], + "PASS_TO_PASS": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "ce6ebdb67a0206f626113362e2c702fa735ee2c1", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "644e7c4302179788aba450d2e463a67e5fd586df" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.flake8", + "/testbed/.github/CODE_OF_CONDUCT.md", + "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", + "/testbed/.github/PULL_REQUEST_TEMPLATE.md", + "/testbed/.gitignore", + "/testbed/.readthedocs.yaml", + "/testbed/AUTHORS", + "/testbed/CHANGELOG", + "/testbed/CONTRIBUTING.md", + "/testbed/LICENSE", + "/testbed/Makefile", + "/testbed/README.rst", + "/testbed/SECURITY.md", + "/testbed/TODO", + "/testbed/docs/Makefile", + "/testbed/docs/source/analyzing.rst", + "/testbed/docs/source/api.rst", + "/testbed/docs/source/changes.rst", + "/testbed/docs/source/conf.py", + "/testbed/docs/source/extending.rst", + "/testbed/docs/source/index.rst", + "/testbed/docs/source/indices.rst", + "/testbed/docs/source/intro.rst", + "/testbed/docs/source/license.rst", + "/testbed/docs/source/ui.rst", + "/testbed/docs/sqlformat.1", + "/testbed/examples/column_defs_lowlevel.py", + "/testbed/examples/extract_table_names.py", + "/testbed/pyproject.toml", + "/testbed/sqlparse/__init__.py", + "/testbed/sqlparse/__main__.py", + "/testbed/sqlparse/cli.py", + "/testbed/sqlparse/engine/__init__.py", + "/testbed/sqlparse/engine/filter_stack.py", + "/testbed/sqlparse/engine/grouping.py", + "/testbed/sqlparse/engine/statement_splitter.py", + "/testbed/sqlparse/exceptions.py", + "/testbed/sqlparse/filters/__init__.py", + "/testbed/sqlparse/filters/aligned_indent.py", + "/testbed/sqlparse/filters/others.py", + "/testbed/sqlparse/filters/output.py", + "/testbed/sqlparse/filters/reindent.py", + "/testbed/sqlparse/filters/right_margin.py", + "/testbed/sqlparse/filters/tokens.py", + "/testbed/sqlparse/formatter.py", + "/testbed/sqlparse/keywords.py", + "/testbed/sqlparse/lexer.py", + "/testbed/sqlparse/sql.py", + "/testbed/sqlparse/tokens.py", + "/testbed/sqlparse/utils.py", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/files/_Make_DirEntry.sql", + "/testbed/tests/files/begintag.sql", + "/testbed/tests/files/begintag_2.sql", + "/testbed/tests/files/casewhen_procedure.sql", + "/testbed/tests/files/dashcomment.sql", + "/testbed/tests/files/encoding_gbk.sql", + "/testbed/tests/files/encoding_utf8.sql", + "/testbed/tests/files/function.sql", + "/testbed/tests/files/function_psql.sql", + "/testbed/tests/files/function_psql2.sql", + "/testbed/tests/files/function_psql3.sql", + "/testbed/tests/files/function_psql4.sql", + "/testbed/tests/files/huge_select.sql", + "/testbed/tests/files/multiple_case_in_begin.sql", + "/testbed/tests/files/mysql_handler.sql", + "/testbed/tests/files/stream.sql", + "/testbed/tests/files/test_cp1251.sql", + "/testbed/tests/test_cli.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_split.py", + "/testbed/tests/test_tokenize.py", + "/testbed/tests/test_utils.py" + ], + "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": "SqlparseE57923b3", + "profile_lines": [ + 921, + 924 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "upstream_repo": "andialbrecht/sqlparse" + }, + "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "private_test_paths": [ + "tests/test_format.py", + "tests/test_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.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": [ + "sqlparse/engine/grouping.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 855887, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "andialbrecht/sqlparse" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "9285ea5e1852ad0a2b8ad88cab9ef0280ea6bb5d49a5a73b387c5b9df6bb6372", + "is_fork": true, + "learner_path": "tasks/02ce0398e33974f7e82c9d3b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/644e7c4302179788aba450d2e463a67e5fd586df/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "86623e7c1d2dc0ef228f8503825d5218b9cfe061205f30d9e5b3f7eb652d24ea", + "provenance_path": "tasks/02ce0398e33974f7e82c9d3b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "644e7c4302179788aba450d2e463a67e5fd586df", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ce6ebdb67a0206f626113362e2c702fa735ee2c1", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o", + "task_sha256": "50b951cd7a98ed22c96564b9271b6dcbf0893157ba8d59686ecc6ca695799664", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..b44d107dd8cd32f7a99e67e5b599c40254ce481f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "11e42f381e1076b2841d5c785101fccccbe32cad2743a291760348a121287d92", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/644e7c4302179788aba450d2e463a67e5fd586df/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "b059b239e825e2c9fc8b8c8211e5c0841bb9431e6f498e7acc581898dd9a6c48", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "f909ada0ee3c729ae45a61f8de8f0688edd9d9f4787d1b44c0ed316dcbc32690", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "9285ea5e1852ad0a2b8ad88cab9ef0280ea6bb5d49a5a73b387c5b9df6bb6372", + "is_fork": true, + "learner_path": "tasks/02ce0398e33974f7e82c9d3b/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", + "reviewed": true, + "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/644e7c4302179788aba450d2e463a67e5fd586df/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": "e57923b3aa823c524c807953cecc48cf6eec2cb2", + "patch_sha256": "86623e7c1d2dc0ef228f8503825d5218b9cfe061205f30d9e5b3f7eb652d24ea", + "provenance_path": "tasks/02ce0398e33974f7e82c9d3b/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "644e7c4302179788aba450d2e463a67e5fd586df", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ce6ebdb67a0206f626113362e2c702fa735ee2c1", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o", + "task_sha256": "50b951cd7a98ed22c96564b9271b6dcbf0893157ba8d59686ecc6ca695799664", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "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": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..c87e569086a0beb88c6b4d5df534442b94e787a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index e0f1077a210c6e37ad839c7f3797b6f77b14ab79..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -54,7 +54,7 @@ + + + def group_parenthesis(tlist): +- _group_matching(tlist[::-1], sql.Parenthesis) ++ _group_matching(tlist, sql.Parenthesis) + + + def group_case(tlist): diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d70818a12599d2ff45ebc2ab902276bdb04a6ec3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/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/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index e0f1077a210c6e37ad839c7f3797b6f77b14ab79..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -54,7 +54,7 @@ + + + def group_parenthesis(tlist): +- _group_matching(tlist[::-1], sql.Parenthesis) ++ _group_matching(tlist, sql.Parenthesis) + + + def group_case(tlist): +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/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..78bfc76dc957c65d304b4befc78a4a5a1215e8fc --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/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:d92ba63dbdc22d1ee97f2cdcfecc73559bfd7302c3cad77236f30471b2c49b5a" +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/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/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/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..8c8304a48274ac9e6b29e3de55f9de775c9eb438 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_keywordfunctions", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_identifier_list", + "tests/test_grouping.py::test_grouping_identifier_list_subquery", + "tests/test_grouping.py::test_grouping_identifier_list_case", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_grouping_alias", + "tests/test_grouping.py::test_grouping_alias_ctas", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_comparison_exclude", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_grouping_function_not_in", + "tests/test_grouping.py::test_grouping_varchar", + "tests/test_grouping.py::test_comparison_with_parenthesis", + "tests/test_grouping.py::test_comparison_with_functions", + "tests/test_grouping.py::test_aliased_function_without_as", + "tests/test_parse.py::test_parse_within", + "tests/test_parse.py::test_parse_child_of", + "tests/test_parse.py::test_parse_has_ancestor", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_function_param_single_literal", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_parse_casted_params", + "tests/test_parse.py::test_array_index_function_result", + "tests/test_parse.py::test_pprint", + "tests/test_parse.py::test_non_ascii", + "tests/test_parse.py::test_from_subquery", + "tests/test_parse.py::test_parenthesis", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue322_concurrently_is_keyword", + "tests/test_regressions.py::test_issue562_tzcasts", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632" + ], + "pass-to-pass": [ + "tests/test_cli.py::test_cli_main_empty", + "tests/test_cli.py::test_parser_empty", + "tests/test_cli.py::test_main_help", + "tests/test_cli.py::test_valid_args", + "tests/test_cli.py::test_invalid_choice", + "tests/test_cli.py::test_invalid_args", + "tests/test_cli.py::test_invalid_infile", + "tests/test_cli.py::test_invalid_outfile", + "tests/test_cli.py::test_stdout", + "tests/test_cli.py::test_script", + "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", + "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", + "tests/test_cli.py::test_encoding", + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_single", + "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestSpacesAroundOperators::test_basic", + "tests/test_format.py::TestSpacesAroundOperators::test_bools", + "tests/test_format.py::TestSpacesAroundOperators::test_nested", + "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", + "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", + "tests/test_format.py::test_truncate_strings_invalid_option2[0]", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_format.py::test_format_json_ops", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "tests/test_grouping.py::test_grouping_identifier_name_wildcard", + "tests/test_grouping.py::test_grouping_identifier_invalid", + "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", + "tests/test_grouping.py::test_grouping_identifier_as_invalid", + "tests/test_grouping.py::test_grouping_operation[foo+100]", + "tests/test_grouping.py::test_grouping_operation[foo*100]", + "tests/test_grouping.py::test_grouping_identifier_list_other", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_grouping_identifier_list_with_order", + "tests/test_grouping.py::test_returning_kw_ends_where_clause", + "tests/test_grouping.py::test_into_kw_ends_where_clause", + "tests/test_grouping.py::test_grouping_alias_case", + "tests/test_grouping.py::test_grouping_subquery_no_parens", + "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_identifier_with_operators", + "tests/test_grouping.py::test_identifier_with_op_trailing_ws", + "tests/test_grouping.py::test_identifier_with_string_literals", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_grouping.py::test_comparison_with_keywords", + "tests/test_grouping.py::test_comparison_with_floats", + "tests/test_grouping.py::test_comparison_with_strings[=]", + "tests/test_grouping.py::test_comparison_with_strings[!=]", + "tests/test_grouping.py::test_comparison_with_strings[>]", + "tests/test_grouping.py::test_comparison_with_strings[<]", + "tests/test_grouping.py::test_comparison_with_strings[<=]", + "tests/test_grouping.py::test_comparison_with_strings[>=]", + "tests/test_grouping.py::test_comparison_with_strings[~]", + "tests/test_grouping.py::test_comparison_with_strings[~~]", + "tests/test_grouping.py::test_comparison_with_strings[!~~]", + "tests/test_grouping.py::test_comparison_with_strings[LIKE]", + "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", + "tests/test_grouping.py::test_like_and_ilike_comparison", + "tests/test_grouping.py::test_comparison_with_typed_literal", + "tests/test_grouping.py::test_forloops[FOR]", + "tests/test_grouping.py::test_forloops[FOREACH]", + "tests/test_grouping.py::test_nested_for", + "tests/test_grouping.py::test_begin", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "tests/test_grouping.py::test_nested_begin", + "tests/test_grouping.py::test_aliased_column_without_as", + "tests/test_grouping.py::test_qualified_function", + "tests/test_grouping.py::test_aliased_literal_without_as", + "tests/test_grouping.py::test_grouping_as_cte", + "tests/test_grouping.py::test_grouping_create_table", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", + "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", + "tests/test_parse.py::test_parse_tokenize", + "tests/test_parse.py::test_parse_multistatement", + "tests/test_parse.py::test_parse_float[.5]", + "tests/test_parse.py::test_parse_float[.51]", + "tests/test_parse.py::test_parse_float[1.5]", + "tests/test_parse.py::test_parse_float[12.5]", + "tests/test_parse.py::test_parse_modulo_not_placeholder", + "tests/test_parse.py::test_parse_access_symbol", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", + "tests/test_parse.py::test_parse_keyword_like_identifier", + "tests/test_parse.py::test_parse_div_operator", + "tests/test_parse.py::test_quoted_identifier", + "tests/test_parse.py::test_valid_identifier_names[foo]", + "tests/test_parse.py::test_valid_identifier_names[_foo]", + "tests/test_parse.py::test_valid_identifier_names[1_data]", + "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", + "tests/test_parse.py::test_psql_quotation_marks", + "tests/test_parse.py::test_double_precision_is_builtin", + "tests/test_parse.py::test_placeholder[?]", + "tests/test_parse.py::test_placeholder[:1]", + "tests/test_parse.py::test_placeholder[:foo]", + "tests/test_parse.py::test_placeholder[%s]", + "tests/test_parse.py::test_placeholder[%(foo)s]", + "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", + "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", + "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", + "tests/test_parse.py::test_scientific_numbers[e1-None]", + "tests/test_parse.py::test_single_quotes_are_strings", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_simple_1d_array_index", + "tests/test_parse.py::test_2d_array_index", + "tests/test_parse.py::test_schema_qualified_array_index", + "tests/test_parse.py::test_aliased_array_index", + "tests/test_parse.py::test_array_literal", + "tests/test_parse.py::test_typed_array_definition", + "tests/test_parse.py::test_names_and_special_names[foo]", + "tests/test_parse.py::test_names_and_special_names[@foo]", + "tests/test_parse.py::test_names_and_special_names[#foo]", + "tests/test_parse.py::test_names_and_special_names[##foo]", + "tests/test_parse.py::test_get_token_at_offset", + "tests/test_parse.py::test_wildcard_multiplication", + "tests/test_parse.py::test_stmt_tokens_parents", + "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", + "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", + "tests/test_parse.py::test_get_real_name", + "tests/test_parse.py::test_configurable_keywords", + "tests/test_parse.py::test_configurable_regex", + "tests/test_parse.py::test_json_operators[->]", + "tests/test_parse.py::test_json_operators[->>]", + "tests/test_parse.py::test_json_operators[#>]", + "tests/test_parse.py::test_json_operators[#>>]", + "tests/test_parse.py::test_json_operators[@>]", + "tests/test_parse.py::test_json_operators[<@]", + "tests/test_parse.py::test_json_operators[||]", + "tests/test_parse.py::test_json_operators[-]", + "tests/test_parse.py::test_json_operators[#-]", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue26[--hello]", + "tests/test_regressions.py::test_issue26[--hello\\n]", + "tests/test_regressions.py::test_issue26[--]", + "tests/test_regressions.py::test_issue26[--\\n]", + "tests/test_regressions.py::test_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_regressions.py::test_stream", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_except_formatting", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue190_open_file", + "tests/test_regressions.py::test_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue186_get_type", + "tests/test_regressions.py::test_issue212_py2unicode", + "tests/test_regressions.py::test_issue213_leadingws", + "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue469_copy_as_psql_command", + "tests/test_regressions.py::test_issue485_split_multi", + "tests/test_regressions.py::test_issue489_tzcasts", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "tests/test_split.py::test_split_backslash", + "tests/test_split.py::test_split_create_function[function.sql]", + "tests/test_split.py::test_split_create_function[function_psql.sql]", + "tests/test_split.py::test_split_create_function[function_psql2.sql]", + "tests/test_split.py::test_split_create_function[function_psql3.sql]", + "tests/test_split.py::test_split_create_function[function_psql4.sql]", + "tests/test_split.py::test_split_dashcomments", + "tests/test_split.py::test_split_begintag", + "tests/test_split.py::test_split_begintag_2", + "tests/test_split.py::test_split_dropif", + "tests/test_split.py::test_split_comment_with_umlaut", + "tests/test_split.py::test_split_comment_end_of_line", + "tests/test_split.py::test_split_casewhen", + "tests/test_split.py::test_split_casewhen_procedure", + "tests/test_split.py::test_split_cursor_declare", + "tests/test_split.py::test_split_if_function", + "tests/test_split.py::test_split_stream", + "tests/test_split.py::test_split_encoding_parsestream", + "tests/test_split.py::test_split_unicode_parsestream", + "tests/test_split.py::test_split_simple", + "tests/test_split.py::test_split_ignores_empty_newlines", + "tests/test_split.py::test_split_quotes_with_new_line", + "tests/test_split.py::test_split_mysql_handler_for", + "tests/test_split.py::test_split_strip_semicolon_procedure", + "tests/test_split.py::test_split_multiple_case_in_begin", + "tests/test_tokenize.py::test_tokenize_simple", + "tests/test_tokenize.py::test_tokenize_backticks", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", + "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", + "tests/test_tokenize.py::test_tokenize_inline_keywords", + "tests/test_tokenize.py::test_tokenize_negative_numbers", + "tests/test_tokenize.py::test_token_str", + "tests/test_tokenize.py::test_token_repr", + "tests/test_tokenize.py::test_token_flatten", + "tests/test_tokenize.py::test_tokenlist_repr", + "tests/test_tokenize.py::test_single_quotes", + "tests/test_tokenize.py::test_tokenlist_first", + "tests/test_tokenize.py::test_tokenlist_token_matching", + "tests/test_tokenize.py::test_stream_simple", + "tests/test_tokenize.py::test_stream_error", + "tests/test_tokenize.py::test_parse_join[JOIN]", + "tests/test_tokenize.py::test_parse_union", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", + "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", + "tests/test_tokenize.py::test_parse_order[ASC]", + "tests/test_tokenize.py::test_parse_order[DESC]", + "tests/test_tokenize.py::test_parse_identifiers[foo]", + "tests/test_tokenize.py::test_parse_identifiers[Foo]", + "tests/test_tokenize.py::test_parse_identifiers[FOO]", + "tests/test_tokenize.py::test_parse_identifiers[v$name]", + "tests/test_tokenize.py::test_parse_group_by", + "tests/test_tokenize.py::test_parse_order_by", + "tests/test_tokenize.py::test_parse_window_as", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", + "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", + "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", + "tests/test_tokenize.py::test_cli_commands", + "tests/test_utils.py::test_remove_quotes[None-None]", + "tests/test_utils.py::test_remove_quotes['foo'-foo]", + "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", + "tests/test_utils.py::test_remove_quotes[`foo`-foo]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/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/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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 pytest" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/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/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2671, + "mode": 420, + "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 1571, + "mode": 420, + "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" + }, + "tests/files/_Make_DirEntry.sql": { + "bytes": 109, + "mode": 420, + "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" + }, + "tests/files/begintag.sql": { + "bytes": 45, + "mode": 420, + "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" + }, + "tests/files/begintag_2.sql": { + "bytes": 357, + "mode": 420, + "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" + }, + "tests/files/casewhen_procedure.sql": { + "bytes": 150, + "mode": 420, + "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" + }, + "tests/files/dashcomment.sql": { + "bytes": 88, + "mode": 420, + "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" + }, + "tests/files/encoding_gbk.sql": { + "bytes": 50, + "mode": 420, + "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" + }, + "tests/files/encoding_utf8.sql": { + "bytes": 76, + "mode": 420, + "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" + }, + "tests/files/function.sql": { + "bytes": 187, + "mode": 420, + "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" + }, + "tests/files/function_psql.sql": { + "bytes": 3066, + "mode": 420, + "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" + }, + "tests/files/function_psql2.sql": { + "bytes": 177, + "mode": 420, + "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" + }, + "tests/files/function_psql3.sql": { + "bytes": 171, + "mode": 420, + "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" + }, + "tests/files/function_psql4.sql": { + "bytes": 221, + "mode": 420, + "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" + }, + "tests/files/huge_select.sql": { + "bytes": 9434, + "mode": 420, + "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" + }, + "tests/files/multiple_case_in_begin.sql": { + "bytes": 193, + "mode": 420, + "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" + }, + "tests/files/mysql_handler.sql": { + "bytes": 134, + "mode": 420, + "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" + }, + "tests/files/stream.sql": { + "bytes": 44, + "mode": 420, + "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" + }, + "tests/files/test_cp1251.sql": { + "bytes": 49, + "mode": 420, + "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" + }, + "tests/test_cli.py": { + "bytes": 3521, + "mode": 420, + "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" + }, + "tests/test_format.py": { + "bytes": 28438, + "mode": 420, + "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" + }, + "tests/test_grouping.py": { + "bytes": 23973, + "mode": 420, + "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" + }, + "tests/test_keywords.py": { + "bytes": 447, + "mode": 420, + "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" + }, + "tests/test_parse.py": { + "bytes": 18335, + "mode": 420, + "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" + }, + "tests/test_regressions.py": { + "bytes": 14896, + "mode": 420, + "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" + }, + "tests/test_split.py": { + "bytes": 6147, + "mode": 420, + "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" + }, + "tests/test_tokenize.py": { + "bytes": 6364, + "mode": 420, + "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" + }, + "tests/test_utils.py": { + "bytes": 268, + "mode": 420, + "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sqlparse" +description = "A non-validating SQL parser." +authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}] +readme = "README.rst" +dynamic = ["version"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Database", + "Topic :: Software Development", +] +requires-python = ">=3.8" + +[project.urls] +Home = "https://github.com/andialbrecht/sqlparse" +Documentation = "https://sqlparse.readthedocs.io/" +"Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html" +Source = "https://github.com/andialbrecht/sqlparse" +Tracker = "https://github.com/andialbrecht/sqlparse/issues" + +[project.scripts] +sqlformat = "sqlparse.__main__:main" + +[project.optional-dependencies] +dev = [ + "hatch", + "build", +] +doc = [ + "sphinx", +] + +[tool.hatch.version] +path = "sqlparse/__init__.py" + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + # switch to ruff, but fix problems first + # but check defaults! + # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings + "flake8", +] +[tool.hatch.envs.default.scripts] +unittest = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +check = "flake8 sqlparse/" +test = ["check", "unittest"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.types] +dependencies = [ + "mypy>=1.0.0", +] +[tool.hatch.envs.types.scripts] +check = "mypy --install-types --non-interactive {args:sqlparse tests}" + +[tool.coverage.run] +source_pkgs = ["sqlparse", "tests"] +branch = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import os + +import pytest + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function + # Alternate solution is to use parametrization `indirect=True` + # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link +-- Delete the direntry when is removed it's last static link + AFTER DELETE ON links + WHEN NOT EXISTS + ( + SELECT * FROM links + WHERE child_entry = OLD.child_entry + LIMIT 1 + ) +BEGIN + DELETE FROM dir_entries + WHERE dir_entries.inode = OLD.child_entry; +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE FUNCTION foo( + p_in1 VARCHAR + , p_in2 INTEGER +) RETURNS INTEGER AS + + DECLARE + v_foo INTEGER; + BEGIN + SELECT * + FROM foo + INTO v_foo; + RETURN v_foo.id; + END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE OR REPLACE FUNCTION public.delete_data ( + p_tabelle VARCHAR + , p_key VARCHAR + , p_value INTEGER +) RETURNS INTEGER AS +$$ +DECLARE + p_retval INTEGER; + v_constraint RECORD; + v_count INTEGER; + v_data RECORD; + v_fieldname VARCHAR; + v_sql VARCHAR; + v_key VARCHAR; + v_value INTEGER; +BEGIN + v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql INTO v_count; + IF v_count::integer != 0 THEN + SELECT att.attname + INTO v_key + FROM pg_attribute att + LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid + AND con.conkey[1] = att.attnum + AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns + WHERE att.attrelid = rel.oid + AND att.attnum > 0 + AND typ.oid = att.atttypid + AND att.attisdropped = false + AND rel.relname = p_tabelle + AND con.conkey[1] = 1 + AND ns.oid = rel.relnamespace + AND ns.nspname = 'public' + ORDER BY att.attnum; + v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + FOR v_data IN EXECUTE v_sql + LOOP + --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; + FOR v_constraint IN SELECT t.constraint_name + , t.constraint_type + , t.table_name + , c.column_name + FROM public.v_table_constraints t + , public.v_constraint_columns c + WHERE t.constraint_name = c.constraint_name + AND t.constraint_type = 'FOREIGN KEY' + AND c.table_name = p_tabelle + AND t.table_schema = 'public' + AND c.table_schema = 'public' + LOOP + v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); + IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN + --RAISE NOTICE 'Skip (Selbstverweis)'; + CONTINUE; + ELSE + PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); + END IF; + END LOOP; + END LOOP; + v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; + --RAISE NOTICE '%', v_sql; + EXECUTE v_sql; + p_retval := 1; + ELSE + --RAISE NOTICE ' -> Keine Sätze gefunden'; + p_retval := 0; + END IF; + RETURN p_retval; +END; +$$ +LANGUAGE plpgsql; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import sys + +import pytest + +import sqlparse + + +def test_cli_main_empty(): + with pytest.raises(SystemExit): + sqlparse.cli.main([]) + + +def test_parser_empty(): + with pytest.raises(SystemExit): + parser = sqlparse.cli.create_parser() + parser.parse_args([]) + + +def test_main_help(): + # Call with the --help option as a basic sanity check. + with pytest.raises(SystemExit) as exinfo: + sqlparse.cli.main(["--help", ]) + assert exinfo.value.code == 0 + + +def test_valid_args(filepath): + # test doesn't abort + path = filepath('function.sql') + assert sqlparse.cli.main([path, '-r']) is not None + + +def test_invalid_choice(filepath): + path = filepath('function.sql') + with pytest.raises(SystemExit): + sqlparse.cli.main([path, '-l', 'Spanish']) + + +def test_invalid_args(filepath, capsys): + path = filepath('function.sql') + sqlparse.cli.main([path, '-r', '--indent_width', '0']) + _, err = capsys.readouterr() + assert err == ("[ERROR] Invalid options: indent_width requires " + "a positive integer\n") + + +def test_invalid_infile(filepath, capsys): + path = filepath('missing.sql') + sqlparse.cli.main([path, '-r']) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to read" + + +def test_invalid_outfile(filepath, capsys): + path = filepath('function.sql') + outpath = filepath('/missing/function.sql') + sqlparse.cli.main([path, '-r', '-o', outpath]) + _, err = capsys.readouterr() + assert err[:22] == "[ERROR] Failed to open" + + +def test_stdout(filepath, load_file, capsys): + path = filepath('begintag.sql') + expected = load_file('begintag.sql') + sqlparse.cli.main([path]) + out, _ = capsys.readouterr() + assert out == expected + + +def test_script(): + # Call with the --help option as a basic sanity check. + cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] + assert subprocess.call(cmd) == 0 + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + sqlparse.cli.main([path, '--encoding', encoding]) + out, _ = capfd.readouterr() + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): + in_path = filepath(fpath) + expected = load_file(fpath, encoding) + out_path = tmpdir.dirname + '/encoding_out.sql' + sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) + out = load_file(out_path, encoding) + assert out == expected + + +@pytest.mark.parametrize('fpath, encoding', ( + ('encoding_utf8.sql', 'utf-8'), + ('encoding_gbk.sql', 'gbk'), +)) +def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): + path = filepath(fpath) + expected = load_file(fpath, encoding) + old_stdin = sys.stdin + with open(path) as f: + sys.stdin = f + sqlparse.cli.main(['-', '--encoding', encoding]) + sys.stdin = old_stdin + out, _ = capfd.readouterr() + assert out == expected + + +def test_encoding(filepath, capsys): + path = filepath('test_cp1251.sql') + expected = 'insert into foo values (1); -- Песня про надежду\n' + sqlparse.cli.main([path, '--encoding=cp1251']) + out, _ = capsys.readouterr() + assert out == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from sqlparse.exceptions import SQLParseError + + +class TestFormat: + def test_keywordcase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='upper') + assert res == 'SELECT * FROM bar; -- select foo\n' + res = sqlparse.format(sql, keyword_case='capitalize') + assert res == 'Select * From bar; -- select foo\n' + res = sqlparse.format(sql.upper(), keyword_case='lower') + assert res == 'select * from BAR; -- SELECT FOO\n' + + def test_keywordcase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, keyword_case='foo') + + def test_identifiercase(self): + sql = 'select * from bar; -- select foo\n' + res = sqlparse.format(sql, identifier_case='upper') + assert res == 'select * from BAR; -- select foo\n' + res = sqlparse.format(sql, identifier_case='capitalize') + assert res == 'select * from Bar; -- select foo\n' + res = sqlparse.format(sql.upper(), identifier_case='lower') + assert res == 'SELECT * FROM bar; -- SELECT FOO\n' + + def test_identifiercase_invalid_option(self): + sql = 'select * from bar; -- select foo\n' + with pytest.raises(SQLParseError): + sqlparse.format(sql, identifier_case='foo') + + def test_identifiercase_quotes(self): + sql = 'select * from "foo"."bar"' + res = sqlparse.format(sql, identifier_case="upper") + assert res == 'select * from "foo"."bar"' + + def test_strip_comments_single(self): + sql = 'select *-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select-- foo\nfrom -- bar\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select\nfrom\nwhere' + sql = 'select *-- statement starts here\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * from foo-- statement starts here\nwhere' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select * from foo\nwhere' + sql = 'select a-- statement starts here\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo' + sql = '--comment\nselect a-- statement starts here\n' \ + 'from foo--comment\nf' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select a\nfrom foo\nf' + + def test_strip_comments_invalid_option(self): + sql = 'select-- foo\nfrom -- bar\nwhere' + with pytest.raises(SQLParseError): + sqlparse.format(sql, strip_comments=None) + + def test_strip_comments_multi(self): + sql = '/* sql starts here */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = '/* sql starts here */ select' + res = sqlparse.format(sql, strip_comments=True) + assert res == ' select' # note whitespace is preserved, see issue 772 + sql = '/*\n * sql starts here\n */\nselect' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select' + sql = 'select (/* sql starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + sql = 'select (/* sql /* starts here */ select 2)' + res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) + assert res == 'select (select 2)' + + def test_strip_comments_preserves_linebreak(self): + sql = 'select * -- a comment\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\rfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\nfrom foo' + sql = 'select * -- a comment\r\n\r\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + sql = 'select * -- a comment\n\nfrom foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select *\n\nfrom foo' + + def test_strip_comments_preserves_whitespace(self): + sql = 'SELECT 1/*bar*/ AS foo' # see issue772 + res = sqlparse.format(sql, strip_comments=True) + assert res == 'SELECT 1 AS foo' + + def test_strip_comments_preserves_hint(self): + sql = 'select --+full(u)' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = '#+ hint\nselect * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'select --+full(u)\n--comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == 'select --+full(u)\n' + sql = '#+ hint\nselect * from foo\n# comment simple' + res = sqlparse.format(sql, strip_comments=True) + assert res == '#+ hint\nselect * from foo\n' + sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' + res = sqlparse.format(sql, strip_comments=True) + assert res == sql + + def test_strip_ws(self): + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' + assert f(s) == 'select * from foo where (1 = 2)' + s = 'select -- foo\nfrom bar\n' + assert f(s) == 'select -- foo\nfrom bar' + + def test_strip_ws_invalid_option(self): + s = 'select -- foo\nfrom bar\n' + with pytest.raises(SQLParseError): + sqlparse.format(s, strip_whitespace=None) + + def test_preserve_ws(self): + # preserve at least one whitespace after subgroups + f = lambda sql: sqlparse.format(sql, strip_whitespace=True) + s = 'select\n* /* foo */ from bar ' + assert f(s) == 'select * /* foo */ from bar' + + def test_notransform_of_quoted_crlf(self): + # Make sure that CR/CR+LF characters inside string literals don't get + # affected by the formatter. + + s1 = "SELECT some_column LIKE 'value\r'" + s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" + s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" + s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n" + + f = lambda x: sqlparse.format(x) + + # Because of the use of + assert f(s1) == "SELECT some_column LIKE 'value\r'" + assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" + assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" + assert (f(s4) + == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n") + + +class TestFormatReindentAligned: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, reindent_aligned=True) + + def test_basic(self): + sql = """ + select a, b as bb,c from table + join (select a * 2 as a from new_table) other + on table.a = other.a + where c is true + and b between 3 and 4 + or d is 'blue' + limit 10 + """ + + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b as bb,', + ' c', + ' from table', + ' join (', + ' select a * 2 as a', + ' from new_table', + ' ) other', + ' on table.a = other.a', + ' where c is true', + ' and b between 3 and 4', + " or d is 'blue'", + ' limit 10']) + + def test_joins(self): + sql = """ + select * from a + join b on a.one = b.one + left join c on c.two = a.two and c.three = a.three + full outer join d on d.three = a.three + cross join e on e.four = a.four + join f using (one, two, three) + """ + assert self.formatter(sql) == '\n'.join([ + 'select *', + ' from a', + ' join b', + ' on a.one = b.one', + ' left join c', + ' on c.two = a.two', + ' and c.three = a.three', + ' full outer join d', + ' on d.three = a.three', + ' cross join e', + ' on e.four = a.four', + ' join f using (one, two, three)']) + + def test_case_statement(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_case_statement_with_between(self): + sql = """ + select a, + case when a = 0 + then 1 + when bb = 1 then 1 + when c = 2 then 2 + when d between 3 and 5 then 3 + else 0 end as d, + extra_col + from table + where c is true + and b between 3 and 4 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' case when a = 0 then 1', + ' when bb = 1 then 1', + ' when c = 2 then 2', + ' when d between 3 and 5 then 3', + ' else 0', + ' end as d,', + ' extra_col', + ' from table', + ' where c is true', + ' and b between 3 and 4']) + + def test_group_by(self): + sql = """ + select a, b, c, sum(x) as sum_x, count(y) as cnt_y + from table + group by a,b,c + having sum(x) > 1 + and count(y) > 5 + order by 3,2,1 + """ + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' b,', + ' c,', + ' sum(x) as sum_x,', + ' count(y) as cnt_y', + ' from table', + ' group by a,', + ' b,', + ' c', + 'having sum(x) > 1', + ' and count(y) > 5', + ' order by 3,', + ' 2,', + ' 1']) + + def test_group_by_subquery(self): + # TODO: add subquery alias when test_identifier_list_subquery fixed + sql = """ + select *, sum_b + 2 as mod_sum + from ( + select a, sum(b) as sum_b + from table + group by a,z) + order by 1,2 + """ + assert self.formatter(sql) == '\n'.join([ + 'select *,', + ' sum_b + 2 as mod_sum', + ' from (', + ' select a,', + ' sum(b) as sum_b', + ' from table', + ' group by a,', + ' z', + ' )', + ' order by 1,', + ' 2']) + + def test_window_functions(self): + sql = """ + select a, + SUM(a) OVER (PARTITION BY b ORDER BY c ROWS + BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, + ROW_NUMBER() OVER + (PARTITION BY b, c ORDER BY d DESC) as row_num + from table""" + assert self.formatter(sql) == '\n'.join([ + 'select a,', + ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' + 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', + ' ROW_NUMBER() OVER ' + '(PARTITION BY b, c ORDER BY d DESC) as row_num', + ' from table']) + + +class TestSpacesAroundOperators: + @staticmethod + def formatter(sql): + return sqlparse.format(sql, use_space_around_operators=True) + + def test_basic(self): + sql = ('select a+b as d from table ' + 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') + assert self.formatter(sql) == ( + 'select a + b as d from table ' + 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100') + + def test_bools(self): + sql = 'select * from table where a &&b or c||d' + assert self.formatter( + sql) == 'select * from table where a && b or c || d' + + def test_nested(self): + sql = 'select *, case when a-b then c end from table' + assert self.formatter( + sql) == 'select *, case when a - b then c end from table' + + def test_wildcard_vs_mult(self): + sql = 'select a*b-c from table' + assert self.formatter(sql) == 'select a * b - c from table' + + +class TestFormatReindent: + def test_option(self): + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', indent_tabs=2) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, indent_width=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after='foo') + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, wrap_after=-12) + with pytest.raises(SQLParseError): + sqlparse.format('foo', reindent=True, comma_first='foo') + + def test_stmts(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo; select bar' + assert f(s) == 'select foo;\n\nselect bar' + s = 'select foo' + assert f(s) == 'select foo' + s = 'select foo; -- test\n select bar' + assert f(s) == 'select foo; -- test\n\nselect bar' + + def test_keywords(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo union select * from bar;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'union', + 'select *', + 'from bar;']) + + def test_keywords_between(self): + # issue 14 + # don't break AND after BETWEEN + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'and foo between 1 and 2 and bar = 3' + assert f(s) == '\n'.join([ + '', + 'and foo between 1 and 2', + 'and bar = 3']) + + def test_parenthesis(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select count(*) from (select * from foo);' + assert f(s) == '\n'.join([ + 'select count(*)', + 'from', + ' (select *', + ' from foo);']) + assert f("select f(1)") == 'select f(1)' + assert f("select f( 1 )") == 'select f(1)' + assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' + + def test_where(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and baz = 2', + ' or bzz = 3;']) + + s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'where bar = 1', + ' and (baz = 2', + ' or bzz = 3);']) + + def test_join(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select * from foo join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'join bar on 1 = 2']) + s = 'select * from foo inner join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'inner join bar on 1 = 2']) + s = 'select * from foo left outer join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'left outer join bar on 1 = 2']) + s = 'select * from foo straight_join bar on 1 = 2' + assert f(s) == '\n'.join([ + 'select *', + 'from foo', + 'straight_join bar on 1 = 2']) + + def test_identifier_list(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo,', + ' bar,', + ' baz', + 'from table1,', + ' table2', + 'where 1 = 2']) + s = 'select a.*, b.id from a, b' + assert f(s) == '\n'.join([ + 'select a.*,', + ' b.id', + 'from a,', + ' b']) + + def test_identifier_list_with_wrap_after(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) + s = 'select foo, bar, baz from table1, table2 where 1 = 2' + assert f(s) == '\n'.join([ + 'select foo, bar,', + ' baz', + 'from table1, table2', + 'where 1 = 2']) + + def test_identifier_list_comment_first(self): + f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) + # not the 3: It cleans up whitespace too! + s = 'select foo, bar, baz from table where foo in (1, 2,3)' + assert f(s) == '\n'.join([ + 'select foo', + ' , bar', + ' , baz', + 'from table', + 'where foo in (1', + ' , 2', + ' , 3)']) + + def test_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " coalesce(col1, col2)||col3 as bar,", + " col3", + "from my_table"]) + + def test_long_identifier_list_with_functions(self): + f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) + s = ("select 'abc' as foo, json_build_object('a', a," + "'b', b, 'c', c, 'd', d, 'e', e) as col2" + "col3 from my_table") + assert f(s) == '\n'.join([ + "select 'abc' as foo,", + " json_build_object('a',", + " a, 'b', b, 'c', c, 'd', d,", + " 'e', e) as col2col3", + "from my_table"]) + + def test_case(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' + assert f(s) == '\n'.join([ + 'case', + ' when foo = 1 then 2', + ' when foo = 3 then 4', + ' else 5', + 'end']) + + def test_case2(self): + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'case(foo) when bar = 1 then 2 else 3 end' + assert f(s) == '\n'.join([ + 'case(foo)', + ' when bar = 1 then 2', + ' else 3', + 'end']) + + def test_nested_identifier_list(self): + # issue4 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' + assert f(s) == '\n'.join([ + '(foo as bar,', + ' bar1,', + ' bar2 as bar3,', + ' b4 as b5)']) + + def test_duplicate_linebreaks(self): + # issue3 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select c1 -- column1\nfrom foo' + assert f(s) == '\n'.join([ + 'select c1 -- column1', + 'from foo']) + s = 'select c1 -- column1\nfrom foo' + r = sqlparse.format(s, reindent=True, strip_comments=True) + assert r == '\n'.join([ + 'select c1', + 'from foo']) + s = 'select c1\nfrom foo\norder by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from foo', + 'order by c1']) + s = 'select c1 from t1 where (c1 = 1) order by c1' + assert f(s) == '\n'.join([ + 'select c1', + 'from t1', + 'where (c1 = 1)', + 'order by c1']) + + def test_keywordfunctions(self): + # issue36 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select max(a) b, foo, bar' + assert f(s) == '\n'.join([ + 'select max(a) b,', + ' foo,', + ' bar']) + + def test_identifier_and_functions(self): + # issue45 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'select foo.bar, nvl(1) from dual' + assert f(s) == '\n'.join([ + 'select foo.bar,', + ' nvl(1)', + 'from dual']) + + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + +class TestOutputFormat: + def test_python(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == "sql = 'select * from foo;'" + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')"]) + + def test_python_multiple_statements(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python') + assert f(sql) == '\n'.join([ + "sql = 'select * from foo; '", + "sql2 = 'select 1 from dual'"]) + + @pytest.mark.xfail(reason="Needs fixing") + def test_python_multiple_statements_with_formatting(self): + sql = 'select * from foo; select 1 from dual' + f = lambda sql: sqlparse.format(sql, output_format='python', + reindent=True) + assert f(sql) == '\n'.join([ + "sql = ('select * '", + " 'from foo;')", + "sql2 = ('select 1 '", + " 'from dual')"]) + + def test_php(self): + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='php') + assert f(sql) == '$sql = "select * from foo;";' + f = lambda sql: sqlparse.format(sql, output_format='php', + reindent=True) + assert f(sql) == '\n'.join([ + '$sql = "select * ";', + '$sql .= "from foo;";']) + + def test_sql(self): + # "sql" is an allowed option but has no effect + sql = 'select * from foo;' + f = lambda sql: sqlparse.format(sql, output_format='sql') + assert f(sql) == 'select * from foo;' + + def test_invalid_option(self): + sql = 'select * from foo;' + with pytest.raises(SQLParseError): + sqlparse.format(sql, output_format='foo') + + +def test_format_column_ordering(): + # issue89 + sql = 'select * from foo order by c1 desc, c2, c3;' + formatted = sqlparse.format(sql, reindent=True) + expected = '\n'.join([ + 'select *', + 'from foo', + 'order by c1 desc,', + ' c2,', + ' c3;']) + assert formatted == expected + + +def test_truncate_strings(): + sql = "update foo set value = '{}';".format('x' * 1000) + formatted = sqlparse.format(sql, truncate_strings=10) + assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" + formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') + assert formatted == "update foo set value = 'xxxYYY';" + + +@pytest.mark.parametrize('option', ['bar', -1, 0]) +def test_truncate_strings_invalid_option2(option): + with pytest.raises(SQLParseError): + sqlparse.format('foo', truncate_strings=option) + + +@pytest.mark.parametrize('sql', [ + 'select verrrylongcolumn from foo', + 'select "verrrylongcolumn" from "foo"']) +def test_truncate_strings_doesnt_truncate_identifiers(sql): + formatted = sqlparse.format(sql, truncate_strings=2) + assert formatted == sql + + +def test_having_produces_newline(): + sql = ('select * from foo, bar where bar.id = foo.bar_id ' + 'having sum(bar.value) > 100') + formatted = sqlparse.format(sql, reindent=True) + expected = [ + 'select *', + 'from foo,', + ' bar', + 'where bar.id = foo.bar_id', + 'having sum(bar.value) > 100'] + assert formatted == '\n'.join(expected) + + +@pytest.mark.parametrize('right_margin', ['ten', 2]) +def test_format_right_margin_invalid_option(right_margin): + with pytest.raises(SQLParseError): + sqlparse.format('foo', right_margin=right_margin) + + +@pytest.mark.xfail(reason="Needs fixing") +def test_format_right_margin(): + # TODO: Needs better test, only raises exception right now + sqlparse.format('foo', right_margin="79") + + +def test_format_json_ops(): # issue542 + formatted = sqlparse.format( + "select foo->'bar', foo->'bar';", reindent=True) + expected = "select foo->'bar',\n foo->'bar';" + assert formatted == expected + + +@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ + ('case when foo then 1 else bar end', + 'case\n when foo then 1\n else bar\nend', + 'case when foo then 1 else bar end')]) +def test_compact(sql, expected_normal, expected_compact): # issue783 + formatted_normal = sqlparse.format(sql, reindent=True) + formatted_compact = sqlparse.format(sql, reindent=True, compact=True) + assert formatted_normal == expected_normal + assert formatted_compact == expected_compact + + +def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 + formatted = sqlparse.format('( where foo = bar ) from', + strip_whitespace=True) + expected = '(where foo = bar) from' + assert formatted == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from sqlparse import sql, tokens as T + + +def test_grouping_parenthesis(): + s = 'select (select (x3) x2) and (y2) bar' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.Parenthesis) + assert isinstance(parsed.tokens[-1], sql.Identifier) + assert len(parsed.tokens[2].tokens) == 5 + assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) + assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) + assert len(parsed.tokens[2].tokens[3].tokens) == 3 + + +@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1']) +def test_grouping_assignment(s): + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 1 + assert isinstance(parsed.tokens[0], sql.Assignment) + + +@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"]) +def test_grouping_typed_literal(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed[0][4], sql.TypedLiteral) + + +@pytest.mark.parametrize('s, a, b', [ + ('select a from b where c < d + e', sql.Identifier, sql.Identifier), + ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), + ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral), +]) +def test_compare_expr(s, a, b): + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + assert len(parsed.tokens) == 9 + where = parsed.tokens[8] + assert isinstance(where.tokens[2], sql.Comparison) + assert len(where.tokens) == 3 + comparison = where.tokens[2] + assert isinstance(comparison.tokens[0], sql.Identifier) + assert comparison.tokens[2].ttype is T.Operator.Comparison + assert isinstance(comparison.tokens[4], sql.Operation) + assert len(comparison.tokens) == 5 + operation = comparison.tokens[4] + assert isinstance(operation.tokens[0], a) + assert operation.tokens[2].ttype is T.Operator + assert isinstance(operation.tokens[4], b) + assert len(operation.tokens) == 5 + + +def test_grouping_identifiers(): + s = 'select foo.bar from "myscheme"."table" where fail. order' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[2], sql.Identifier) + assert isinstance(parsed.tokens[6], sql.Identifier) + assert isinstance(parsed.tokens[8], sql.Where) + s = 'select * from foo where foo.id = 1' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) + s = 'select * from (select "foo"."id" from foo)' + parsed = sqlparse.parse(s)[0] + assert str(parsed) == s + assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) + + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) + + s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" + parsed = sqlparse.parse(s)[0] + assert len(parsed.tokens) == 7 + assert isinstance(parsed.tokens[2], sql.IdentifierList) + assert len(parsed.tokens[2].tokens) == 4 + identifiers = list(parsed.tokens[2].get_identifiers()) + assert len(identifiers) == 2 + assert identifiers[0].get_alias() == "col" + + +@pytest.mark.parametrize('s', [ + '1 as f', + 'foo as f', + 'foo f', + '1/2 as f', + '1/2 f', + '1<2 as f', # issue327 + '1<2 f', +]) +def test_simple_identifiers(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.Identifier) + + +@pytest.mark.parametrize('s', [ + 'foo, bar', + 'sum(a), sum(b)', + 'sum(a) as x, b as y', + 'sum(a)::integer, b', + 'sum(a)/count(b) as x, y', + 'sum(a)::integer as x, y', + 'sum(a)::integer/count(b) as x, y', # issue297 +]) +def test_group_identifier_list(s): + parsed = sqlparse.parse(s)[0] + assert isinstance(parsed.tokens[0], sql.IdentifierList) + + +def test_grouping_identifier_wildcard(): + p = sqlparse.parse('a.*, b.id')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[-1], sql.Identifier) + + +def test_grouping_identifier_name_wildcard(): + p = sqlparse.parse('a.*')[0] + t = p.tokens[0] + assert t.get_name() == '*' + assert t.is_wildcard() is True + + +def test_grouping_identifier_invalid(): + p = sqlparse.parse('a.')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert p.tokens[0].has_alias() is False + assert p.tokens[0].get_name() is None + assert p.tokens[0].get_real_name() is None + assert p.tokens[0].get_parent_name() == 'a' + + +def test_grouping_identifier_invalid_in_middle(): + # issue261 + s = 'SELECT foo. FROM foo' + p = sqlparse.parse(s)[0] + assert isinstance(p[2], sql.Identifier) + assert p[2][1].ttype == T.Punctuation + assert p[3].ttype == T.Whitespace + assert str(p[2]) == 'foo.' + +@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)']) +def test_grouping_identifer_as(s): + # issue507 + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Identifier) + token = p.tokens[0].tokens[2] + assert token.ttype == T.Keyword + assert token.normalized == 'AS' + +def test_grouping_identifier_as_invalid(): + # issue8 + p = sqlparse.parse('foo as select *')[0] + assert len(p.tokens), 5 + assert isinstance(p.tokens[0], sql.Identifier) + assert len(p.tokens[0].tokens) == 1 + assert p.tokens[2].ttype == T.Keyword + + +def test_grouping_identifier_function(): + p = sqlparse.parse('foo() as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo()||col2 bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Operation) + assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) + p = sqlparse.parse('foo(c1) over win1 as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Identifier) + p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] + assert isinstance(p.tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[0], sql.Function) + assert len(p.tokens[0].tokens[0].tokens) == 4 + assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) + assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], + sql.Parenthesis) + + +@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100']) +def test_grouping_operation(s): + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[0], sql.Operation) + + +def test_grouping_identifier_list(): + p = sqlparse.parse('a, b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_subquery(): + """identifier lists should still work in subqueries with aliases""" + p = sqlparse.parse("select * from (" + "select a, b + c as d from table) sub")[0] + subquery = p.tokens[-1].tokens[0] + idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) + assert iden_list is not None + # all the identifiers should be within the IdentifierList + _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) + assert ilist is None + + +def test_grouping_identifier_list_case(): + p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList) + + +def test_grouping_identifier_list_other(): + # issue2 + p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] + assert isinstance(p.tokens[2], sql.IdentifierList) + assert len(p.tokens[2].tokens) == 13 + + +def test_grouping_identifier_list_with_inline_comments(): + # issue163 + p = sqlparse.parse('foo /* a comment */, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[0], sql.Identifier) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + + +def test_grouping_identifiers_with_operators(): + p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] + assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5 + + +def test_grouping_identifier_list_with_order(): + # issue101 + p = sqlparse.parse('1, 2 desc, 3')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + assert isinstance(p.tokens[0].tokens[3], sql.Identifier) + assert str(p.tokens[0].tokens[3]) == '2 desc' + + +def test_grouping_nested_identifier_with_order(): + # issue745 + p = sqlparse.parse('(a desc)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert isinstance(p.tokens[0].tokens[1], sql.Identifier) + assert str(p.tokens[0].tokens[1]) == 'a desc' + + +def test_grouping_where(): + s = 'select * from foo where bar = 1 order by id desc' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert len(p.tokens) == 12 + + s = 'select x from (select y from foo where bar = 1) z' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where) + + +@pytest.mark.parametrize('s', ( + 'select 1 where 1 = 2 union select 2', + 'select 1 where 1 = 2 union all select 2', +)) +def test_grouping_where_union(s): + p = sqlparse.parse(s)[0] + assert p.tokens[5].value.startswith('union') + + +def test_returning_kw_ends_where_clause(): + s = 'delete from foo where x > y returning z' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[6], sql.Where) + assert p.tokens[7].ttype == T.Keyword + assert p.tokens[7].value == 'returning' + + +def test_into_kw_ends_where_clause(): # issue324 + s = 'select * from foo where a = 1 into baz' + p = sqlparse.parse(s)[0] + assert isinstance(p.tokens[8], sql.Where) + assert p.tokens[9].ttype == T.Keyword + assert p.tokens[9].value == 'into' + + +@pytest.mark.parametrize('sql, expected', [ + # note: typecast needs to be 2nd token for this test + ('select foo::integer from bar', 'integer'), + ('select (current_database())::information_schema.sql_identifier', + 'information_schema.sql_identifier'), +]) +def test_grouping_typecast(sql, expected): + p = sqlparse.parse(sql)[0] + assert p.tokens[2].get_typecast() == expected + + +def test_grouping_alias(): + s = 'select foo as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_real_name() == 'foo' + assert p.tokens[2].get_alias() == 'bar' + s = 'select foo from mytable t1' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[6].get_real_name() == 'mytable' + assert p.tokens[6].get_alias() == 't1' + s = 'select foo::integer as bar from mytable' + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[2].get_alias() == 'bar' + s = ('SELECT DISTINCT ' + '(current_database())::information_schema.sql_identifier AS view') + p = sqlparse.parse(s)[0] + assert str(p) == s + assert p.tokens[4].get_alias() == 'view' + + +def test_grouping_alias_case(): + # see issue46 + p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() == 'foo' + + +def test_grouping_alias_ctas(): + p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] + assert p.tokens[10].get_alias() == 'col1' + assert isinstance(p.tokens[10].tokens[0], sql.Function) + +def test_grouping_subquery_no_parens(): + # Not totally sure if this is the right approach... + # When a THEN clause contains a subquery w/o parenthesis around it *and* + # a WHERE condition, the WHERE grouper consumes END too. + # This takes makes sure that it doesn't fail. + p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Case) + + +@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y']) +def test_grouping_alias_returns_none(s): + # see issue185 and issue445 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].get_alias() is None + + +def test_grouping_idlist_function(): + # see issue10 too + p = sqlparse.parse('foo(1) x, bar')[0] + assert isinstance(p.tokens[0], sql.IdentifierList) + + +def test_grouping_comparison_exclude(): + # make sure operators are not handled too lazy + p = sqlparse.parse('(=)')[0] + assert isinstance(p.tokens[0], sql.Parenthesis) + assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + p = sqlparse.parse('(a>=1)')[0] + assert isinstance(p.tokens[0].tokens[1], sql.Comparison) + + +def test_grouping_function(): + p = sqlparse.parse('foo()')[0] + assert isinstance(p.tokens[0], sql.Function) + p = sqlparse.parse('foo(null, bar)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 2 + p = sqlparse.parse('foo(5) over win1')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Identifier) + p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] + assert isinstance(p.tokens[0], sql.Function) + assert len(list(p.tokens[0].get_parameters())) == 1 + assert isinstance(p.tokens[0].get_window(), sql.Parenthesis) + + +def test_grouping_function_not_in(): + # issue183 + p = sqlparse.parse('in(1, 2)')[0] + assert len(p.tokens) == 2 + assert p.tokens[0].ttype == T.Keyword + assert isinstance(p.tokens[1], sql.Parenthesis) + + +def test_grouping_varchar(): + p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] + assert isinstance(p.tokens[2], sql.Function) + + +def test_statement_get_type(): + def f(sql): + return sqlparse.parse(sql)[0] + + assert f('select * from foo').get_type() == 'SELECT' + assert f('update foo').get_type() == 'UPDATE' + assert f(' update foo').get_type() == 'UPDATE' + assert f('\nupdate foo').get_type() == 'UPDATE' + assert f('foo').get_type() == 'UNKNOWN' + + +def test_identifier_with_operators(): + # issue 53 + p = sqlparse.parse('foo||bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + # again with whitespaces + p = sqlparse.parse('foo || bar')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +def test_identifier_with_op_trailing_ws(): + # make sure trailing whitespace isn't grouped with identifier + p = sqlparse.parse('foo || bar ')[0] + assert len(p.tokens) == 2 + assert isinstance(p.tokens[0], sql.Operation) + assert p.tokens[1].ttype is T.Whitespace + + +def test_identifier_with_string_literals(): + p = sqlparse.parse("foo + 'bar'")[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Operation) + + +# This test seems to be wrong. It was introduced when fixing #53, but #111 +# showed that this shouldn't be an identifier at all. I'm leaving this +# commented in the source for a while. +# def test_identifier_string_concat(): +# p = sqlparse.parse("'foo' || bar")[0] +# assert len(p.tokens) == 1 +# assert isinstance(p.tokens[0], sql.Identifier) + + +def test_identifier_consumes_ordering(): + # issue89 + p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] + assert isinstance(p.tokens[-1], sql.IdentifierList) + ids = list(p.tokens[-1].get_identifiers()) + assert len(ids) == 3 + assert ids[0].get_name() == 'c1' + assert ids[0].get_ordering() == 'DESC' + assert ids[1].get_name() == 'c2' + assert ids[1].get_ordering() is None + + +def test_comparison_with_keywords(): + # issue90 + # in fact these are assignments, but for now we don't distinguish them + p = sqlparse.parse('foo = NULL')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'NULL' + # make sure it's case-insensitive + p = sqlparse.parse('foo = null')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + + +def test_comparison_with_floats(): + # issue145 + p = sqlparse.parse('foo = 25.5')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == '25.5' + + +def test_comparison_with_parenthesis(): + # issue23 + p = sqlparse.parse('(3 + 4) = 7')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + comp = p.tokens[0] + assert isinstance(comp.left, sql.Parenthesis) + assert comp.right.ttype is T.Number.Integer + + +@pytest.mark.parametrize('operator', ( + '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', + 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', +)) +def test_comparison_with_strings(operator): + # issue148 + p = sqlparse.parse("foo {} 'bar'".format(operator))[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert p.tokens[0].right.value == "'bar'" + assert p.tokens[0].right.ttype == T.String.Single + + +def test_like_and_ilike_comparison(): + def validate_where_clause(where_clause, expected_tokens): + assert len(where_clause.tokens) == len(expected_tokens) + for where_token, expected_token in zip(where_clause, expected_tokens): + expected_ttype, expected_value = expected_token + if where_token.ttype is not None: + assert where_token.match(expected_ttype, expected_value, regex=True) + else: + # Certain tokens, such as comparison tokens, do not define a ttype that can be + # matched against. For these tokens, we ensure that the token instance is of + # the expected type and has a value conforming to specified regular expression + import re + assert (isinstance(where_token, expected_ttype) + and re.match(expected_value, where_token.value)) + + [p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") + [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] + validate_where_clause(p1_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mytable.mycolumn LIKE.*"), + (T.Whitespace, None), + ]) + + [p2] = sqlparse.parse( + "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") + [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] + validate_where_clause(p2_where, [ + (T.Keyword, "where"), + (T.Whitespace, None), + (sql.Comparison, r"mycolumn NOT ILIKE.*"), + (T.Whitespace, None), + ]) + + +def test_comparison_with_functions(): + # issue230 + p = sqlparse.parse('foo = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'foo' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'DATE(bar.baz)' + + p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Comparison) + assert len(p.tokens[0].tokens) == 5 + assert p.tokens[0].left.value == 'DATE(foo.bar)' + assert p.tokens[0].right.value == 'bar.baz' + + +def test_comparison_with_typed_literal(): + p = sqlparse.parse("foo = DATE 'bar.baz'")[0] + assert len(p.tokens) == 1 + comp = p.tokens[0] + assert isinstance(comp, sql.Comparison) + assert len(comp.tokens) == 5 + assert comp.left.value == 'foo' + assert isinstance(comp.right, sql.TypedLiteral) + assert comp.right.value == "DATE 'bar.baz'" + + +@pytest.mark.parametrize('start', ['FOR', 'FOREACH']) +def test_forloops(start): + p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] + assert (len(p.tokens)) == 1 + assert isinstance(p.tokens[0], sql.For) + + +def test_nested_for(): + p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] + assert len(p.tokens) == 1 + for1 = p.tokens[0] + assert for1.tokens[0].value == 'FOR' + assert for1.tokens[-1].value == 'END LOOP' + for2 = for1.tokens[6] + assert isinstance(for2, sql.For) + assert for2.tokens[0].value == 'FOR' + assert for2.tokens[-1].value == 'END LOOP' + + +def test_begin(): + p = sqlparse.parse('BEGIN foo END')[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Begin) + + +def test_keyword_followed_by_parenthesis(): + p = sqlparse.parse('USING(somecol')[0] + assert len(p.tokens) == 3 + assert p.tokens[0].ttype == T.Keyword + assert p.tokens[1].ttype == T.Punctuation + + +def test_nested_begin(): + p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] + assert len(p.tokens) == 1 + outer = p.tokens[0] + assert outer.tokens[0].value == 'BEGIN' + assert outer.tokens[-1].value == 'END' + inner = outer.tokens[4] + assert inner.tokens[0].value == 'BEGIN' + assert inner.tokens[-1].value == 'END' + assert isinstance(inner, sql.Begin) + + +def test_aliased_column_without_as(): + p = sqlparse.parse('foo bar')[0].tokens + assert len(p) == 1 + assert p[0].get_real_name() == 'foo' + assert p[0].get_alias() == 'bar' + + p = sqlparse.parse('foo.bar baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_qualified_function(): + p = sqlparse.parse('foo()')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + + p = sqlparse.parse('foo.bar()')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + + +def test_aliased_function_without_as(): + p = sqlparse.parse('foo() bar')[0].tokens[0] + assert p.get_parent_name() is None + assert p.get_real_name() == 'foo' + assert p.get_alias() == 'bar' + + p = sqlparse.parse('foo.bar() baz')[0].tokens[0] + assert p.get_parent_name() == 'foo' + assert p.get_real_name() == 'bar' + assert p.get_alias() == 'baz' + + +def test_aliased_literal_without_as(): + p = sqlparse.parse('1 foo')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'foo' + + +def test_grouping_as_cte(): + p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens + assert len(p) > 4 + assert p[0].get_alias() is None + assert p[2].value == 'AS' + assert p[4].value == 'WITH' + +def test_grouping_create_table(): + p = sqlparse.parse("create table db.tbl (a string)")[0].tokens + assert p[4].value == "db.tbl" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from sqlparse.lexer import Lexer + + +class TestSQLREGEX: + @pytest.mark.parametrize('number', ['1.0', '-1.0', + '1.', '-1.', + '.1', '-.1']) + def test_float_numbers(self, number): + ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) + assert tokens.Number.Float == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from sqlparse.lexer import Lexer + + +def test_parse_tokenize(): + s = 'select * from foo;' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert str(stmts[0]) == s + + +def test_parse_multistatement(): + sql1 = 'select * from foo;' + sql2 = 'select * from bar;' + stmts = sqlparse.parse(sql1 + sql2) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +@pytest.mark.parametrize('s', ['select\n*from foo;', + 'select\r\n*from foo', + 'select\r*from foo', + 'select\r\n*from foo\n']) +def test_parse_newlines(s): + p = sqlparse.parse(s)[0] + assert str(p) == s + + +def test_parse_within(): + s = 'foo(col1, col2)' + p = sqlparse.parse(s)[0] + col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] + assert col1.within(sql.Function) + + +def test_parse_child_of(): + s = '(col1, col2)' + p = sqlparse.parse(s)[0] + assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) + s = 'select foo' + p = sqlparse.parse(s)[0] + assert not p.tokens[2].is_child_of(p.tokens[0]) + assert p.tokens[2].is_child_of(p) + + +def test_parse_has_ancestor(): + s = 'foo or (bar, baz)' + p = sqlparse.parse(s)[0] + baz = p.tokens[-1].tokens[1].tokens[-1] + assert baz.has_ancestor(p.tokens[-1].tokens[1]) + assert baz.has_ancestor(p.tokens[-1]) + assert baz.has_ancestor(p) + + +@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5']) +def test_parse_float(s): + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype is sqlparse.tokens.Number.Float + + +@pytest.mark.parametrize('s, holder', [ + ('select * from foo where user = ?', '?'), + ('select * from foo where user = :1', ':1'), + ('select * from foo where user = :name', ':name'), + ('select * from foo where user = %s', '%s'), + ('select * from foo where user = $a', '$a')]) +def test_parse_placeholder(s, holder): + t = sqlparse.parse(s)[0].tokens[-1].tokens + assert t[-1].ttype is sqlparse.tokens.Name.Placeholder + assert t[-1].value == holder + + +def test_parse_modulo_not_placeholder(): + tokens = list(sqlparse.lexer.tokenize('x %3')) + assert tokens[2][0] == sqlparse.tokens.Operator + + +def test_parse_access_symbol(): + # see issue27 + t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens + assert isinstance(t[-1], sql.Identifier) + assert t[-1].get_name() == 'foo' + assert t[-1].get_real_name() == '[foo bar]' + assert t[-1].get_parent_name() == 'a' + + +def test_parse_square_brackets_notation_isnt_too_greedy(): + # see issue153 + t = sqlparse.parse('[foo], [bar]')[0].tokens + assert isinstance(t[0], sql.IdentifierList) + assert len(t[0].tokens) == 4 + assert t[0].tokens[0].get_real_name() == '[foo]' + assert t[0].tokens[-1].get_real_name() == '[bar]' + + +def test_parse_square_brackets_notation_isnt_too_greedy2(): + # see issue583 + t = sqlparse.parse('[(foo[i])]')[0].tokens + assert isinstance(t[0], sql.SquareBrackets) # not Identifier! + + +def test_parse_keyword_like_identifier(): + # see issue47 + t = sqlparse.parse('foo.key')[0].tokens + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_parameter(): + # see issue94 + t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert isinstance(t[0], sql.Identifier) + + +def test_parse_function_param_single_literal(): + t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert t[0].ttype is T.Number.Integer + + +def test_parse_nested_function(): + t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() + assert len(t) == 1 + assert type(t[0]) is sql.Function + + +def test_parse_casted_params(): + t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() + assert len(t) == 2 + + +def test_parse_div_operator(): + p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens + assert p[0].tokens[0].tokens[2].ttype is T.Operator + assert p[0].get_alias() == 'div_col1' + + +def test_quoted_identifier(): + t = sqlparse.parse('select x.y as "z" from foo')[0].tokens + assert isinstance(t[2], sql.Identifier) + assert t[2].get_name() == 'z' + assert t[2].get_real_name() == 'y' + + +@pytest.mark.parametrize('name', [ + 'foo', '_foo', # issue175 + '1_data', # valid MySQL table name, see issue337 + '業者名稱', # valid at least for SQLite3, see issue641 +]) +def test_valid_identifier_names(name): + t = sqlparse.parse(name)[0].tokens + assert isinstance(t[0], sql.Identifier) + assert t[0].get_name() == name + + +def test_psql_quotation_marks(): + # issue83 + + # regression: make sure plain $$ work + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ + .... + $$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # make sure $SOMETHING$ works too + t = sqlparse.split(""" + CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ + .... + $PROC_1$ LANGUAGE plpgsql; + CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ + .... + $PROC_2$ LANGUAGE plpgsql;""") + assert len(t) == 2 + + # operators are valid infront of dollar quoted strings + t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") + assert len(t) == 1 + + # identifiers must be separated by whitespace + t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") + assert len(t) == 2 + + +def test_double_precision_is_builtin(): + s = 'DOUBLE PRECISION' + t = sqlparse.parse(s)[0].tokens + assert len(t) == 1 + assert t[0].ttype == sqlparse.tokens.Name.Builtin + assert t[0].value == 'DOUBLE PRECISION' + + +@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s']) +def test_placeholder(ph): + p = sqlparse.parse(ph)[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.Name.Placeholder + + +@pytest.mark.parametrize('num, expected', [ + ('6.67428E-8', T.Number.Float), + ('1.988e33', T.Number.Float), + ('1e-12', T.Number.Float), + ('e1', None), +]) +def test_scientific_numbers(num, expected): + p = sqlparse.parse(num)[0].tokens + assert len(p) == 1 + assert p[0].ttype is expected + + +def test_single_quotes_are_strings(): + p = sqlparse.parse("'foo'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_double_quotes_are_identifiers(): + p = sqlparse.parse('"foo"')[0].tokens + assert len(p) == 1 + assert isinstance(p[0], sql.Identifier) + + +def test_single_quotes_with_linebreaks(): + # issue118 + p = sqlparse.parse("'f\nf'")[0].tokens + assert len(p) == 1 + assert p[0].ttype is T.String.Single + + +def test_sqlite_identifiers(): + # Make sure we still parse sqlite style escapes + p = sqlparse.parse('[col1],[col2]')[0].tokens + id_names = [id_.get_name() for id_ in p[0].get_identifiers()] + assert len(p) == 1 + assert isinstance(p[0], sql.IdentifierList) + assert id_names == ['[col1]', '[col2]'] + + p = sqlparse.parse('[col1]+[col2]')[0] + types = [tok.ttype for tok in p.flatten()] + assert types == [T.Name, T.Operator, T.Name] + + +def test_simple_1d_array_index(): + p = sqlparse.parse('col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + indices = list(p[0].get_array_indices()) + assert len(indices) == 1 # 1-dimensional index + assert len(indices[0]) == 1 # index is single token + assert indices[0][0].value == '1' + + +def test_2d_array_index(): + p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens + assert len(p) == 1 + assert p[0].get_name() == 'col' + assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index + + +def test_array_index_function_result(): + p = sqlparse.parse('somefunc()[1]')[0].tokens + assert len(p) == 1 + assert len(list(p[0].get_array_indices())) == 1 + + +def test_schema_qualified_array_index(): + p = sqlparse.parse('schem.col[1]')[0].tokens + assert len(p) == 1 + assert p[0].get_parent_name() == 'schem' + assert p[0].get_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_aliased_array_index(): + p = sqlparse.parse('col[1] x')[0].tokens + assert len(p) == 1 + assert p[0].get_alias() == 'x' + assert p[0].get_real_name() == 'col' + assert list(p[0].get_array_indices())[0][0].value == '1' + + +def test_array_literal(): + # See issue #176 + p = sqlparse.parse('ARRAY[%s, %s]')[0] + assert len(p.tokens) == 2 + assert len(list(p.flatten())) == 7 + + +def test_typed_array_definition(): + # array indices aren't grouped with built-ins, but make sure we can extract + # identifier names + p = sqlparse.parse('x int, y int[], z int')[0] + names = [x.get_name() for x in p.get_sublists() + if isinstance(x, sql.Identifier)] + assert names == ['x', 'y', 'z'] + + +@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo']) +def test_single_line_comments(s): + # see issue178 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 5 + assert p.tokens[-1].ttype == T.Comment.Single + + +@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo']) +def test_names_and_special_names(s): + # see issue192 + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Identifier) + + +def test_get_token_at_offset(): + p = sqlparse.parse('select * from dual')[0] + # 0123456789 + assert p.get_token_at_offset(0) == p.tokens[0] + assert p.get_token_at_offset(1) == p.tokens[0] + assert p.get_token_at_offset(6) == p.tokens[1] + assert p.get_token_at_offset(7) == p.tokens[2] + assert p.get_token_at_offset(8) == p.tokens[3] + assert p.get_token_at_offset(9) == p.tokens[4] + assert p.get_token_at_offset(10) == p.tokens[4] + + +def test_pprint(): + p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' + '(select * from dual) q0 where 1=1 and 2=2')[0] + output = StringIO() + + p._pprint_tree(f=output) + pprint = '\n'.join([ + "|- 0 DML 'select'", + "|- 1 Whitespace ' '", + "|- 2 IdentifierList 'a0, b0...'", + "| |- 0 Identifier 'a0'", + "| | `- 0 Name 'a0'", + "| |- 1 Punctuation ','", + "| |- 2 Whitespace ' '", + "| |- 3 Identifier 'b0'", + "| | `- 0 Name 'b0'", + "| |- 4 Punctuation ','", + "| |- 5 Whitespace ' '", + "| |- 6 Identifier 'c0'", + "| | `- 0 Name 'c0'", + "| |- 7 Punctuation ','", + "| |- 8 Whitespace ' '", + "| |- 9 Identifier 'd0'", + "| | `- 0 Name 'd0'", + "| |- 10 Punctuation ','", + "| |- 11 Whitespace ' '", + "| `- 12 Identifier 'e0'", + "| `- 0 Name 'e0'", + "|- 3 Whitespace ' '", + "|- 4 Keyword 'from'", + "|- 5 Whitespace ' '", + "|- 6 Identifier '(selec...'", + "| |- 0 Parenthesis '(selec...'", + "| | |- 0 Punctuation '('", + "| | |- 1 DML 'select'", + "| | |- 2 Whitespace ' '", + "| | |- 3 Wildcard '*'", + "| | |- 4 Whitespace ' '", + "| | |- 5 Keyword 'from'", + "| | |- 6 Whitespace ' '", + "| | |- 7 Identifier 'dual'", + "| | | `- 0 Name 'dual'", + "| | `- 8 Punctuation ')'", + "| |- 1 Whitespace ' '", + "| `- 2 Identifier 'q0'", + "| `- 0 Name 'q0'", + "|- 7 Whitespace ' '", + "`- 8 Where 'where ...'", + " |- 0 Keyword 'where'", + " |- 1 Whitespace ' '", + " |- 2 Comparison '1=1'", + " | |- 0 Integer '1'", + " | |- 1 Comparison '='", + " | `- 2 Integer '1'", + " |- 3 Whitespace ' '", + " |- 4 Keyword 'and'", + " |- 5 Whitespace ' '", + " `- 6 Comparison '2=2'", + " |- 0 Integer '2'", + " |- 1 Comparison '='", + " `- 2 Integer '2'", + ""]) + assert output.getvalue() == pprint + + +def test_wildcard_multiplication(): + p = sqlparse.parse('select * from dual')[0] + assert p.tokens[2].ttype == T.Wildcard + + p = sqlparse.parse('select a0.* from dual a0')[0] + assert p.tokens[2][2].ttype == T.Wildcard + + p = sqlparse.parse('select 1 * 2 from dual')[0] + assert p.tokens[2][2].ttype == T.Operator + + +def test_stmt_tokens_parents(): + # see issue 226 + s = "CREATE TABLE test();" + stmt = sqlparse.parse(s)[0] + for token in stmt.tokens: + assert token.has_ancestor(stmt) + + +@pytest.mark.parametrize('sql, is_literal', [ + ('$$foo$$', True), + ('$_$foo$_$', True), + ('$token$ foo $token$', True), + # don't parse inner tokens + ('$_$ foo $token$bar$token$ baz$_$', True), + ('$A$ foo $B$', False) # tokens don't match +]) +def test_dbldollar_as_literal(sql, is_literal): + # see issue 277 + p = sqlparse.parse(sql)[0] + if is_literal: + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Literal + else: + for token in p.tokens: + assert token.ttype != T.Literal + + +def test_non_ascii(): + _test_non_ascii = "insert into test (id, name) values (1, 'тест');" + + s = _test_non_ascii + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == s + assert statement._pprint_tree() is None + + s = _test_non_ascii.encode('utf-8') + stmts = sqlparse.parse(s, 'utf-8') + assert len(stmts) == 1 + statement = stmts[0] + assert str(statement) == _test_non_ascii + assert statement._pprint_tree() is None + + +def test_get_real_name(): + # issue 369 + s = "update a t set t.b=1" + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert 'a' == stmts[0].tokens[2].get_real_name() + assert 't' == stmts[0].tokens[2].get_alias() + + +def test_from_subquery(): + # issue 446 + s = 'from(select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 2 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + + s = 'from (select 1)' + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + assert len(stmts[0].tokens) == 3 + assert stmts[0].tokens[0].value == 'from' + assert stmts[0].tokens[0].ttype == T.Keyword + assert stmts[0].tokens[1].ttype == T.Whitespace + + +def test_parenthesis(): + tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Number.Integer, + T.Newline, + T.Newline, + T.Punctuation] + tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens + assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, + T.Newline, + T.Newline, + T.Whitespace, + T.Number.Integer, + T.Whitespace, + T.Newline, + T.Newline, + T.Punctuation] + + +def test_configurable_keywords(): + sql = """select * from foo BACON SPAM EGGS;""" + tokens = sqlparse.parse(sql)[0] + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo BACON"), + (None, "SPAM EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + Lexer.get_default_instance().add_keywords( + { + "BACON": sqlparse.tokens.Name.Builtin, + "SPAM": sqlparse.tokens.Keyword, + "EGGS": sqlparse.tokens.Keyword, + } + ) + + tokens = sqlparse.parse(sql)[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + ) == [ + (sqlparse.tokens.Keyword.DML, "select"), + (sqlparse.tokens.Wildcard, "*"), + (sqlparse.tokens.Keyword, "from"), + (None, "foo"), + (sqlparse.tokens.Name.Builtin, "BACON"), + (sqlparse.tokens.Keyword, "SPAM"), + (sqlparse.tokens.Keyword, "EGGS"), + (sqlparse.tokens.Punctuation, ";"), + ] + + +def test_configurable_regex(): + lex = Lexer.get_default_instance() + lex.clear() + + my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword) + + lex.set_SQL_REGEX( + keywords.SQL_REGEX[:38] + + [my_regex] + + keywords.SQL_REGEX[38:] + ) + lex.add_keywords(keywords.KEYWORDS_COMMON) + lex.add_keywords(keywords.KEYWORDS_ORACLE) + lex.add_keywords(keywords.KEYWORDS_PLPGSQL) + lex.add_keywords(keywords.KEYWORDS_HQL) + lex.add_keywords(keywords.KEYWORDS_MSACCESS) + lex.add_keywords(keywords.KEYWORDS) + + tokens = sqlparse.parse("select * from foo zorder by bar;")[0] + + # reset the syntax for later tests. + Lexer.get_default_instance().default_initialization() + + assert list( + (t.ttype, t.value) + for t in tokens + if t.ttype not in sqlparse.tokens.Whitespace + )[4] == (sqlparse.tokens.Keyword, "zorder by") + + +@pytest.mark.parametrize('sql', [ + '->', '->>', '#>', '#>>', + '@>', '<@', + # leaving ? out for now, they're somehow ambiguous as placeholders + # '?', '?|', '?&', + '||', '-', '#-' +]) +def test_json_operators(sql): + p = sqlparse.parse(sql) + assert len(p) == 1 + assert len(p[0].tokens) == 1 + assert p[0].tokens[0].ttype == sqlparse.tokens.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from sqlparse.exceptions import SQLParseError + + +def test_issue9(): + # make sure where doesn't consume parenthesis + p = sqlparse.parse('(where 1)')[0] + assert isinstance(p, sql.Statement) + assert len(p.tokens) == 1 + assert isinstance(p.tokens[0], sql.Parenthesis) + prt = p.tokens[0] + assert len(prt.tokens) == 3 + assert prt.tokens[0].ttype == T.Punctuation + assert prt.tokens[-1].ttype == T.Punctuation + + +def test_issue13(): + parsed = sqlparse.parse("select 'one';\n" + "select 'two\\'';\n" + "select 'three';") + assert len(parsed) == 3 + assert str(parsed[1]).strip() == "select 'two\\'';" + + +@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', + '--', '--\n']) +def test_issue26(s): + # parse stand-alone comments + p = sqlparse.parse(s)[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype is T.Comment.Single + + +@pytest.mark.parametrize('value', ['create', 'CREATE']) +def test_issue34(value): + t = sqlparse.parse("create")[0].token_first() + assert t.match(T.Keyword.DDL, value) is True + + +def test_issue35(): + # missing space before LIMIT. Updated for #321 + sql = sqlparse.format("select * from foo where bar = 1 limit 1", + reindent=True) + assert sql == "\n".join([ + "select *", + "from foo", + "where bar = 1", + "limit 1"]) + + +def test_issue38(): + sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) + assert sql == "SELECT foo;" + sql = sqlparse.format("/* foo */", strip_comments=True) + assert sql == "" + + +def test_issue39(): + p = sqlparse.parse('select user.id from user')[0] + assert len(p.tokens) == 7 + idt = p.tokens[2] + assert idt.__class__ == sql.Identifier + assert len(idt.tokens) == 3 + assert idt.tokens[0].match(T.Name, 'user') is True + assert idt.tokens[1].match(T.Punctuation, '.') is True + assert idt.tokens[2].match(T.Name, 'id') is True + + +def test_issue40(): + # make sure identifier lists in subselects are grouped + p = sqlparse.parse('SELECT id, name FROM ' + '(SELECT id, name FROM bar) as foo')[0] + assert len(p.tokens) == 7 + assert p.tokens[2].__class__ == sql.IdentifierList + assert p.tokens[-1].__class__ == sql.Identifier + assert p.tokens[-1].get_name() == 'foo' + sp = p.tokens[-1].tokens[0] + assert sp.tokens[3].__class__ == sql.IdentifierList + # make sure that formatting works as expected + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar)', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar)']) + + s = sqlparse.format('SELECT id == name FROM ' + '(SELECT id, name FROM bar) as foo', reindent=True) + assert s == '\n'.join([ + 'SELECT id == name', + 'FROM', + ' (SELECT id,', + ' name', + ' FROM bar) as foo']) + + +@pytest.mark.parametrize('s', ['select x.y::text as z from foo', + 'select x.y::text as "z" from foo', + 'select x."y"::text as z from foo', + 'select x."y"::text as "z" from foo', + 'select "x".y::text as z from foo', + 'select "x".y::text as "z" from foo', + 'select "x"."y"::text as z from foo', + 'select "x"."y"::text as "z" from foo']) +@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), + ('get_real_name', 'y'), + ('get_parent_name', 'x'), + ('get_alias', 'z'), + ('get_typecast', 'text')]) +def test_issue78(s, func_name, result): + # the bug author provided this nice examples, let's use them! + p = sqlparse.parse(s)[0] + i = p.tokens[2] + assert isinstance(i, sql.Identifier) + + func = getattr(i, func_name) + assert func() == result + + +def test_issue83(): + sql = """ CREATE OR REPLACE FUNCTION func_a(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + CREATE OR REPLACE FUNCTION func_b(text) + RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS + $_$ + BEGIN + ... + END; + $_$; + + ALTER TABLE..... ;""" + t = sqlparse.split(sql) + assert len(t) == 3 + + +def test_comment_encoding_when_reindent(): + # There was an UnicodeEncodeError in the reindent filter that + # casted every comment followed by a keyword to str. + sql = 'select foo -- Comment containing Ümläuts\nfrom bar' + formatted = sqlparse.format(sql, reindent=True) + assert formatted == sql + + +def test_parse_sql_with_binary(): + # See https://github.com/andialbrecht/sqlparse/pull/88 + # digest = '‚|ËêŠplL4¡h‘øN{' + digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_dont_alias_keywords(): + # The _group_left_right function had a bug where the check for the + # left side wasn't handled correctly. In one case this resulted in + # a keyword turning into an identifier. + p = sqlparse.parse('FROM AS foo')[0] + assert len(p.tokens) == 5 + assert p.tokens[0].ttype is T.Keyword + assert p.tokens[2].ttype is T.Keyword + + +def test_format_accepts_encoding(load_file): + # issue20 + sql = load_file('test_cp1251.sql', 'cp1251') + formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') + tformatted = 'insert into foo\nvalues (1); -- Песня про надежду' + + assert formatted == tformatted + + +def test_stream(get_stream): + with get_stream("stream.sql") as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue90(): + sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' + ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' + ' "rating_score" = 0, "thumbnail_width" = NULL,' + ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'UPDATE "gallery_photo"', + 'SET "owner_id" = 4018,', + ' "deleted_at" = NULL,', + ' "width" = NULL,', + ' "height" = NULL,', + ' "rating_votes" = 0,', + ' "rating_score" = 0,', + ' "thumbnail_width" = NULL,', + ' "thumbnail_height" = NULL,', + ' "price" = 1,', + ' "description" = NULL']) + assert formatted == tformatted + + +def test_except_formatting(): + sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT 1', + 'FROM foo', + 'WHERE 2 = 3', + 'EXCEPT', + 'SELECT 2', + 'FROM bar', + 'WHERE 1 = 2']) + assert formatted == tformatted + + +def test_null_with_as(): + sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' + formatted = sqlparse.format(sql, reindent=True) + tformatted = '\n'.join([ + 'SELECT NULL AS c1,', + ' NULL AS c2', + 'FROM t1']) + assert formatted == tformatted + + +def test_issue190_open_file(filepath): + path = filepath('stream.sql') + with open(path) as stream: + p = sqlparse.parse(stream)[0] + assert p.get_type() == 'INSERT' + + +def test_issue193_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue194_splitting_function(): + sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) + BEGIN + DECLARE y VARCHAR(20); + IF (1 = 1) THEN + SET x = y; + END IF; + RETURN x; + END; + SELECT * FROM a.b;""" + statements = sqlparse.split(sql) + assert len(statements) == 2 + + +def test_issue186_get_type(): + sql = "-- comment\ninsert into foo" + p = sqlparse.parse(sql)[0] + assert p.get_type() == 'INSERT' + + +def test_issue212_py2unicode(): + t1 = sql.Token(T.String, 'schöner ') + t2 = sql.Token(T.String, 'bug') + token_list = sql.TokenList([t1, t2]) + assert str(token_list) == 'schöner bug' + + +def test_issue213_leadingws(): + sql = " select * from foo" + assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo" + + +def test_issue227_gettype_cte(): + select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') + assert select_stmt[0].get_type() == 'SELECT' + with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' + 'SELECT * FROM foo;') + assert with_stmt[0].get_type() == 'SELECT' + with2_stmt = sqlparse.parse(""" + WITH foo AS (SELECT 1 AS abc, 2 AS def), + bar AS (SELECT * FROM something WHERE x > 1) + INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") + assert with2_stmt[0].get_type() == 'INSERT' + + +def test_issue207_runaway_format(): + sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' + p = sqlparse.format(sql, reindent=True) + assert p == '\n'.join([ + "select 1", + "from", + " (select 1 as one,", + " 2 as two,", + " 3", + " from dual) t0"]) + + +def test_token_next_doesnt_ignore_skip_cm(): + sql = '--comment\nselect 1' + tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] + assert tok.value == 'select' + + +@pytest.mark.parametrize('s', [ + 'SELECT x AS', + 'AS' +]) +def test_issue284_as_grouping(s): + p = sqlparse.parse(s)[0] + assert s == str(p) + + +def test_issue315_utf8_by_default(): + # Make sure the lexer can handle utf-8 string by default correctly + # digest = '齐天大圣.カラフルな雲.사랑해요' + # The digest contains Chinese, Japanese and Korean characters + # All in 'utf-8' encoding. + digest = ( + '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' + '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' + '\x9b\xb2.' + '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' + ) + sql = "select * from foo where bar = '{}'".format(digest) + formatted = sqlparse.format(sql, reindent=True) + tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) + assert formatted == tformatted + + +def test_issue322_concurrently_is_keyword(): + s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' + p = sqlparse.parse(s)[0] + + assert len(p.tokens) == 12 + assert p.tokens[0].ttype is T.Keyword.DDL # CREATE + assert p.tokens[2].ttype is T.Keyword # INDEX + assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY + assert p.tokens[4].value == 'CONCURRENTLY' + assert isinstance(p.tokens[6], sql.Identifier) + assert p.tokens[6].value == 'myindex' + + +@pytest.mark.parametrize('s', [ + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', + 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop', + +]) +def test_issue359_index_error_assignments(s): + sqlparse.parse(s) + sqlparse.format(s, strip_comments=True) + + +def test_issue469_copy_as_psql_command(): + formatted = sqlparse.format( + '\\copy select * from foo', + keyword_case='upper', identifier_case='capitalize') + assert formatted == '\\copy SELECT * FROM Foo' + + +@pytest.mark.xfail(reason='Needs to be fixed') +def test_issue484_comments_and_newlines(): + formatted = sqlparse.format('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL, --my special comment', + ' myName VARCHAR2(100) NOT NULL', + ')']), + strip_comments=True) + assert formatted == ('\n'.join([ + 'Create table myTable', + '(', + ' myId TINYINT NOT NULL,', + ' myName VARCHAR2(100) NOT NULL', + ')'])) + + +def test_issue485_split_multi(): + p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERT +TO public.ruled_tab +DO instead ( +select 1; +select 2; +);''' + assert len(sqlparse.split(p_sql)) == 1 + + +def test_issue489_tzcasts(): + p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] + assert p.tokens[-1].has_alias() is True + assert p.tokens[-1].get_alias() == 'foo' + + +def test_issue562_tzcasts(): + # Test that whitespace between 'from' and 'bar' is retained + formatted = sqlparse.format( + 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True + ) + assert formatted == \ + 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo' + + +def test_as_in_parentheses_indents(): + # did raise NoneType has no attribute is_group in _process_parentheses + formatted = sqlparse.format('(as foo)', reindent=True) + assert formatted == '(as foo)' + + +def test_format_invalid_where_clause(): + # did raise ValueError + formatted = sqlparse.format('where, foo', reindent=True) + assert formatted == 'where, foo' + + +def test_splitting_at_and_backticks_issue588(): + splitted = sqlparse.split( + 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') + assert len(splitted) == 2 + assert splitted[-1] == 'grant bar to user1@`myhost`;' + + +def test_comment_between_cte_clauses_issue632(): + p, = sqlparse.parse(""" + WITH foo AS (), + -- A comment before baz subquery + baz AS () + SELECT * FROM baz;""") + assert p.get_type() == "SELECT" + + +def test_copy_issue672(): + p = sqlparse.parse('select * from foo')[0] + copied = copy.deepcopy(p) + assert str(p) == str(copied) + + +def test_primary_key_issue740(): + p = sqlparse.parse('PRIMARY KEY')[0] + assert len(p.tokens) == 1 + assert p.tokens[0].ttype == T.Keyword + + +@pytest.fixture +def limit_recursion(): + curr_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + yield + sys.setrecursionlimit(curr_limit) + + +def test_max_recursion(limit_recursion): + with pytest.raises(SQLParseError): + sqlparse.parse('[' * 1000 + ']' * 1000) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from io import StringIO + +import pytest + +import sqlparse + + +def test_split_semicolon(): + sql1 = 'select * from foo;' + sql2 = "select * from foo where bar = 'foo;bar';" + stmts = sqlparse.parse(''.join([sql1, sql2])) + assert len(stmts) == 2 + assert str(stmts[0]) == sql1 + assert str(stmts[1]) == sql2 + + +def test_split_backslash(): + stmts = sqlparse.parse("select '\'; select '\'';") + assert len(stmts) == 2 + + +@pytest.mark.parametrize('fn', ['function.sql', + 'function_psql.sql', + 'function_psql2.sql', + 'function_psql3.sql', + 'function_psql4.sql']) +def test_split_create_function(load_file, fn): + sql = load_file(fn) + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert str(stmts[0]) == sql + + +def test_split_dashcomments(load_file): + sql = load_file('dashcomment.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +@pytest.mark.parametrize('s', ['select foo; -- comment\n', + 'select foo; -- comment\r', + 'select foo; -- comment\r\n', + 'select foo; -- comment']) +def test_split_dashcomments_eol(s): + stmts = sqlparse.parse(s) + assert len(stmts) == 1 + + +def test_split_begintag(load_file): + sql = load_file('begintag.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 3 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_begintag_2(load_file): + sql = load_file('begintag_2.sql') + stmts = sqlparse.parse(sql) + assert len(stmts) == 1 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_dropif(): + sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_with_umlaut(): + sql = ('select * from foo;\n' + '-- Testing an umlaut: ä\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + + +def test_split_comment_end_of_line(): + sql = ('select * from foo; -- foo\n' + 'select * from bar;') + stmts = sqlparse.parse(sql) + assert len(stmts) == 2 + assert ''.join(str(q) for q in stmts) == sql + # make sure the comment belongs to first query + assert str(stmts[0]) == 'select * from foo; -- foo\n' + + +def test_split_casewhen(): + sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" + "comment on table actor is 'The actor table.';") + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_casewhen_procedure(load_file): + # see issue580 + stmts = sqlparse.split(load_file('casewhen_procedure.sql')) + assert len(stmts) == 2 + + +def test_split_cursor_declare(): + sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' + 'SELECT 2;') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_if_function(): # see issue 33 + # don't let IF as a function confuse the splitter + sql = ('CREATE TEMPORARY TABLE tmp ' + 'SELECT IF(a=1, a, b) AS o FROM one; ' + 'SELECT t FROM two') + stmts = sqlparse.split(sql) + assert len(stmts) == 2 + + +def test_split_stream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = sqlparse.parsestream(stream) + assert isinstance(stmts, types.GeneratorType) + assert len(list(stmts)) == 2 + + +def test_split_encoding_parsestream(): + stream = StringIO("SELECT 1; SELECT 2;") + stmts = list(sqlparse.parsestream(stream)) + assert isinstance(stmts[0].tokens[0].value, str) + + +def test_split_unicode_parsestream(): + stream = StringIO('SELECT ö') + stmts = list(sqlparse.parsestream(stream)) + assert str(stmts[0]) == 'SELECT ö' + + +def test_split_simple(): + stmts = sqlparse.split('select * from foo; select * from bar;') + assert len(stmts) == 2 + assert stmts[0] == 'select * from foo;' + assert stmts[1] == 'select * from bar;' + + +def test_split_ignores_empty_newlines(): + stmts = sqlparse.split('select foo;\nselect bar;\n') + assert len(stmts) == 2 + assert stmts[0] == 'select foo;' + assert stmts[1] == 'select bar;' + + +def test_split_quotes_with_new_line(): + stmts = sqlparse.split('select "foo\nbar"') + assert len(stmts) == 1 + assert stmts[0] == 'select "foo\nbar"' + + stmts = sqlparse.split("select 'foo\n\bar'") + assert len(stmts) == 1 + assert stmts[0] == "select 'foo\n\bar'" + + +def test_split_mysql_handler_for(load_file): + # see issue581 + stmts = sqlparse.split(load_file('mysql_handler.sql')) + assert len(stmts) == 2 + + +@pytest.mark.parametrize('sql, expected', [ + ('select * from foo;', ['select * from foo']), + ('select * from foo', ['select * from foo']), + ('select * from foo; select * from bar;', [ + 'select * from foo', + 'select * from bar', + ]), + (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ + 'select * from foo', + 'select * from bar', + ]), + ('select * from foo\n\n; bar', ['select * from foo', 'bar']), +]) +def test_split_strip_semicolon(sql, expected): + stmts = sqlparse.split(sql, strip_semicolon=True) + assert len(stmts) == len(expected) + for idx, expectation in enumerate(expected): + assert stmts[idx] == expectation + + +def test_split_strip_semicolon_procedure(load_file): + stmts = sqlparse.split(load_file('mysql_handler.sql'), + strip_semicolon=True) + assert len(stmts) == 2 + assert stmts[0].endswith('end') + assert stmts[1].endswith('end') + +@pytest.mark.parametrize('sql, num', [ + ('USE foo;\nGO\nSELECT 1;\nGO', 4), + ('SELECT * FROM foo;\nGO', 2), + ('USE foo;\nGO 2\nSELECT 1;', 3) +]) +def test_split_go(sql, num): # issue762 + stmts = sqlparse.split(sql) + assert len(stmts) == num + + +def test_split_multiple_case_in_begin(load_file): # issue784 + stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) + assert len(stmts) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__31bk4r7o/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from sqlparse import sql, tokens as T + + +def test_tokenize_simple(): + s = 'select * from foo;' + stream = lexer.tokenize(s) + assert isinstance(stream, types.GeneratorType) + tokens = list(stream) + assert len(tokens) == 8 + assert len(tokens[0]) == 2 + assert tokens[0] == (T.Keyword.DML, 'select') + assert tokens[-1] == (T.Punctuation, ';') + + +def test_tokenize_backticks(): + s = '`foo`.`bar`' + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0] == (T.Name, '`foo`') + + +@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', + 'foo\r\nbar\r\n', 'foo\r\nbar\n']) +def test_tokenize_linebreaks(s): + # issue1 + tokens = lexer.tokenize(s) + assert ''.join(str(x[1]) for x in tokens) == s + + +def test_tokenize_inline_keywords(): + # issue 7 + s = "create created_foo" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[0][0] == T.Keyword.DDL + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'created_foo' + s = "enddate" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 1 + assert tokens[0][0] == T.Name + s = "left join_col" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 3 + assert tokens[2][0] == T.Name + assert tokens[2][1] == 'join_col' + + +def test_tokenize_negative_numbers(): + s = "values(-1)" + tokens = list(lexer.tokenize(s)) + assert len(tokens) == 4 + assert tokens[2][0] == T.Number.Integer + assert tokens[2][1] == '-1' + + +def test_token_str(): + token = sql.Token(None, 'FoO') + assert str(token) == 'FoO' + + +def test_token_repr(): + token = sql.Token(T.Keyword, 'foo') + tst = " 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = nil } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb66632f8e08cda1ebac1f6956b1fdbfab11f543 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/instruction.md @@ -0,0 +1,38 @@ +Base64StdEncoding() causes nil pointer dereference in JSON marshaling + +#### Description + +After calling `Base64StdEncoding()`, attempting to marshal a BitSet to JSON results in a panic due to a nil pointer dereference. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "encoding/json" + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create a BitSet and set some bits + b := bitset.New(100) + b.Set(1).Set(10).Set(50) + + // Switch to standard base64 encoding + bitset.Base64StdEncoding() + + // This will panic with nil pointer dereference + data, err := json.Marshal(b) + if err != nil { + fmt.Printf("Error: %v\n", err) + return + } + + fmt.Printf("JSON: %s\n", data) +} +``` + +The panic occurs when trying to marshal the BitSet after calling `Base64StdEncoding()`. The expected behavior would be to successfully marshal the BitSet using standard base64 encoding instead of URL encoding. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..18035c2e764db4222bd1a2b7dca698797b2b03b5 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "798b6b3fccf5b2584c570ae35aecfa04eac6518c2fd82fad517d266fabeb5404", + "size": 47821 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "27371904a17ddb15136231247533cfce1ef0651905df0fc58225445728333de7", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "64dbdd9bd829a0c4fd86916c2ef194ffd30809e645f6bc359c934140a4972092", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "e5403b76ba061e03351311a7c997a10bc59404e45cd6ae1930f34bd575905e22", + "is_fork": true, + "learner_path": "tasks/e15d3bd9373f44c52e122f6f/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/5f7fea53b03945e7ef03b0978a564cf90c139085/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "86b9254ab02cdb4470e72ea29d764005173a702a7d9c184ac542b1476b9bbf69", + "provenance_path": "tasks/e15d3bd9373f44c52e122f6f/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "5f7fea53b03945e7ef03b0978a564cf90c139085", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "deb46a06a11ab53c16297b33a31e807b6054c5b5", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3", + "task_sha256": "a5a35fbde95e908f8c69102bee0b0f3f94d4f4c9a395e414fcc062205ffb8d45", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "d0e644e870bbf0772174102504a9d7769fd8fc6f5725c9de2e903bb64ced5ca7", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5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gkvLyBQcm9jZXNzIGJ5dGUgYnkgYnl0ZQoJZm9yIGkgOj0gMDsgaSA8IDg7IGkrKyB7CgkJc2hpZnQgOj0gaSA8PCAzIC8vIGkgKiA4IHVzaW5nIGJpdCBzaGlmdAoJCW1hc2sgOj0gdWludDgobSA+PiBzaGlmdCkKCQliaXRzIDo9IHBvcExVVFttYXNrXQoKCQkvLyBHZXQgdGhlIGJpdHMgd2UnbGwgZGVwb3NpdCBmcm9tIHRoZSBzb3VyY2UKCQliIDo9IHVpbnQ4KHcgPj4gaW5Qb3MpCgoJCS8vIERlcG9zaXQgdGhlbSBhY2NvcmRpbmcgdG8gdGhlIG1hc2sgZm9yIHRoaXMgYnl0ZQoJCWRlcG9zaXRlZCA6PSBwZGVwTFVUW2JdW21hc2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0380859fa162c44b9ed879ef019f3266c4659d5c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/task.toml @@ -0,0 +1,10 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..bff8bfb490682abcf6e8f39704e76ac36d340fb7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/manifest.json @@ -0,0 +1,439 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..5bfcbb87b26a080cac37f002750788a5a0546c34 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__wqocwkk3/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "1d42d239fdc7d348571a5aaef4e1ab44f87880875e60875ac11d7fa8612c2001", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..53a38363360b292f07673c7619e59cd5e932cb1d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/bitset.go @@ -0,0 +1,1756 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf)-1)*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..57f36fc60481f0a26cc64298376896c9fb21be34 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/instruction.md @@ -0,0 +1,48 @@ +BitSet.From() constructor creates incorrect length when using word arrays + +#### Description + +The `From()` constructor function incorrectly calculates the bit length when creating a BitSet from a word array, resulting in a BitSet that's 64 bits shorter than expected. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create a word array with 4 words (should represent 256 bits) + words := []uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF} + + // Create BitSet using From constructor + bs := bitset.From(words) + + fmt.Printf("Expected length: %d\n", len(words)*64) // Should be 256 + fmt.Printf("Actual length: %d\n", bs.Len()) // Shows 192 instead + + // This demonstrates the issue - we're missing 64 bits + if bs.Len() != uint(len(words)*64) { + fmt.Printf("ERROR: BitSet length is %d bits short!\n", len(words)*64 - int(bs.Len())) + } +} +``` + +Expected output: +``` +Expected length: 256 +Actual length: 256 +``` + +Actual output: +``` +Expected length: 256 +Actual length: 192 +ERROR: BitSet length is 64 bits short! +``` + +The issue affects any usage of the `From()` constructor where you need the full bit capacity of the provided word array. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..990fc5c74a3af4a609aa1002cfe4d9952b43fc08 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "39193020237c3cefc73971ce81163656ada46c99010c3b7dd92f051083263bbf", + "size": 47838 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "production/runtime-images-v1/resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "526a013abc24dd8f51ba2a2e1d54d2cad5fb8fdcfe4f05cb37d3af28272d75a9", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "fd47ed35b297480e166adfddf06b42b18468347f8c63bd24aae8ce0310ad98b3", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "b05419ec48c6e35653efdf7d28c27a0417db549a3d7da70a6d118bd13c859412", + "is_fork": true, + "learner_path": "tasks/f23c4748c6913ef1be27f325/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/2a5b4ec08cc4aa5cebc86fc75fc36ade2e0949c4/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "a49ee32cabab8a0f3b7bf69a459cfb18fbcdcfe7f14fa64dbd27b1a0507112cb", + "provenance_path": "tasks/f23c4748c6913ef1be27f325/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "2a5b4ec08cc4aa5cebc86fc75fc36ade2e0949c4", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "5e33ab6edd04b447db87697f74e10782542f228d", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy", + "task_sha256": "84f5a7d3bbee8d94b4c0ad92f3e013f617181d87791a388abb6fecc6b3b48e74", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "2a5658d6b079b5ce96daeba203e45f41623b0f26f7f76e5cd3eb6caf2e296235", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5kIGJvb2xlYW4gdmFsdWVzLiBJdCBzaG91bGQgYmUgbW9yZQplZmZpY2llbnQgdGhhbiBtYXBbdWludF0gYm9vbC4KCkl0IHByb3ZpZGVzIG1ldGhvZHMgZm9yIHNldHRpbmcsIGNsZWFyaW5nLCBmbGlwcGluZywgYW5kIHRlc3RpbmcKaW5kaXZpZHVhbCBpbnRlZ2Vycy4KCkJ1dCBpdCBhbHNvIHByb3ZpZGVzIHNldCBpbnRlcnNlY3Rpb24sIHVuaW9uLCBkaWZmZXJlbmNlLApjb21wbGVtZW50LCBhbmQgc3ltbWV0cmljIG9wZXJhdGlvbnMsIGFzIHdlbGwgYXMgdGVzdHMgdG8KY2hlY2sgd2hldGhlciBhbnksIGFsbCwgb3Igbm8gYml0cyBhcmUgc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c2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0864cdd1464da741d5d337a7b1bc813ef93f29b3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:53f3a6a98ae99ed2bdf00d740b7d4a44ed9fef2f615f0cf4d219130d2ff4ae59" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..24bf526a53049fba44c3e91f52025a1d24679d73 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/manifest.json @@ -0,0 +1,1049 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWords" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWordsNeededLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestTestTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestRankSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlip" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlipRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyUnaligned" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitStrings" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitSetInstance" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWriteTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/nil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_10" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_63" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_65" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_640" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/shift_to_full_page" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/remove_all" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/slightly_offset_results" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/first_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/third_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/way_off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/split_between_two_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/partly_off_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/skip_one_nibble" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/empty_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/invalid_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word_full" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/multiple_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPdep" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/single_bit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/two_sequential_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/extracting_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/large_gaps" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/depositing_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_unmasked_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_bits_outside_mask_within_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntMaskSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntAndSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntOrSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntXorSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "ExampleBitSet_Len" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..64227e157d3021bf6916e4b7e0f3faf2b193c8c3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xynnh0iy/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "e333e2aaca447a092a1c75313798430d5e2bc9d8743aca5410e46e9e193fe211", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..f73fa691004834fceacaa174de1beab77fe16d9c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/bitset.go @@ -0,0 +1,1756 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt -= popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3478fc7aed6a98c01f7c1f93896411054c422c8f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/instruction.md @@ -0,0 +1,40 @@ +SymmetricDifferenceCardinality returns incorrect count + +#### Description + +The `SymmetricDifferenceCardinality` method is returning an incorrect count when comparing bitsets of different lengths. The cardinality appears to be significantly lower than expected. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create two bitsets of different sizes + a := bitset.New(100) + b := bitset.New(200) + + // Set some bits in both sets + for i := uint(0); i < 50; i++ { + a.Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + + // Calculate symmetric difference cardinality + count := a.SymmetricDifferenceCardinality(b) + fmt.Printf("Symmetric difference cardinality: %d\n", count) + + // Expected: should be around 150 (50 bits from a + 100 bits from b) + // Actual: returns much lower value like 6 +} +``` + +The symmetric difference should include all bits that are in either set but not in both. When the bitsets have different lengths, the method appears to be subtracting rather than adding the extra bits from the longer set. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..06aa1c49fe0f168f6b509013b576c83e90ddc89a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "8f89fcc605c995cf39eb5a1b4377499017d54e478f7b51ac772290ea7fe9812f", + "size": 47836 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "production/runtime-images-v1/resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "53d187912db3f76cf09c0964662009b12752f16e0bccfb71d04df22581484dbb", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "f9aa48d2f74e72790e5c262e55a8d372578af5c267931c9ca114f034d63627fa", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "5f194797a49bab5cb4b54ceba51ad295f5dff283f7d49869433afebd7faab1d0", + "is_fork": true, + "learner_path": "tasks/0b2f00f5be2608e0a415d789/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/730830fded21846deee47e52bb9d8b11e5acdd9e/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "d325eff7d06d9a69eb767166a0ff349ca8401b821a23dd7a6044c676ea47adc3", + "provenance_path": "tasks/0b2f00f5be2608e0a415d789/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "730830fded21846deee47e52bb9d8b11e5acdd9e", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "e26630a028500db65eff9db7fa127e4ee6db959b", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn", + "task_sha256": "dc241b7541d4c4c9e31ba3a3e8f2fc20b1bc81a2b9b552b31574221b7840bf65", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "92a7dbc6e0f5f83bfc7bd0b1a68b274cdf7c730d8e3e9cf3fbcd3eefbd60bf39", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5kIGJvb2xlYW4gdmFsdWVzLiBJdCBzaG91bGQgYmUgbW9yZQplZmZpY2llbnQgdGhhbiBtYXBbdWludF0gYm9vbC4KCkl0IHByb3ZpZGVzIG1ldGhvZHMgZm9yIHNldHRpbmcsIGNsZWFyaW5nLCBmbGlwcGluZywgYW5kIHRlc3RpbmcKaW5kaXZpZHVhbCBpbnRlZ2Vycy4KCkJ1dCBpdCBhbHNvIHByb3ZpZGVzIHNldCBpbnRlcnNlY3Rpb24sIHVuaW9uLCBkaWZmZXJlbmNlLApjb21wbGVtZW50LCBhbmQgc3ltbWV0cmljIG9wZXJhdGlvbnMsIGFzIHdlbGwgYXMgdGVzdHMgdG8KY2hlY2sgd2hldGhlciBhbnksIGFsbCwgb3Igbm8gYml0cyBhcmUgc2V0LCBhbmQgcXVlcnlpbmcgYQpiaXRzZXQncyBjdXJyZW50IGxlbmd0aCBhbmQgbnVtYmVyIG9mIHBvc2l0aXZlIGJpdHMuCgpCaXRTZXRzIGFyZSBleHBhbmRlZCB0byB0aGUgc2l6ZSBvZiB0aGUgbGFyZ2VzdCBzZXQgYml0OyB0aGUKbWVtb3J5IGFsbG9jYXRpb24gaXMgYXBwcm94aW1hdGVseSBNYXggYml0cywgd2hlcmUgTWF4IGlzCnRoZSBsYXJnZXN0IHNldCBiaXQuIEJpdFNldHMgYXJlIG5ldmVyIHNocnVu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QKCQliIDo9IHVpbnQ4KHcgPj4gc2hpZnQpCgkJbWFzayA6PSB1aW50OChtID4+IHNoaWZ0KQoKCQlleHRyYWN0ZWQgOj0gcGV4dExVVFtiXVttYXNrXQoJCWJpdHMgOj0gcG9wTFVUW21hc2tdCgoJCXJlc3VsdCB8PSB1aW50NjQoZXh0cmFjdGVkKSA8PCBvdXRQb3MKCQlvdXRQb3MgKz0gdWludChiaXRzKQoJfQoKCXJldHVybiByZXN1bHQKfQoKZnVuYyBwZGVwKHcsIG0gdWludDY0KSAocmVzdWx0IHVpbnQ2NCkgewoJdmFyIGluUG9zIHVpbnQKCgkvLyBQcm9jZXNzIGJ5dGUgYnkgYnl0ZQoJZm9yIGkgOj0gMDsgaSA8IDg7IGkrKyB7CgkJc2hpZnQgOj0gaSA8PCAzIC8vIGkgKiA4IHVzaW5nIGJpdCBzaGlmdAoJCW1hc2sgOj0gdWludDgobSA+PiBzaGlmdCkKCQliaXRzIDo9IHBvcExVVFttYXNrXQoKCQkvLyBHZXQgdGhlIGJpdHMgd2UnbGwgZGVwb3NpdCBmcm9tIHRoZSBzb3VyY2UKCQliIDo9IHVpbnQ4KHcgPj4gaW5Qb3MpCgoJCS8vIERlcG9zaXQgdGhlbSBhY2NvcmRpbmcgdG8gdGhlIG1hc2sgZm9yIHRoaXMgYnl0ZQoJCWRlcG9zaXRlZCA6PSBwZGVwTFVUW2JdW21hc2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..76e9672484a086c3f054047455622fb8ee1563e8 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:75b9809d7296fdd5a71047002c2c862092b99ed43d69b8b785ff58636d5b7db4" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..e749ee2ab32ca17566310f17efae92e588215cf3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/manifest.json @@ -0,0 +1,1049 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWords" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWordsNeededLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestTestTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestRankSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlip" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlipRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyUnaligned" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitStrings" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitSetInstance" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWriteTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/nil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_10" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_63" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_65" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_640" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/shift_to_full_page" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/remove_all" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/slightly_offset_results" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/first_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/third_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/way_off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/split_between_two_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/partly_off_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/skip_one_nibble" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/empty_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/invalid_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word_full" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/multiple_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPdep" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/single_bit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/two_sequential_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/extracting_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/large_gaps" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/depositing_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_unmasked_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_bits_outside_mask_within_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntMaskSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntAndSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntOrSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntXorSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "ExampleBitSet_Len" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fbfae49949f4b8684d39aece0d5ff86787ed064c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__xzau3frn/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "96509636a8ebd03729fcc7479b6e3dbac433b415d482e4e8bf224de94b4c1a53", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..2010ad25c27fc615447c558396b1c56ef0720cc9 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/bitset.go @@ -0,0 +1,1756 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length >= b.length { + b.extendSet(compare.length) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] = data[i] ^ cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] |= compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0b9e23ec1fd2d8d400ab9ce6634587a201e34cb --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/instruction.md @@ -0,0 +1,42 @@ +InPlaceSymmetricDifference produces incorrect results + +#### Description + +The `InPlaceSymmetricDifference` method is not producing symmetric results when operating on bitsets of different sizes. The symmetric difference operation should be commutative (A ⊕ B = B ⊕ A), but currently it's not working correctly. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create two bitsets of different sizes + a := bitset.New(10) + b := bitset.New(20) + + // Set some bits + a.Set(1).Set(3).Set(5) + b.Set(3).Set(7).Set(15) + + // Make copies for testing symmetry + a1 := a.Clone() + b1 := b.Clone() + + // Perform symmetric difference in both directions + a1.InPlaceSymmetricDifference(b1) + b.InPlaceSymmetricDifference(a) + + // These should be equal but they're not + fmt.Printf("a ⊕ b: %s\n", a1.String()) + fmt.Printf("b ⊕ a: %s\n", b.String()) + fmt.Printf("Equal: %v\n", a1.Equal(b)) +} +``` + +The symmetric difference should produce the same result regardless of operand order, but currently it doesn't when the bitsets have different lengths. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..8383b490cfb5865b664f21f37d4d678c52961268 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/provenance.json @@ -0,0 +1,248 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "original-bug": "task-specific unchanged semantic bug", + "partial-repair": "strict partial repair candidate with independently unproven wrongness", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "acceptance_disposition": "needs_semantic_review; may be a legitimate alternative; do not cherry-pick another canary from measured rewards", + "candidate_file_inventory": { + "bitset.go": { + "mode": "0o644", + "sha256": "561b691a80dcdfb1c69622456aebe6d4751434256287371c03b1477de825ad5b", + "size": 47830 + } + }, + "expected_wrongness": "unproven until independent semantic review", + "original_patch_hunks": 2, + "original_patch_sha256": "6ab8392612a2e854ef53e6c7667ca6fcc06274b627b1a33660d81de37a0822ae", + "retained_mutation_file": "bitset.go", + "retained_mutation_hunk_sha256": "a589a9b405c1f2ad1061061be4fd8a1c1d5c7cadb4e03cd9c83ba1fdf4c950d9" + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "f2be1252cd2703161c4d837036bc0c95bf64fc13c96b0ac463c997d4d4a47ddd", + "size": 47840 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "production/runtime-images-v1/resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "66c5be0a5f6559a31c0cf160e595f295d17c0dbddda200b416e2de9191665056", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "65b8137e64557b44a6822c608766fcb07c0186cccc126e4152e80a22406b5699", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "067d14ee57b4d5253dbe1e40176d049d08473c267ff725239e28b09d02dd955d", + "is_fork": true, + "learner_path": "tasks/ba2e34bd5e18ee8bf056981d/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/8a95c0ae52ce1cfe0623e89a7c4fa4a501eade22/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "6ab8392612a2e854ef53e6c7667ca6fcc06274b627b1a33660d81de37a0822ae", + "provenance_path": "tasks/ba2e34bd5e18ee8bf056981d/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "8a95c0ae52ce1cfe0623e89a7c4fa4a501eade22", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "2c3f76b952fe50b262c68a611cf198fe8dcfebb4", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l", + "task_sha256": "7400ecac27fea527e48656b13929d67fb39f0a80cc1873d99fc1b141ca38bbac", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "de9ea0ba72b11458920d1f6b20d3971c444427dd0be8be934d88fcd1474424db", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5kIGJvb2xlYW4gdmFsdWVzLiBJdCBzaG91bGQgYmUgbW9yZQplZmZpY2llbnQgdGhhbiBtYXBbdWludF0gYm9vbC4KCkl0IHByb3ZpZGVzIG1ldGhvZHMgZm9yIHNldHRpbmcsIGNsZWFyaW5nLCBmbGlwcGluZywgYW5kIHRlc3RpbmcKaW5kaXZpZHVhbCBpbnRlZ2Vycy4KCkJ1dCBpdCBhbHNvIHByb3ZpZGVzIHNldCBpbnRlcnNlY3Rpb24sIHVuaW9uLCBkaWZmZXJlbmNlLApjb21wbGVtZW50LCBhbmQgc3ltbWV0cmljIG9wZXJhdGlvbnMsIGFzIHdlbGwgYXMgdGVzdHMgdG8KY2hlY2sgd2hldGhlciBhbnksIGFsbCwgb3Igbm8gYml0cyBhcmUgc2V0LCBhbmQgcXVlcnlpbmcgYQpiaXRzZXQncyBjdXJyZW50IGxlbmd0aCBhbmQgbnVtYmVyIG9mIHBvc2l0aXZlIGJpdHMuCgpCaXRTZXRzIGFyZSBleHBhbmRlZCB0byB0aGUgc2l6ZSBvZiB0aGUgbGFyZ2VzdCBzZXQgYml0OyB0aGUKbWVtb3J5IGFsbG9jYXRpb24gaXMgYXBwcm94aW1hdGVseSBNYXggYml0cywgd2hlcmUgTWF4IGlzCnRoZSBsYXJnZXN0IHNldCBiaXQuIEJpdFNldHMgYXJlIG5ldmVyIHNocnVuay4gT24gY3Jl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HVpbnQ4KHcgPj4gc2hpZnQpCgkJbWFzayA6PSB1aW50OChtID4+IHNoaWZ0KQoKCQlleHRyYWN0ZWQgOj0gcGV4dExVVFtiXVttYXNrXQoJCWJpdHMgOj0gcG9wTFVUW21hc2tdCgoJCXJlc3VsdCB8PSB1aW50NjQoZXh0cmFjdGVkKSA8PCBvdXRQb3MKCQlvdXRQb3MgKz0gdWludChiaXRzKQoJfQoKCXJldHVybiByZXN1bHQKfQoKZnVuYyBwZGVwKHcsIG0gdWludDY0KSAocmVzdWx0IHVpbnQ2NCkgewoJdmFyIGluUG9zIHVpbnQKCgkvLyBQcm9jZXNzIGJ5dGUgYnkgYnl0ZQoJZm9yIGkgOj0gMDsgaSA8IDg7IGkrKyB7CgkJc2hpZnQgOj0gaSA8PCAzIC8vIGkgKiA4IHVzaW5nIGJpdCBzaGlmdAoJCW1hc2sgOj0gdWludDgobSA+PiBzaGlmdCkKCQliaXRzIDo9IHBvcExVVFttYXNrXQoKCQkvLyBHZXQgdGhlIGJpdHMgd2UnbGwgZGVwb3NpdCBmcm9tIHRoZSBzb3VyY2UKCQliIDo9IHVpbnQ4KHcgPj4gaW5Qb3MpCgoJCS8vIERlcG9zaXQgdGhlbSBhY2NvcmRpbmcgdG8gdGhlIG1hc2sgZm9yIHRoaXMgYnl0ZQoJCWRlcG9zaXRlZCA6PSBwZGVwTFVUW2JdW21hc2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6aba8c5f840cf6ed9a3ebd0056964ca177bfb317 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:d39aae95f8d2d668ed1065c0845bc432e4979eb334e4e49f609e442059c3f94e" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..62e072cedcf7ef486ac6b19d5c4c66b2b2506ff9 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/manifest.json @@ -0,0 +1,1049 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWords" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWordsNeededLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestTestTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestRankSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlip" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlipRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyUnaligned" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitStrings" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitSetInstance" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWriteTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/nil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_10" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_63" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_65" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_640" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/shift_to_full_page" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/remove_all" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/slightly_offset_results" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/first_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/third_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/way_off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/split_between_two_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/partly_off_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/skip_one_nibble" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/empty_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/invalid_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word_full" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/multiple_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPdep" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/single_bit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/two_sequential_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/extracting_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/large_gaps" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/depositing_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_unmasked_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_bits_outside_mask_within_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntMaskSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntAndSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntOrSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntXorSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "ExampleBitSet_Len" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/partial-repair.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/partial-repair.sh new file mode 100644 index 0000000000000000000000000000000000000000..40f4866100e34356a66850e687d36598e15e8399 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/partial-repair.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5kIGJvb2xlYW4gdmFsdWVzLiBJdCBzaG91bGQgYmUgbW9yZQplZmZpY2llbnQgdGhhbiBtYXBbdWludF0gYm9vbC4KCkl0IHByb3ZpZGVzIG1ldGhvZHMgZm9yIHNldHRpbmcsIGNsZWFyaW5nLCBmbGlwcGluZywgYW5kIHRlc3RpbmcKaW5kaXZpZHVhbCBpbnRlZ2Vycy4KCkJ1dCBpdCBhbHNvIHByb3ZpZGVzIHNldCBpbnRlcnNlY3Rpb24sIHVuaW9uLCBkaWZmZXJlbmNlLApjb21wbGVtZW50LCBhbmQgc3ltbWV0cmljIG9wZXJhdG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bmcgdG8gdGhlIG1hc2sgZm9yIHRoaXMgYnl0ZQoJCWRlcG9zaXRlZCA6PSBwZGVwTFVUW2JdW21hc2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..86e3cd590e17c1914d1321f2c0d616401df2ac9e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__yrye1q5l/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "7822d64f7957ef1093a174b2f4ac0c7ac8896454e6f0e23216253f3b7379799d", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..46d05b9ed8ebe3ba6adbec8ec9ceeb2662a9508f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/bitset.go @@ -0,0 +1,1756 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..87aeefd737495831f39762988aaaa020db6ba7ce --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa18dceb32d2796c433efcc98c5eb7f9f058fd6f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/instruction.md @@ -0,0 +1,51 @@ +EachSet iterator returns incorrect bit positions + +#### Description + +The `EachSet()` iterator is returning incorrect bit positions when iterating over set bits in a BitSet. The positions returned are consistently lower than the actual bit positions that were set. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + bs := bitset.New(128) + + // Set some specific bits + bs.Set(3) + bs.Set(5) + bs.Set(6) + bs.Set(63) + bs.Set(65) + bs.Set(127) + + fmt.Println("Expected positions: 3, 5, 6, 63, 65, 127") + fmt.Print("Actual positions: ") + + for pos := range bs.EachSet() { + fmt.Printf("%d ", pos) + } + fmt.Println() +} +``` + +Expected output: +``` +Expected positions: 3, 5, 6, 63, 65, 127 +Actual positions: 3 5 6 63 65 127 +``` + +Actual output: +``` +Expected positions: 3, 5, 6, 63, 65, 127 +Actual positions: 2 1 0 56 64 125 +``` + +The iterator is consistently returning positions that are offset from the correct values, particularly noticeable when bits span across word boundaries (64-bit words). +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..11c9d35168c51402e23376b94b1be53ee4d1037f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "b7d0009b4a68db3cea6add8b96db1316579f21414bb1030bbb58258f92fd0918", + "size": 47836 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "f3c506a335e9ab3ef784588de2497939064593421c76871d209a43f199e97327", + "size": 427 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "production/runtime-images-v1/resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "6ef84246b47ca4a6e9989f775ae2f65f9fc2845b3c69a1a172893430af46f954", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "26f35e200642453ec048e97a229b8b45295a8257d0194d3a1d1f691476e4b797", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_modify__z28xc391", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "eff2d155a4f74396710763246da48540f29fdbdfc9b39e2080489d04bb5f0370", + "is_fork": true, + "learner_path": "tasks/64ebc3cf1c4db70d7c053b00/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/a897d1cf0fb2fd60dd7fc180d4f353e7119bb73f/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "71ac9577e64de4ad926ef83dcd7d547e9eab73cb084e8f2dda0edeecf97f99d4", + "provenance_path": "tasks/64ebc3cf1c4db70d7c053b00/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "a897d1cf0fb2fd60dd7fc180d4f353e7119bb73f", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "a68ba8434976df01a4e831a43263e500f77f6ab1", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_modify__z28xc391", + "task_sha256": "35646029e82850aea50d22a52ef3a1a8644e94b0679b375e5eda24fe82705559", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "1dd6e54cd426da9b810fd54f80c31fa0780e358f727195148a187eebb6ab9a71", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..43bb8614b656a729e962ad8dbae3d23262f2523f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset_iter.go": {"data": "Ly9nbzpidWlsZCBnbzEuMjMKLy8gK2J1aWxkIGdvMS4yMwoKcGFja2FnZSBiaXRzZXQKCmltcG9ydCAoCgkiaXRlciIKCSJtYXRoL2JpdHMiCikKCmZ1bmMgKGIgKkJpdFNldCkgRWFjaFNldCgpIGl0ZXIuU2VxW3VpbnRdIHsKCXJldHVybiBmdW5jKHlpZWxkIGZ1bmModWludCkgYm9vbCkgewoJCWZvciB3b3JkSW5kZXgsIHdvcmQgOj0gcmFuZ2UgYi5zZXQgewoJCQlpZHggOj0gMAoJCQlmb3IgdHJhaWwgOj0gYml0cy5UcmFpbGluZ1plcm9zNjQod29yZCk7IHRyYWlsICE9IDY0OyB0cmFpbCA9IGJpdHMuVHJhaWxpbmdaZXJvczY0KHdvcmQgPj4gaWR4KSB7CgkJCQlpZiAheWllbGQodWludCh3b3JkSW5kZXg8PGxvZzJXb3JkU2l6ZSArIGlkeCArIHRyYWlsKSkgewoJCQkJCXJldHVybgoJCQkJfQoJCQkJaWR4ICs9IHRyYWlsICsgMQoJCQl9CgkJfQoJfQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a204a379d736c52f89c2c38a601b78daf9a111f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:c1610246fa1a6f85ac834b07baa8e4c13037900b824dfa8b092b90a5dc363855" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ee6404105797d7c64668c4df5ae3d7c576d659fa --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/manifest.json @@ -0,0 +1,1049 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWords" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWordsNeededLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestTestTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestRankSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlip" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlipRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyUnaligned" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitStrings" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitSetInstance" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWriteTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/nil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_10" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_63" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_65" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_640" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/shift_to_full_page" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/remove_all" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/slightly_offset_results" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/first_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/third_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/way_off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/split_between_two_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/partly_off_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/skip_one_nibble" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/empty_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/invalid_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word_full" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/multiple_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPdep" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/single_bit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/two_sequential_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/extracting_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/large_gaps" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/depositing_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_unmasked_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_bits_outside_mask_within_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntMaskSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntAndSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntOrSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntXorSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "ExampleBitSet_Len" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fe57e685ab247bdab914c38129b73f9ce3e2682f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z28xc391/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "818fad99d78d046b16f411a9dd0d6b86e9dec2a599d8487c1a95cbd1728cb19c", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..0112a03a2b7b8c2ae029051235d3ba86080e5895 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/bitset.go @@ -0,0 +1,1756 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^(word & 0xFFFFFFFF) + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f2e097babe5d8a544e821b53be48a4232263603 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/instruction.md @@ -0,0 +1,32 @@ +Complement operation returns incorrect bit count + +#### Description + +The Complement method is producing bitsets with an incorrect number of set bits. When complementing a bitset, the resulting count is off by one. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create a bitset with length 48 + bs := bitset.New(48) + bs.Set(0) // Set one bit + + // Complement it + complement := bs.Complement() + + fmt.Printf("Original bitset count: %d\n", bs.Count()) + fmt.Printf("Complement count: %d\n", complement.Count()) + fmt.Printf("Expected complement count: %d\n", 47) // Should be 47, not 48 +} +``` + +The complement should have 47 bits set (48 total - 1 set bit), but it's returning 48 instead. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..710a67769386297317a08b1e88c9fd3ebb7a1b57 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "2e6496ceec8721ec8befcdfdc06110e08538a7de041ba782873da9a9b0c0ea2c", + "size": 47851 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "production/runtime-images-v1/resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "21fc51a48af9ae9e0f1685e558bbef9511790ed00bd93b95f0824aa07442e89e", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "5a3e1a4fb73a6af85ed86f2cc17ab8b90afd31d76bc4a58ee67bdc2b37644040", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "8ea75315bafc4818453c3c890156e44dd846624e8fbedf82fd1cbcebfa35177e", + "is_fork": true, + "learner_path": "tasks/69f35fc35bd4356e0e2dfab1/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/fbdeb96df8bd7ca1b191d80f2e4e61e689cd1dd7/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "51926114bc5d0137f88f060915fc52e2d66136bdf9816c527639feb0b32bb3b4", + "provenance_path": "tasks/69f35fc35bd4356e0e2dfab1/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "fbdeb96df8bd7ca1b191d80f2e4e61e689cd1dd7", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "293f6dab0c15085a19ee2aeca826ab1870ccb8ca", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m", + "task_sha256": "7f12257ece8dbafddbdc1bb2e1373087ed35b0399150959e8178d95be66fe8c9", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "c4e371615910af75b658e7a8ea5fd1e9f8c454b153f7c5b79a65d249c6507284", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5kIGJvb2xlYW4gdmFsdWVzLiBJdCBzaG91bGQgYmUgbW9yZQplZmZpY2llbnQgdGhhbiBtYXBbdWludF0gYm9vbC4KCkl0IHByb3ZpZGVzIG1ldGhvZHMgZm9yIHNldHRpbmcsIGNsZWFyaW5nLCBmbGlwcGluZywgYW5kIHRlc3RpbmcKaW5kaXZpZHVhbCBpbnRlZ2Vycy4KCkJ1dCBpdCBhbHNvIHByb3ZpZGVzIHNldCBpbnRlcnNlY3Rpb24s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yY2UKCQliIDo9IHVpbnQ4KHcgPj4gaW5Qb3MpCgoJCS8vIERlcG9zaXQgdGhlbSBhY2NvcmRpbmcgdG8gdGhlIG1hc2sgZm9yIHRoaXMgYnl0ZQoJCWRlcG9zaXRlZCA6PSBwZGVwTFVUW2JdW21hc2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0380859fa162c44b9ed879ef019f3266c4659d5c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/task.toml @@ -0,0 +1,10 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..d61823f1f3423bd77b853ec2269a1592a2c171b8 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/manifest.json @@ -0,0 +1,1049 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWords" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWordsNeededLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestTestTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestRankSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlip" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlipRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyUnaligned" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitStrings" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitSetInstance" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWriteTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/nil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_10" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_63" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_65" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_640" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/shift_to_full_page" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/remove_all" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/slightly_offset_results" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/first_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/third_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/way_off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/split_between_two_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/partly_off_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/skip_one_nibble" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/empty_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/invalid_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word_full" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/multiple_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPdep" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/single_bit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/two_sequential_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/extracting_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/large_gaps" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/depositing_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_unmasked_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_bits_outside_mask_within_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntMaskSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntAndSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntOrSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntXorSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "ExampleBitSet_Len" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..c74dc82b26ac2d3fdd1648a108f8d2fae668afa3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_modify__z3duw80m/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "e8892d4c74232108839bf2eb22a523a091362e955315610ff072e46acc8f903a", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..8f9a0f71156076f8cd954ee473217ea695c204b4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/bitset.go @@ -0,0 +1,1759 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cce25548e14679bf2d8f1417773db1044da5482d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/instruction.md @@ -0,0 +1,39 @@ +BitSet.wordCount() returns incorrect value after change + +#### Description + +The `wordCount()` method now returns the length of the underlying slice instead of the calculated word count based on the bit set's length. This causes issues when the underlying slice has been resized or when comparing bit sets. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create a bitset and set some bits + bs := bitset.New(100) + bs.Set(50) + + // The wordCount should be based on the length (100 bits) + // but now returns the actual slice length which may differ + fmt.Printf("Expected word count based on length: %d\n", (100+63)/64) + fmt.Printf("Actual word count: %d\n", bs.wordCount()) // This may differ now + + // This can cause problems in operations like Equal() + bs1 := bitset.New(100) + bs2 := bitset.New(100) + bs1.Set(50) + bs2.Set(50) + + // These should be equal but may not be due to wordCount mismatch + fmt.Printf("BitSets equal: %v\n", bs1.Equal(bs2)) +} +``` + +The issue occurs because `wordCount()` now returns `len(b.set)` instead of calculating the required words based on `b.length`. This can lead to inconsistencies when the underlying slice has been resized or when comparing bit sets that should be equivalent. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..6d26bf41a80533155d6ab442878a2e85ead31394 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "1a55012b0d7763ee12d4abfbd7e80a96d9e922e5c8769e085bc243f231dff459", + "size": 47863 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "54d3a28a74026fa147b62683d4bea7754120cffad82369ce2f8102755979a866", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "21a7a3ff14d8dc41f94bcad7ea4611832de5e886455416ca8357de7f88c02bd5", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "55b01266525493797d51b6face1f50c57676a2159debd8485b66f80e75c56133", + "is_fork": true, + "learner_path": "tasks/9101ba78c2fdf16966ffe21e/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/0b8fdcd0582399e9dcca4c82801a5b9bb78b419a/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "6ca499804fe81399a430ca64c633e545afb057177f8081c206e37e82f2316c2f", + "provenance_path": "tasks/9101ba78c2fdf16966ffe21e/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "0b8fdcd0582399e9dcca4c82801a5b9bb78b419a", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "cc2d829beccbd581cb66fceb0f4713884328bdb0", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs", + "task_sha256": "552b578b2ef5433bdc898bf58d8c04a44c9195a39da5ab61ca084b2d337e58d8", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "0fe0f43b5f007bb2083f387c9fa85196617fa045f17ca252bba6f806be994d22", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5kIGJvb2xlYW4gdmFsdWVzLiBJdCBzaG91bGQgYmUgbW9yZQplZmZpY2llbnQgdGhhbiBtYXBbdWludF0gYm9vbC4KCkl0IHByb3ZpZGVzIG1ldGhvZHMgZm9yIHNldHRpbmcsIGNsZWFyaW5nLCBmbGlwcGluZywgYW5kIHRlc3RpbmcKaW5kaXZpZHVhbCBpbnRlZ2Vycy4KCkJ1dCBpdCBhbHNvIHByb3ZpZGVzIHNldCBpbnRlcnNlY3Rpb24sIHVuaW9uLCBkaWZmZXJlbmNlLApjb21wbGVtZW50LCBhbmQgc3ltbWV0cmljIG9wZXJhdGlvbnMsIGFzIHdlbGwgYXMgdGVzdHMgdG8KY2hlY2sgd2hldGhlciBhbnksIGFsbCwgb3Igbm8gYml0cyBhcmUgc2V0LCBhbmQgcXVlcnlpbmcgYQpiaXRzZXQncyBjdXJyZW50IGxlbmd0aCBhbmQgbnVtYmVyIG9mIHBvc2l0aXZlIGJpdHMuCgpCaXRTZXRzIGFyZSBleHBhbmRlZCB0byB0aGUgc2l6ZSBvZiB0aGUgbGFyZ2VzdCBzZXQgYml0OyB0aGUKbWVtb3J5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=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea05ef0b675832219af4361c2c79547294a15482 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:24483854a51a4be3da0af250841323900036316cacd0c3d47d63564d3c087271" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..5fcc7f7672532714a2d0c729f0ff200fe95ceef9 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/manifest.json @@ -0,0 +1,454 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..903e1ae2fcd5005c9e04e37090c7a67369d6bf80 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__22dqgexs/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "465fce0f8d2629ff4f6ee23554c812fcc0df07fac1e6aaa7acfceb433192921c", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..0935947688bfde952ac4a07bfe07a66a6479b28c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/bitset.go @@ -0,0 +1,1762 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + // If from >= to, return 0 as specified + if from >= to { + return 0 + } + + // If the range is beyond the length of the bitset, adjust 'to' + if to > b.length { + to = b.length + } + + // If from is beyond the length or the adjusted range is empty, return 0 + if from >= b.length || from >= to { + return 0 + } + + // Calculate word indices and bit positions + fromWord := from >> log2WordSize + toWord := (to - 1) >> log2WordSize + + // If the range is within a single word + if fromWord == toWord { + // Create a mask for the bits in the range + mask := (uint64(1) << (to - from)) - 1 + mask = mask << wordsIndex(from) + return uint(bits.OnesCount64(b.set[fromWord] & mask)) + } + + // Count bits in multiple words + count := uint(0) + + // First word - count bits from the 'from' position to the end of the word + firstWordMask := allBits << wordsIndex(from) + count += uint(bits.OnesCount64(b.set[fromWord] & firstWordMask)) + + // Middle words - count all bits + for word := fromWord + 1; word < toWord; word++ { + count += uint(bits.OnesCount64(b.set[word])) + } + + // Last word - count bits from the start of the word to the 'to' position + lastWordMask := allBits >> (wordSize - wordsIndex(to)) + count += uint(bits.OnesCount64(b.set[toWord] & lastWordMask)) + + return count +} + +// Extract extracts bits according to a mask and returns the result +// in a new BitSet. See ExtractTo for details. +func (b *BitSet) Extract(mask *BitSet) *BitSet { + dst := New(mask.Count()) + b.ExtractTo(mask, dst) + return dst +} + +// ExtractTo copies bits from the BitSet using positions specified in mask +// into a compacted form in dst. The number of set bits in mask determines +// the number of bits that will be extracted. +// +// For example, if mask has bits set at positions 1,4,5, then ExtractTo will +// take bits at those positions from the source BitSet and pack them into +// consecutive positions 0,1,2 in the destination BitSet. +func (b *BitSet) ExtractTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(mask.set) == 0 || len(b.set) == 0 { + return + } + + // Ensure destination has enough space for extracted bits + resultBits := uint(popcntSlice(mask.set)) + if dst.length < resultBits { + dst.extendSet(resultBits - 1) + } + + outPos := uint(0) + length := len(mask.set) + if len(b.set) < length { + length = len(b.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to extract + } + + // Extract and compact bits according to mask + extracted := pext(b.set[i], mask.set[i]) + bitsExtracted := uint(bits.OnesCount64(mask.set[i])) + + // Calculate destination position + wordIdx := outPos >> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5ea41ccdacd74398641f5a8f24cbfb9d4356e55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/instruction.md @@ -0,0 +1,51 @@ +OnesBetween returns incorrect count when range spans multiple words + +#### Description + +The `OnesBetween` method is returning incorrect counts when the bit range spans multiple words. The method appears to be undercounting the number of set bits in certain scenarios. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create a bitset and set some bits + bs := bitset.New(1000) + + // Set bits in a pattern that spans multiple words + for i := uint(0); i < 500; i += 3 { + bs.Set(i) + } + + // Count ones in a range that spans multiple words + count := bs.OnesBetween(100, 400) + + // Manual verification by iterating through the range + expected := uint(0) + for i := uint(100); i < 400; i++ { + if bs.Test(i) { + expected++ + } + } + + fmt.Printf("OnesBetween(100, 400) returned: %d\n", count) + fmt.Printf("Expected count: %d\n", expected) + + if count != expected { + fmt.Printf("ERROR: Counts don't match!\n") + } +} +``` + +This will show that `OnesBetween` returns a lower count than expected when manually counting the bits in the same range. + +The issue seems to occur specifically when: +- The range spans multiple 64-bit words +- There are set bits in the boundary words that should be included in the count +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..c235ad260f38d608084917da2fa87286201cad19 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "b958889c32535f70b27d71b6562e9e9fd9673c35a4e9598d95997ce06d97257f", + "size": 47929 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "production/runtime-images-v1/resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "618017fd8b87eeb5864e5cecdddbfa6b97cef94184432dfb0022b21f5f2148df", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "56d53ae31751170b59e1c92fed35a9339b1882821744d17670752c882e210821", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "e2126813125d396306ec55d99293025c567ec6754a8938e68dbf302a3ff4b2f2", + "is_fork": true, + "learner_path": "tasks/a9200da6ca411d92c2b201d4/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/a6b9ccaa65708321c9d3a85f88b6752e21682a04/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "05bf65025825e8440c0ca9073bec15a33319392110af25b9ba860fe3dcd10d87", + "provenance_path": "tasks/a9200da6ca411d92c2b201d4/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "a6b9ccaa65708321c9d3a85f88b6752e21682a04", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "e9c96cbb46056a46bea94f522c38f1826d6a1c45", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7", + "task_sha256": "18297f751a0f497b6ab12388e6fe7f9387e8df2212b683ddccb6acee56a6b88d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "53c5fbd9a3a9900c2e56517dd559ef8c8ec926ec589be29d03d3b1e6a86a3c3f", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGF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oKCXJldHVybiByZXN1bHQKfQoKZnVuYyBwZGVwKHcsIG0gdWludDY0KSAocmVzdWx0IHVpbnQ2NCkgewoJdmFyIGluUG9zIHVpbnQKCgkvLyBQcm9jZXNzIGJ5dGUgYnkgYnl0ZQoJZm9yIGkgOj0gMDsgaSA8IDg7IGkrKyB7CgkJc2hpZnQgOj0gaSA8PCAzIC8vIGkgKiA4IHVzaW5nIGJpdCBzaGlmdAoJCW1hc2sgOj0gdWludDgobSA+PiBzaGlmdCkKCQliaXRzIDo9IHBvcExVVFttYXNrXQoKCQkvLyBHZXQgdGhlIGJpdHMgd2UnbGwgZGVwb3NpdCBmcm9tIHRoZSBzb3VyY2UKCQliIDo9IHVpbnQ4KHcgPj4gaW5Qb3MpCgoJCS8vIERlcG9zaXQgdGhlbSBhY2NvcmRpbmcgdG8gdGhlIG1hc2sgZm9yIHRoaXMgYnl0ZQoJCWRlcG9zaXRlZCA6PSBwZGVwTFVUW2JdW21hc2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..552ee70e4b677995cc218dc56c6f5f2ea3e969cb --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:00a63aae86a0c37e00673898efef9bd629c9c0ef109aa7bf39cf850f89d4c1e7" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f1028ffd12965af27352ce00d8fed638f5ea7013 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/manifest.json @@ -0,0 +1,1049 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWords" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWordsNeededLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestTestTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestRankSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlip" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlipRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyUnaligned" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitStrings" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitSetInstance" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWriteTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/nil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_10" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_63" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_65" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_640" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/shift_to_full_page" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/remove_all" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/slightly_offset_results" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/first_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/third_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/way_off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/split_between_two_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/partly_off_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/skip_one_nibble" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/empty_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/invalid_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word_full" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/multiple_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPdep" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/single_bit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/two_sequential_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/extracting_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/large_gaps" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/depositing_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_unmasked_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_bits_outside_mask_within_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntMaskSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntAndSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntOrSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntXorSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "ExampleBitSet_Len" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..cd6052e371b121ad49376d70cd24ae2fe6492825 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__2slz4zg7/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "645696c6d8f1f5750b2d1f6970c3f31f2f402b3e68e89928517c48df35f0f3ca", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..dbef7bbf3c56a1d1d2372a68fc7591ee54b6b906 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/bitset.go @@ -0,0 +1,1753 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + if len(buffer) == 0 { + return i, buffer[:0] + } + + x := int(i >> log2WordSize) + if x >= len(b.set) { + return i, buffer[:0] + } + + bufferSize := len(buffer) + bufferPos := 0 + + // Process first (partial) word + word := b.set[x] >> wordsIndex(i) + for word != 0 && bufferPos < bufferSize { + t := bits.TrailingZeros64(word) + buffer[bufferPos] = i + uint(t) + bufferPos++ + word &= ^(uint64(1) << t) // Clear the bit we just processed + } + + // If buffer is full, return + if bufferPos >= bufferSize { + return buffer[bufferPos-1] + 1, buffer[:bufferPos] + } + + // Process remaining words + x++ + for ; x < len(b.set) && bufferPos < bufferSize; x++ { + word := b.set[x] + for word != 0 && bufferPos < bufferSize { + t := bits.TrailingZeros64(word) + buffer[bufferPos] = uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (maybe partial) word + word := b.set[x] + word = word >> wordsIndex(i) + wordAll := allBits >> wordsIndex(i) + + index := i + uint(bits.TrailingZeros64(^word)) + if word != wordAll && index < b.length { + return index, true + } + + // process the following full words until next bit is cleared + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != allBits { + index = uint((x+idx)*wordSize + bits.TrailingZeros64(^word)) + if index < b.length { + return index, true + } + } + } + + return 0, false +} + +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85461390daf9ebf7e99e0871967d672b868d118f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/instruction.md @@ -0,0 +1,39 @@ +NextSetMany returns empty buffer instead of populated results + +#### Description + +The `NextSetMany` function is returning an empty buffer instead of the expected set bit indices. When calling `NextSetMany` with a buffer to collect multiple set bits, the function returns an empty slice regardless of the actual set bits present in the BitSet. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create a bitset and set some bits + bs := bitset.New(100) + bs.Set(0).Set(1).Set(5).Set(65).Set(130) + + // Try to get multiple set bits starting from index 0 + buffer := make([]uint, 10) + nextIdx, results := bs.NextSetMany(0, buffer) + + fmt.Printf("Expected: [0 1 5 65 130]\n") + fmt.Printf("Got: %v\n", results) + fmt.Printf("Next index - Expected: 131, Got: %d\n", nextIdx) +} +``` + +This should return the set bit indices `[0 1 5 65 130]` but instead returns an empty slice `[]`. + +The issue affects various scenarios: +- Getting bits from the beginning of the bitset +- Getting bits starting from a specific index +- Cases where the buffer is smaller than the number of available set bits +- Both single-word and multi-word scenarios +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..83ec89ce6d22a61b644fbe5a2b204b6e5636fe7e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "db198dc287c5a940eb937d9ab207fb28cc8c282924db8a35dbddf3456a2199c7", + "size": 47839 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "production/runtime-images-v1/resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "735fefefdd19cb2ed6cfbba5f09014d9ddf817b46762cc57a21ebbf2fdfac7f7", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "4f932774d6b226df3c40df3dea2a50e891e93af9b0d5201359d6eebd432052e5", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "23340a20bac9caa0135b2c5c10674a87d6584243698ed82947c6c862e4847a6a", + "is_fork": true, + "learner_path": "tasks/01f5b57ce4418a7156725e81/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/2c497f1dc5f75e40dd092b0cb3ec2187458c886e/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "f2da468d04647ca09959d1f67a2469e391f34df9046062daa7c64621a55ef23b", + "provenance_path": "tasks/01f5b57ce4418a7156725e81/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "2c497f1dc5f75e40dd092b0cb3ec2187458c886e", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "bf3e584faa427097aa450efe19fac5ff5f79c1b9", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x", + "task_sha256": "78f7a71dbae813995d27b8a31aa6ba4638db373b8e42687c981b7625b1fcd43c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "12762e9d0196ed0e287a6efa84ec59669b3bb1ee044ebdb403ddc182fc331296", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5kIGJvb2xlYW4gdmFsdWVzLiBJdC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gYnl0ZQoJZm9yIGkgOj0gMDsgaSA8IDg7IGkrKyB7CgkJc2hpZnQgOj0gaSA8PCAzIC8vIGkgKiA4IHVzaW5nIGJpdCBzaGlmdAoJCW1hc2sgOj0gdWludDgobSA+PiBzaGlmdCkKCQliaXRzIDo9IHBvcExVVFttYXNrXQoKCQkvLyBHZXQgdGhlIGJpdHMgd2UnbGwgZGVwb3NpdCBmcm9tIHRoZSBzb3VyY2UKCQliIDo9IHVpbnQ4KHcgPj4gaW5Qb3MpCgoJCS8vIERlcG9zaXQgdGhlbSBhY2NvcmRpbmcgdG8gdGhlIG1hc2sgZm9yIHRoaXMgYnl0ZQoJCWRlcG9zaXRlZCA6PSBwZGVwTFVUW2JdW21hc2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4b6632b963c461e1a3a950f575ae2c85e09dd16c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:6fe61794277ce4e1d31c3faf1b2401cb0066285df1f50329904a24a60148a2c0" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ca6905819ac31d31de70049375447fbae9ee5108 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/manifest.json @@ -0,0 +1,1049 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWords" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWordsNeededLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestTestTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestRankSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlip" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlipRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyUnaligned" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitStrings" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitSetInstance" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWriteTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/nil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_10" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_63" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_65" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_640" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/shift_to_full_page" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/remove_all" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/slightly_offset_results" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/first_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/third_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/way_off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/split_between_two_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/partly_off_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/skip_one_nibble" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/empty_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/invalid_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word_full" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/multiple_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPdep" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/single_bit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/two_sequential_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/extracting_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/large_gaps" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/depositing_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_unmasked_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_bits_outside_mask_within_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntMaskSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntAndSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntOrSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntXorSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "ExampleBitSet_Len" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..137377e332be1b02dbf720a9d20a6f37e8b26e85 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__4q2une2x/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "13dd1773b7e2b6b1533859fd9b4c07f9dc1ea89ae06a0bf3eabd5a3525cfdb26", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi; diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/LICENSE b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..59cab8a939be75e5786e202364996d6d56d2d863 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 Will Fitzgerald. All rights reserved. + +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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER 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/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/README.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b245facb7ec90afa7b800faa36e73f2aa5c12f4c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/README.md @@ -0,0 +1,166 @@ +# bitset + +*Go language library to map between non-negative integers and boolean values* + +[![Test](https://github.com/bits-and-blooms/bitset/workflows/Test/badge.svg)](https://github.com/willf/bitset/actions?query=workflow%3ATest) +[![Go Report Card](https://goreportcard.com/badge/github.com/willf/bitset)](https://goreportcard.com/report/github.com/willf/bitset) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/bits-and-blooms/bitset?tab=doc)](https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc) + + +This library is part of the [awesome go collection](https://github.com/avelino/awesome-go). It is used in production by several important systems: + +* [beego](https://github.com/beego/beego) +* [CubeFS](https://github.com/cubefs/cubefs) +* [Amazon EKS Distro](https://github.com/aws/eks-distro) +* [sourcegraph](https://github.com/sourcegraph/sourcegraph-public-snapshot) +* [torrent](https://github.com/anacrolix/torrent) + + +## Description + +Package bitset implements bitsets, a mapping between non-negative integers and boolean values. +It should be more efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing individual integers. + +But it also provides set intersection, union, difference, complement, and symmetric operations, as well as tests to check whether any, all, or no bits are set, and querying a bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the memory allocation is approximately Max bits, where Max is the largest set bit. BitSets are never shrunk automatically, but `Shrink` and `Compact` methods are available. On creation, a hint can be given for the number of bits that will be used. + +Many of the methods, including Set, Clear, and Flip, return a BitSet pointer, which allows for chaining. + +### Example use: + +```go +package main + +import ( + "fmt" + "math/rand" + + "github.com/bits-and-blooms/bitset" +) + +func main() { + fmt.Printf("Hello from BitSet!\n") + var b bitset.BitSet + // play some Go Fish + for i := 0; i < 100; i++ { + card1 := uint(rand.Intn(52)) + card2 := uint(rand.Intn(52)) + b.Set(card1) + if b.Test(card2) { + fmt.Println("Go Fish!") + } + b.Clear(card1) + } + + // Chaining + b.Set(10).Set(11) + + for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { + fmt.Println("The following bit is set:", i) + } + if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { + fmt.Println("Intersection works.") + } else { + fmt.Println("Intersection doesn't work???") + } +} +``` + +If you have Go 1.23 or better, you can iterate over the set bits like so: + +```go +for i := range b.EachSet() {} +``` + + + +Package documentation is at: https://pkg.go.dev/github.com/bits-and-blooms/bitset?tab=doc + +## Serialization + + +You may serialize a bitset safely and portably to a stream +of bytes as follows: +```Go + const length = 9585 + const oneEvery = 97 + bs := bitset.New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + // failure + } + // Here n == buf.Len() +``` +You can later deserialize the result as follows: + +```Go + // Read back from buf + bs = bitset.New() + n, err = bs.ReadFrom(&buf) + if err != nil { + // error + } + // n is the number of bytes read +``` + +The `ReadFrom` function attempts to read the data into the existing +BitSet instance, to minimize memory allocations. + + +*Performance tip*: +When reading and writing to a file or a network connection, you may get better performance by +wrapping your streams with `bufio` instances. + +E.g., +```Go + f, err := os.Create("myfile") + w := bufio.NewWriter(f) +``` +```Go + f, err := os.Open("myfile") + r := bufio.NewReader(f) +``` + +## Memory Usage + +The memory usage of a bitset using `N` bits is at least `N/8` bytes. The number of bits in a bitset is at least as large as one plus the greatest bit index you have accessed. Thus it is possible to run out of memory while using a bitset. If you have lots of bits, you might prefer compressed bitsets, like the [Roaring bitmaps](https://roaringbitmap.org) and its [Go implementation](https://github.com/RoaringBitmap/roaring). + +The `roaring` library allows you to go back and forth between compressed Roaring bitmaps and the conventional bitset instances: +```Go + mybitset := roaringbitmap.ToBitSet() + newroaringbitmap := roaring.FromBitSet(mybitset) +``` + + +### Goroutine safety + +In general, it's not safe to access the same BitSet using different goroutines--they are unsynchronized for performance. + +Should you want to access a BitSet from more than one goroutine, you should provide synchronization. Typically this is done by using channels to pass the *BitSet around (in Go style; so there is only ever one owner), or by using `sync.Mutex` to serialize operations on BitSets. + +## Installation + +```bash +go get github.com/bits-and-blooms/bitset +``` + +## Contributing + +If you wish to contribute to this project, please branch and issue a pull request against master ("[GitHub Flow](https://guides.github.com/introduction/flow/)") + +## Running all tests + +Before committing the code, please check if it passes tests, has adequate coverage, etc. +```bash +go test +go test -cover +``` diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..f888420c3ba52393f7e3c09111952c2d128facd3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +You can report privately a vulnerability by email at daniel@lemire.me (current maintainer). diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/azure-pipelines.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9b295918404f10aa91f0c95760a8454f615b741 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/azure-pipelines.yml @@ -0,0 +1,39 @@ +# Go +# Build your Go project. +# Add steps that test, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/go + +trigger: +- master + +pool: + vmImage: 'Ubuntu-16.04' + +variables: + GOBIN: '$(GOPATH)/bin' # Go binaries path + GOROOT: '/usr/local/go1.11' # Go installation path + GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path + modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code + +steps: +- script: | + mkdir -p '$(GOBIN)' + mkdir -p '$(GOPATH)/pkg' + mkdir -p '$(modulePath)' + shopt -s extglob + shopt -s dotglob + mv !(gopath) '$(modulePath)' + echo '##vso[task.prependpath]$(GOBIN)' + echo '##vso[task.prependpath]$(GOROOT)/bin' + displayName: 'Set up the Go workspace' + +- script: | + go version + go get -v -t -d ./... + if [ -f Gopkg.toml ]; then + curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + dep ensure + fi + go build -v . + workingDirectory: '$(modulePath)' + displayName: 'Get dependencies, then build' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/bitset.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/bitset.go new file mode 100644 index 0000000000000000000000000000000000000000..217f2d86b6cdab4e622136f27a030f464713b406 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/bitset.go @@ -0,0 +1,1750 @@ +/* +Package bitset implements bitsets, a mapping +between non-negative integers and boolean values. It should be more +efficient than map[uint] bool. + +It provides methods for setting, clearing, flipping, and testing +individual integers. + +But it also provides set intersection, union, difference, +complement, and symmetric operations, as well as tests to +check whether any, all, or no bits are set, and querying a +bitset's current length and number of positive bits. + +BitSets are expanded to the size of the largest set bit; the +memory allocation is approximately Max bits, where Max is +the largest set bit. BitSets are never shrunk. On creation, +a hint can be given for the number of bits that will be used. + +Many of the methods, including Set,Clear, and Flip, return +a BitSet pointer, which allows for chaining. + +Example use: + + import "bitset" + var b BitSet + b.Set(10).Set(11) + if b.Test(1000) { + b.Clear(1000) + } + if B.Intersection(bitset.New(100).Set(10)).Count() > 1 { + fmt.Println("Intersection works.") + } + +As an alternative to BitSets, one should check out the 'big' package, +which provides a (less set-theoretical) view of bitsets. +*/ +package bitset + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math/bits" + "strconv" +) + +// the wordSize of a bit set +const wordSize = 64 + +// the wordSize of a bit set in bytes +const wordBytes = wordSize / 8 + +// wordMask is wordSize-1, used for bit indexing in a word +const wordMask = wordSize - 1 + +// log2WordSize is lg(wordSize) +const log2WordSize = 6 + +// allBits has every bit set +const allBits uint64 = 0xffffffffffffffff + +// default binary BigEndian +var binaryOrder binary.ByteOrder = binary.BigEndian + +// default json encoding base64.URLEncoding +var base64Encoding = base64.URLEncoding + +// Base64StdEncoding Marshal/Unmarshal BitSet with base64.StdEncoding(Default: base64.URLEncoding) +func Base64StdEncoding() { base64Encoding = base64.StdEncoding } + +// LittleEndian sets Marshal/Unmarshal Binary as Little Endian (Default: binary.BigEndian) +func LittleEndian() { binaryOrder = binary.LittleEndian } + +// BigEndian sets Marshal/Unmarshal Binary as Big Endian (Default: binary.BigEndian) +func BigEndian() { binaryOrder = binary.BigEndian } + +// BinaryOrder returns the current binary order, see also LittleEndian() +// and BigEndian() to change the order. +func BinaryOrder() binary.ByteOrder { return binaryOrder } + +// A BitSet is a set of bits. The zero value of a BitSet is an empty set of length 0. +type BitSet struct { + length uint + set []uint64 +} + +// Error is used to distinguish errors (panics) generated in this package. +type Error string + +// safeSet will fixup b.set to be non-nil and return the field value +func (b *BitSet) safeSet() []uint64 { + if b.set == nil { + b.set = make([]uint64, wordsNeeded(0)) + } + return b.set +} + +// SetBitsetFrom fills the bitset with an array of integers without creating a new BitSet instance +func (b *BitSet) SetBitsetFrom(buf []uint64) { + b.length = uint(len(buf)) * 64 + b.set = buf +} + +// From is a constructor used to create a BitSet from an array of words +func From(buf []uint64) *BitSet { + return FromWithLength(uint(len(buf))*64, buf) +} + +// FromWithLength constructs from an array of words and length in bits. +// This function is for advanced users, most users should prefer +// the From function. +// As a user of FromWithLength, you are responsible for ensuring +// that the length is correct: your slice should have length at +// least (length+63)/64 in 64-bit words. +func FromWithLength(length uint, set []uint64) *BitSet { + if len(set) < wordsNeeded(length) { + panic("BitSet.FromWithLength: slice is too short") + } + return &BitSet{length, set} +} + +// Bytes returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +// +// Deprecated: Bytes is deprecated. Use [BitSet.Words] instead. +func (b *BitSet) Bytes() []uint64 { + return b.set +} + +// Words returns the bitset as array of 64-bit words, giving direct access to the internal representation. +// It is not a copy, so changes to the returned slice will affect the bitset. +// It is meant for advanced users. +func (b *BitSet) Words() []uint64 { + return b.set +} + +// wordsNeeded calculates the number of words needed for i bits +func wordsNeeded(i uint) int { + if i > (Cap() - wordMask) { + return int(Cap() >> log2WordSize) + } + return int((i + wordMask) >> log2WordSize) +} + +// wordsNeededUnbound calculates the number of words needed for i bits, possibly exceeding the capacity. +// This function is useful if you know that the capacity cannot be exceeded (e.g., you have an existing BitSet). +func wordsNeededUnbound(i uint) int { + return (int(i) + wordMask) >> log2WordSize +} + +// wordsIndex calculates the index of words in a `uint64` +func wordsIndex(i uint) uint { + return i & wordMask +} + +// New creates a new BitSet with a hint that length bits will be required. +// The memory usage is at least length/8 bytes. +// In case of allocation failure, the function will return a BitSet with zero +// capacity. +func New(length uint) (bset *BitSet) { + defer func() { + if r := recover(); r != nil { + bset = &BitSet{ + 0, + make([]uint64, 0), + } + } + }() + + bset = &BitSet{ + length, + make([]uint64, wordsNeeded(length)), + } + + return bset +} + +// MustNew creates a new BitSet with the given length bits. +// It panics if length exceeds the possible capacity or by a lack of memory. +func MustNew(length uint) (bset *BitSet) { + if length >= Cap() { + panic("You are exceeding the capacity") + } + + return &BitSet{ + length, + make([]uint64, wordsNeeded(length)), // may panic on lack of memory + } +} + +// Cap returns the total possible capacity, or number of bits +// that can be stored in the BitSet theoretically. Under 32-bit system, +// it is 4294967295 and under 64-bit system, it is 18446744073709551615. +// Note that this is further limited by the maximum allocation size in Go, +// and your available memory, as any Go data structure. +func Cap() uint { + return ^uint(0) +} + +// Len returns the number of bits in the BitSet. +// Note that it differ from Count function. +func (b *BitSet) Len() uint { + return b.length +} + +// extendSet adds additional words to incorporate new bits if needed +func (b *BitSet) extendSet(i uint) { + if i >= Cap() { + panic("You are exceeding the capacity") + } + nsize := wordsNeeded(i + 1) + if b.set == nil { + b.set = make([]uint64, nsize) + } else if cap(b.set) >= nsize { + b.set = b.set[:nsize] // fast resize + } else if len(b.set) < nsize { + newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x + copy(newset, b.set) + b.set = newset + } + b.length = i + 1 +} + +// Test whether bit i is set. +func (b *BitSet) Test(i uint) bool { + if i >= b.length { + return false + } + return b.set[i>>log2WordSize]&(1<> log2WordSize) + subWordIndex := wordsIndex(i) + + // The word that the index falls within, shifted so the index is at bit 0 + var firstWord, secondWord uint64 + if firstWordIndex < len(b.set) { + firstWord = b.set[firstWordIndex] >> subWordIndex + } + + // The next word, masked to only include the necessary bits and shifted to cover the + // top of the word + if (firstWordIndex + 1) < len(b.set) { + secondWord = b.set[firstWordIndex+1] << uint64(wordSize-subWordIndex) + } + + return firstWord | secondWord +} + +// Set bit i to 1, the capacity of the bitset is automatically +// increased accordingly. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +// The memory usage is at least slightly over i/8 bytes. +func (b *BitSet) Set(i uint) *BitSet { + if i >= b.length { // if we need more bits, make 'em + b.extendSet(i) + } + b.set[i>>log2WordSize] |= 1 << wordsIndex(i) + return b +} + +// Clear bit i to 0. This never cause a memory allocation. It is always safe. +func (b *BitSet) Clear(i uint) *BitSet { + if i >= b.length { + return b + } + b.set[i>>log2WordSize] &^= 1 << wordsIndex(i) + return b +} + +// SetTo sets bit i to value. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) SetTo(i uint, value bool) *BitSet { + if value { + return b.Set(i) + } + return b.Clear(i) +} + +// Flip bit at i. +// Warning: using a very large value for 'i' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) Flip(i uint) *BitSet { + if i >= b.length { + return b.Set(i) + } + b.set[i>>log2WordSize] ^= 1 << wordsIndex(i) + return b +} + +// FlipRange bit in [start, end). +// Warning: using a very large value for 'end' +// may lead to a memory shortage and a panic: the caller is responsible +// for providing sensible parameters in line with their memory capacity. +func (b *BitSet) FlipRange(start, end uint) *BitSet { + if start >= end { + return b + } + + if end-1 >= b.length { // if we need more bits, make 'em + b.extendSet(end - 1) + } + + startWord := int(start >> log2WordSize) + endWord := int(end >> log2WordSize) + + // b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + // e.g: + // start = 71, + // startWord = 1 + // wordsIndex(start) = 71 % 64 = 7 + // (^uint64(0) << 7) = 0b111111....11110000000 + // + // mask = ^(^uint64(0) << 7) = 0b000000....00001111111 + // + // flips the first 7 bits in b.set[1] and + // in the range loop, the b.set[1] gets again flipped + // so the two expressions flip results in a flip + // in b.set[1] from [7,63] + // + // handle startWord special, get's reflipped in range loop + b.set[startWord] ^= ^(^uint64(0) << wordsIndex(start)) + + for idx := range b.set[startWord:endWord] { + b.set[startWord+idx] = ^b.set[startWord+idx] + } + + // handle endWord special + // e.g. + // end = 135 + // endWord = 2 + // + // wordsIndex(-7) = 57 + // see the golang spec: + // "For unsigned integer values, the operations +, -, *, and << are computed + // modulo 2n, where n is the bit width of the unsigned integer's type." + // + // mask = ^uint64(0) >> 57 = 0b00000....0001111111 + // + // flips in b.set[2] from [0,7] + // + // is end at word boundary? + if idx := wordsIndex(-end); idx != 0 { + b.set[endWord] ^= ^uint64(0) >> wordsIndex(idx) + } + + return b +} + +// Shrink shrinks BitSet so that the provided value is the last possible +// set value. It clears all bits > the provided index and reduces the size +// and length of the set. +// +// Note that the parameter value is not the new length in bits: it is the +// maximal value that can be stored in the bitset after the function call. +// The new length in bits is the parameter value + 1. Thus it is not possible +// to use this function to set the length to 0, the minimal value of the length +// after this function call is 1. +// +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Shrink(lastbitindex uint) *BitSet { + length := lastbitindex + 1 + idx := wordsNeeded(length) + if idx > len(b.set) { + return b + } + shrunk := make([]uint64, idx) + copy(shrunk, b.set[:idx]) + b.set = shrunk + b.length = length + lastWordUsedBits := length % 64 + if lastWordUsedBits != 0 { + b.set[idx-1] &= allBits >> uint64(64-wordsIndex(lastWordUsedBits)) + } + return b +} + +// Compact shrinks BitSet to so that we preserve all set bits, while minimizing +// memory usage. Compact calls Shrink. +// A new slice is allocated to store the new bits, so you may see an increase in +// memory usage until the GC runs. Normally this should not be a problem, but if you +// have an extremely large BitSet its important to understand that the old BitSet will +// remain in memory until the GC frees it. +// If you are memory constrained, this function may cause a panic. +func (b *BitSet) Compact() *BitSet { + idx := len(b.set) - 1 + for ; idx >= 0 && b.set[idx] == 0; idx-- { + } + newlength := uint((idx + 1) << log2WordSize) + if newlength >= b.length { + return b // nothing to do + } + if newlength > 0 { + return b.Shrink(newlength - 1) + } + // We preserve one word + return b.Shrink(63) +} + +// InsertAt takes an index which indicates where a bit should be +// inserted. Then it shifts all the bits in the set to the left by 1, starting +// from the given index position, and sets the index position to 0. +// +// Depending on the size of your BitSet, and where you are inserting the new entry, +// this method could be extremely slow and in some cases might cause the entire BitSet +// to be recopied. +func (b *BitSet) InsertAt(idx uint) *BitSet { + insertAtElement := idx >> log2WordSize + + // if length of set is a multiple of wordSize we need to allocate more space first + if b.isLenExactMultiple() { + b.set = append(b.set, uint64(0)) + } + + var i uint + for i = uint(len(b.set) - 1); i > insertAtElement; i-- { + // all elements above the position where we want to insert can simply by shifted + b.set[i] <<= 1 + + // we take the most significant bit of the previous element and set it as + // the least significant bit of the current element + b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63 + } + + // generate a mask to extract the data that we need to shift left + // within the element where we insert a bit + dataMask := uint64(1)< 0x40000 { + buffer.WriteString("...") + break + } + buffer.WriteString(strconv.FormatInt(int64(i), 10)) + i, e = b.NextSet(i + 1) + if e { + buffer.WriteString(",") + } + } + buffer.WriteString("}") + return buffer.String() +} + +// DeleteAt deletes the bit at the given index position from +// within the bitset +// All the bits residing on the left of the deleted bit get +// shifted right by 1 +// The running time of this operation may potentially be +// relatively slow, O(length) +func (b *BitSet) DeleteAt(i uint) *BitSet { + // the index of the slice element where we'll delete a bit + deleteAtElement := i >> log2WordSize + + // generate a mask for the data that needs to be shifted right + // within that slice element that gets modified + dataMask := ^((uint64(1) << wordsIndex(i)) - 1) + + // extract the data that we'll shift right from the slice element + data := b.set[deleteAtElement] & dataMask + + // set the masked area to 0 while leaving the rest as it is + b.set[deleteAtElement] &= ^dataMask + + // shift the previously extracted data to the right and then + // set it in the previously masked area + b.set[deleteAtElement] |= (data >> 1) & dataMask + + // loop over all the consecutive slice elements to copy each + // lowest bit into the highest position of the previous element, + // then shift the entire content to the right by 1 + for i := int(deleteAtElement) + 1; i < len(b.set); i++ { + b.set[i-1] |= (b.set[i] & 1) << 63 + b.set[i] >>= 1 + } + + b.length = b.length - 1 + + return b +} + +// AppendTo appends all set bits to buf and returns the (maybe extended) buf. +// In case of allocation failure, the function will panic. +// +// See also [BitSet.AsSlice] and [BitSet.NextSetMany]. +func (b *BitSet) AppendTo(buf []uint) []uint { + // In theory, we could overflow uint, but in practice, we will not. + for idx, word := range b.set { + for word != 0 { + // In theory idx<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is set + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + if word != 0 { + return uint((x+idx)< 0; j, buffer = bitmap.NextSetMany(j,buffer) { +// for k := range buffer { +// do something with buffer[k] +// } +// j += 1 +// } +// +// It is possible to retrieve all set bits as follow: +// +// indices := make([]uint, bitmap.Count()) +// bitmap.NextSetMany(0, indices) +// +// It is also possible to retrieve all set bits with [BitSet.AppendTo] +// or [BitSet.AsSlice]. +// +// However if Count() is large, it might be preferable to +// use several calls to NextSetMany for memory reasons. +func (b *BitSet) NextSetMany(i uint, buffer []uint) (uint, []uint) { + // In theory, we could overflow uint, but in practice, we will not. + capacity := cap(buffer) + result := buffer[:capacity] + + x := int(i >> log2WordSize) + if x >= len(b.set) || capacity == 0 { + return 0, result[:0] + } + + // process first (partial) word + word := b.set[x] >> wordsIndex(i) + + size := 0 + for word != 0 { + result[size] = i + uint(bits.TrailingZeros64(word)) + + size++ + if size == capacity { + return result[size-1], result[:size] + } + + // clear the rightmost set bit + word &= word - 1 + } + + // process the following full words + // x < len(b.set), no out-of-bounds panic in following slice expression + x++ + for idx, word := range b.set[x:] { + for word != 0 { + result[size] = uint((x+idx)< 0 { + return result[size-1], result[:size] + } + return 0, result[:0] +} + +// NextClear returns the next clear bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are set) +func (b *BitSet) NextClear(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return i, true // All bits beyond the end of the set are implicitly clear + } + + // process first (partial) word + word := ^b.set[x] >> wordsIndex(i) // Invert the word to find clear bits + if word != 0 { + return i + uint(bits.TrailingZeros64(word)), true + } + + // process the following full words until next bit is clear + x++ + for ; x < len(b.set); x++ { + word = ^b.set[x] // Invert the word to find clear bits + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + if word != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + word := b.set[x] + + // Flip all bits and find the highest one bit + word = ^word + + // Clear the bits above the index + word = word & ((1 << (wordsIndex(i) + 1)) - 1) + + if word != 0 { + return uint(x<= 0; x-- { + word = b.set[x] + word = ^word + if word != 0 { + return uint(x< b.wordCount() { + l = b.wordCount() + } + for i := 0; i < l; i++ { + result.set[i] = b.set[i] &^ compare.set[i] + } + return +} + +// DifferenceCardinality computes the cardinality of the difference +func (b *BitSet) DifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + cnt := uint64(0) + cnt += popcntMaskSlice(b.set[:l], compare.set[:l]) + cnt += popcntSlice(b.set[l:]) + return uint(cnt) +} + +// InPlaceDifference computes the difference of base set and other set +// This is the BitSet equivalent of &^ (and not) +func (b *BitSet) InPlaceDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l <= 0 { + return + } + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] &^= cmpData[i] + } +} + +// Convenience function: return two bitsets ordered by +// increasing length. Note: neither can be nil +func sortByLength(a *BitSet, b *BitSet) (ap *BitSet, bp *BitSet) { + if a.length <= b.length { + ap, bp = a, b + } else { + ap, bp = b, a + } + return +} + +// Intersection of base set and other set +// This is the BitSet equivalent of & (and) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Intersection(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = New(b.length) + for i, word := range b.set { + result.set[i] = word & compare.set[i] + } + return +} + +// IntersectionCardinality computes the cardinality of the intersection +func (b *BitSet) IntersectionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntAndSlice(b.set, compare.set) + return uint(cnt) +} + +// InPlaceIntersection destructively computes the intersection of +// base set and the compare set. +// This is the BitSet equivalent of & (and) +func (b *BitSet) InPlaceIntersection(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] &= cmpData[i] + } + } + if l >= 0 { + for i := l; i < len(b.set); i++ { + b.set[i] = 0 + } + } + if compare.length > 0 { + if compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + } +} + +// Union of base set and other set +// This is the BitSet equivalent of | (or) +func (b *BitSet) Union(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word | compare.set[i] + } + return +} + +// UnionCardinality computes the cardinality of the uniton of the base set +// and the compare set. +func (b *BitSet) UnionCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntOrSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceUnion creates the destructive union of base set and compare set. +// This is the BitSet equivalent of | (or). +func (b *BitSet) InPlaceUnion(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + + for i := 0; i < l; i++ { + data[i] |= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) SymmetricDifference(compare *BitSet) (result *BitSet) { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + // compare is bigger, so clone it + result = compare.Clone() + for i, word := range b.set { + result.set[i] = word ^ compare.set[i] + } + return +} + +// SymmetricDifferenceCardinality computes the cardinality of the symmetric difference +func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint { + panicIfNull(b) + panicIfNull(compare) + b, compare = sortByLength(b, compare) + cnt := popcntXorSlice(b.set, compare.set) + if len(compare.set) > len(b.set) { + cnt += popcntSlice(compare.set[len(b.set):]) + } + return uint(cnt) +} + +// InPlaceSymmetricDifference creates the destructive SymmetricDifference of base set and other set +// This is the BitSet equivalent of ^ (xor) +func (b *BitSet) InPlaceSymmetricDifference(compare *BitSet) { + panicIfNull(b) + panicIfNull(compare) + l := compare.wordCount() + if l > b.wordCount() { + l = b.wordCount() + } + if compare.length > 0 && compare.length-1 >= b.length { + b.extendSet(compare.length - 1) + } + if l > 0 { + // bounds check elimination + data, cmpData := b.set, compare.set + _ = data[l-1] + _ = cmpData[l-1] + for i := 0; i < l; i++ { + data[i] ^= cmpData[i] + } + } + if len(compare.set) > l { + for i := l; i < len(compare.set); i++ { + b.set[i] = compare.set[i] + } + } +} + +// Is the length an exact multiple of word sizes? +func (b *BitSet) isLenExactMultiple() bool { + return wordsIndex(b.length) == 0 +} + +// Clean last word by setting unused bits to 0 +func (b *BitSet) cleanLastWord() { + if !b.isLenExactMultiple() { + b.set[len(b.set)-1] &= allBits >> (wordSize - wordsIndex(b.length)) + } +} + +// Complement computes the (local) complement of a bitset (up to length bits) +// In case of allocation failure, the function will return an empty BitSet. +func (b *BitSet) Complement() (result *BitSet) { + panicIfNull(b) + result = New(b.length) + for i, word := range b.set { + result.set[i] = ^word + } + result.cleanLastWord() + return +} + +// All returns true if all bits are set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) All() bool { + panicIfNull(b) + return b.Count() == b.length +} + +// None returns true if no bit is set, false otherwise. Returns true for +// empty sets. +func (b *BitSet) None() bool { + panicIfNull(b) + if b != nil && b.set != nil { + for _, word := range b.set { + if word > 0 { + return false + } + } + } + return true +} + +// Any returns true if any bit is set, false otherwise +func (b *BitSet) Any() bool { + panicIfNull(b) + return !b.None() +} + +// IsSuperSet returns true if this is a superset of the other set +func (b *BitSet) IsSuperSet(other *BitSet) bool { + l := other.wordCount() + if b.wordCount() < l { + l = b.wordCount() + } + for i, word := range other.set[:l] { + if b.set[i]&word != word { + return false + } + } + return popcntSlice(other.set[l:]) == 0 +} + +// IsStrictSuperSet returns true if this is a strict superset of the other set +func (b *BitSet) IsStrictSuperSet(other *BitSet) bool { + return b.Count() > other.Count() && b.IsSuperSet(other) +} + +// DumpAsBits dumps a bit set as a string of bits. Following the usual convention in Go, +// the least significant bits are printed last (index 0 is at the end of the string). +// This is useful for debugging and testing. It is not suitable for serialization. +func (b *BitSet) DumpAsBits() string { + if b.set == nil { + return "." + } + buffer := bytes.NewBufferString("") + i := len(b.set) - 1 + for ; i >= 0; i-- { + fmt.Fprintf(buffer, "%064b.", b.set[i]) + } + return buffer.String() +} + +// BinaryStorageSize returns the binary storage requirements (see WriteTo) in bytes. +func (b *BitSet) BinaryStorageSize() int { + return wordBytes + wordBytes*b.wordCount() +} + +func readUint64Array(reader io.Reader, data []uint64) error { + length := len(data) + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < length; i += bufferSize { + end := i + bufferSize + if end > length { + end = length + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + if _, err := io.ReadFull(reader, buffer); err != nil { + return err + } + for i := range chunk { + chunk[i] = uint64(binaryOrder.Uint64(buffer[8*i:])) + } + } + return nil +} + +func writeUint64Array(writer io.Writer, data []uint64) error { + bufferSize := 128 + buffer := make([]byte, bufferSize*wordBytes) + for i := 0; i < len(data); i += bufferSize { + end := i + bufferSize + if end > len(data) { + end = len(data) + buffer = buffer[:wordBytes*(end-i)] + } + chunk := data[i:end] + for i, x := range chunk { + binaryOrder.PutUint64(buffer[8*i:], x) + } + _, err := writer.Write(buffer) + if err != nil { + return err + } + } + return nil +} + +// WriteTo writes a BitSet to a stream. The format is: +// 1. uint64 length +// 2. []uint64 set +// The length is the number of bits in the BitSet. +// +// The set is a slice of uint64s containing between length and length + 63 bits. +// It is interpreted as a big-endian array of uint64s by default (see BinaryOrder()) +// meaning that the first 8 bits are stored at byte index 7, the next 8 bits are stored +// at byte index 6... the bits 64 to 71 are stored at byte index 8, etc. +// If you change the binary order, you need to do so for both reading and writing. +// We recommend using the default binary order. +// +// Upon success, the number of bytes written is returned. +// +// Performance: if this function is used to write to a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Writer. +// E.g., +// +// f, err := os.Create("myfile") +// w := bufio.NewWriter(f) +func (b *BitSet) WriteTo(stream io.Writer) (int64, error) { + length := uint64(b.length) + // Write length + err := binary.Write(stream, binaryOrder, &length) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(0), err + } + err = writeUint64Array(stream, b.set[:b.wordCount()]) + if err != nil { + // Upon failure, we do not guarantee that we + // return the number of bytes written. + return int64(wordBytes), err + } + return int64(b.BinaryStorageSize()), nil +} + +// ReadFrom reads a BitSet from a stream written using WriteTo +// The format is: +// 1. uint64 length +// 2. []uint64 set +// See WriteTo for details. +// Upon success, the number of bytes read is returned. +// If the current BitSet is not large enough to hold the data, +// it is extended. In case of error, the BitSet is either +// left unchanged or made empty if the error occurs too late +// to preserve the content. +// +// Performance: if this function is used to read from a disk or network +// connection, it might be beneficial to wrap the stream in a bufio.Reader. +// E.g., +// +// f, err := os.Open("myfile") +// r := bufio.NewReader(f) +func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) { + var length uint64 + err := binary.Read(stream, binaryOrder, &length) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return 0, err + } + newlength := uint(length) + + if uint64(newlength) != length { + return 0, errors.New("unmarshalling error: type mismatch") + } + nWords := wordsNeeded(uint(newlength)) + if cap(b.set) >= nWords { + b.set = b.set[:nWords] + } else { + b.set = make([]uint64, nWords) + } + + b.length = newlength + + err = readUint64Array(stream, b.set) + if err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + // We do not want to leave the BitSet partially filled as + // it is error prone. + b.set = b.set[:0] + b.length = 0 + return 0, err + } + + return int64(b.BinaryStorageSize()), nil +} + +// MarshalBinary encodes a BitSet into a binary form and returns the result. +// Please see WriteTo for details. +func (b *BitSet) MarshalBinary() ([]byte, error) { + var buf bytes.Buffer + _, err := b.WriteTo(&buf) + if err != nil { + return []byte{}, err + } + + return buf.Bytes(), err +} + +// UnmarshalBinary decodes the binary form generated by MarshalBinary. +// Please see WriteTo for details. +func (b *BitSet) UnmarshalBinary(data []byte) error { + buf := bytes.NewReader(data) + _, err := b.ReadFrom(buf) + return err +} + +// MarshalJSON marshals a BitSet as a JSON structure +func (b BitSet) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) + _, err := b.WriteTo(buffer) + if err != nil { + return nil, err + } + + // URLEncode all bytes + return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes())) +} + +// UnmarshalJSON unmarshals a BitSet from JSON created using MarshalJSON +func (b *BitSet) UnmarshalJSON(data []byte) error { + // Unmarshal as string + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return err + } + + // URLDecode string + buf, err := base64Encoding.DecodeString(s) + if err != nil { + return err + } + + _, err = b.ReadFrom(bytes.NewReader(buf)) + return err +} + +// Rank returns the number of set bits up to and including the index +// that are set in the bitset. +// See https://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics +func (b *BitSet) Rank(index uint) (rank uint) { + index++ // Rank is up to and including + + // needed more than once + length := len(b.set) + + // TODO: built-in min requires go1.21 or later + // idx := min(int(index>>6), len(b.set)) + idx := int(index >> 6) + if idx > length { + idx = length + } + + // sum up the popcounts until idx ... + // TODO: cannot range over idx (...): requires go1.22 or later + // for j := range idx { + for j := 0; j < idx; j++ { + if w := b.set[j]; w != 0 { + rank += uint(bits.OnesCount64(w)) + } + } + + // ... plus partial word at idx, + // make Rank inlineable and faster in the end + // don't test index&63 != 0, just add, less branching + if idx < length { + rank += uint(bits.OnesCount64(b.set[idx] << (64 - index&63))) + } + + return +} + +// Select returns the index of the jth set bit, where j is the argument. +// The caller is responsible to ensure that 0 <= j < Count(): when j is +// out of range, the function returns the length of the bitset (b.length). +// +// Note that this function differs in convention from the Rank function which +// returns 1 when ranking the smallest value. We follow the conventional +// textbook definition of Select and Rank. +func (b *BitSet) Select(index uint) uint { + leftover := index + for idx, word := range b.set { + w := uint(bits.OnesCount64(word)) + if w > leftover { + return uint(idx)*64 + select64(word, leftover) + } + leftover -= w + } + return b.length +} + +// top detects the top bit set +func (b *BitSet) top() (uint, bool) { + for idx := len(b.set) - 1; idx >= 0; idx-- { + if word := b.set[idx]; word != 0 { + return uint(idx<= b.length { + b.length = top + bits + 1 + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just add pages + copy(dst[pages:nsize], b.set) + } else { + if pad+shift >= wordSize { + dst[idx+pages+1] = b.set[idx] >> (wordSize - shift) + } + + for i := int(idx); i >= 0; i-- { + if i > 0 { + dst[i+int(pages)] = (b.set[i] << shift) | (b.set[i-1] >> (wordSize - shift)) + } else { + dst[i+int(pages)] = b.set[i] << shift + } + } + } + + // zeroing extra pages + for i := 0; i < int(pages); i++ { + dst[i] = 0 + } + + b.set = dst +} + +// ShiftRight shifts the bitset like >> operation would do. +func (b *BitSet) ShiftRight(bits uint) { + panicIfNull(b) + + if bits == 0 { + return + } + + top, ok := b.top() + if !ok { + return + } + + if bits >= top { + b.set = make([]uint64, wordsNeeded(b.length)) + return + } + + pad, idx := top%wordSize, top>>log2WordSize + shift, pages := bits%wordSize, bits>>log2WordSize + if bits%wordSize == 0 { // happy case: just clear pages + b.set = b.set[pages:] + b.length -= pages * wordSize + } else { + for i := 0; i <= int(idx-pages); i++ { + if i < int(idx-pages) { + b.set[i] = (b.set[i+int(pages)] >> shift) | (b.set[i+int(pages)+1] << (wordSize - shift)) + } else { + b.set[i] = b.set[i+int(pages)] >> shift + } + } + + if pad < shift { + b.set[int(idx-pages)] = 0 + } + } + + for i := int(idx-pages) + 1; i <= int(idx); i++ { + b.set[i] = 0 + } +} + +// OnesBetween returns the number of set bits in the range [from, to). +// The range is inclusive of 'from' and exclusive of 'to'. +// Returns 0 if from >= to. +func (b *BitSet) OnesBetween(from, to uint) uint { + panicIfNull(b) + + if from >= to { + return 0 + } + + // Calculate indices and masks for the starting and ending words + startWord := from >> log2WordSize // Divide by wordSize + endWord := to >> log2WordSize + startOffset := from & wordMask // Mod wordSize + endOffset := to & wordMask + + // Case 1: Bits lie within a single word + if startWord == endWord { + // Create mask for bits between from and to + mask := uint64((1<= startOffset + count = uint(bits.OnesCount64(b.set[startWord] & startMask)) + + // 2b: Count all bits in complete words between start and end + if endWord > startWord+1 { + count += uint(popcntSlice(b.set[startWord+1 : endWord])) + } + + // 2c: Count bits in last word (from start of word to endOffset) + if endOffset > 0 { + endMask := uint64(1<> log2WordSize + bitOffset := outPos & wordMask + + // Write extracted bits, handling word boundary crossing + dst.set[wordIdx] |= extracted << bitOffset + if bitOffset+bitsExtracted > wordSize { + dst.set[wordIdx+1] = extracted >> (wordSize - bitOffset) + } + + outPos += bitsExtracted + } +} + +// Deposit creates a new BitSet and deposits bits according to a mask. +// See DepositTo for details. +func (b *BitSet) Deposit(mask *BitSet) *BitSet { + dst := New(mask.length) + b.DepositTo(mask, dst) + return dst +} + +// DepositTo spreads bits from a compacted form in the BitSet into positions +// specified by mask in dst. This is the inverse operation of Extract. +// +// For example, if mask has bits set at positions 1,4,5, then DepositTo will +// take consecutive bits 0,1,2 from the source BitSet and place them into +// positions 1,4,5 in the destination BitSet. +func (b *BitSet) DepositTo(mask *BitSet, dst *BitSet) { + panicIfNull(b) + panicIfNull(mask) + panicIfNull(dst) + + if len(dst.set) == 0 || len(mask.set) == 0 || len(b.set) == 0 { + return + } + + inPos := uint(0) + length := len(mask.set) + if len(dst.set) < length { + length = len(dst.set) + } + + // Process each word + for i := 0; i < length; i++ { + if mask.set[i] == 0 { + continue // Skip words with no bits to deposit + } + + // Calculate source word index + wordIdx := inPos >> log2WordSize + if wordIdx >= uint(len(b.set)) { + break // No more source bits available + } + + // Get source bits, handling word boundary crossing + sourceBits := b.set[wordIdx] + bitOffset := inPos & wordMask + if wordIdx+1 < uint(len(b.set)) && bitOffset != 0 { + // Combine bits from current and next word + sourceBits = (sourceBits >> bitOffset) | + (b.set[wordIdx+1] << (wordSize - bitOffset)) + } else { + sourceBits >>= bitOffset + } + + // Deposit bits according to mask + dst.set[i] = (dst.set[i] &^ mask.set[i]) | pdep(sourceBits, mask.set[i]) + inPos += uint(bits.OnesCount64(mask.set[i])) + } +} + +//go:generate go run cmd/pextgen/main.go -pkg=bitset + +func pext(w, m uint64) (result uint64) { + var outPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + b := uint8(w >> shift) + mask := uint8(m >> shift) + + extracted := pextLUT[b][mask] + bits := popLUT[mask] + + result |= uint64(extracted) << outPos + outPos += uint(bits) + } + + return result +} + +func pdep(w, m uint64) (result uint64) { + var inPos uint + + // Process byte by byte + for i := 0; i < 8; i++ { + shift := i << 3 // i * 8 using bit shift + mask := uint8(m >> shift) + bits := popLUT[mask] + + // Get the bits we'll deposit from the source + b := uint8(w >> inPos) + + // Deposit them according to the mask for this byte + deposited := pdepLUT[b][mask] + + // Add to result + result |= uint64(deposited) << shift + inPos += uint(bits) + } + + return result +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/bitset_iter.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/bitset_iter.go new file mode 100644 index 0000000000000000000000000000000000000000..79bf8a0182ce21cd7e62ecabcea5194a2c134762 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/environment/source/bitset_iter.go @@ -0,0 +1,23 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "iter" + "math/bits" +) + +func (b *BitSet) EachSet() iter.Seq[uint] { + return func(yield func(uint) bool) { + for wordIndex, word := range b.set { + idx := 0 + for trail := bits.TrailingZeros64(word); trail != 64; trail = bits.TrailingZeros64(word >> idx) { + if !yield(uint(wordIndex<> 32 + seen += 32 + j -= n + } + ww := part + + // Divide 32bit + part = ww & 0xFFFF + + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 16 + seen += 16 + j -= n + } + ww = part + + // Divide 16bit + part = ww & 0xFF + n = uint(bits.OnesCount64(part)) + if n <= j { + part = ww >> 8 + seen += 8 + j -= n + } + ww = part + + // Lookup in final byte + counter := 0 + for ; counter < 8; counter++ { + j -= uint((ww >> counter) & 1) + if j+1 == 0 { + break + } + } + return uint(seen + counter) +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/instruction.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6232345f7a2d13f3bfa59de25bd02904bdf12377 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/instruction.md @@ -0,0 +1,32 @@ +NextClear returns incorrect results for bitsets with all bits set + +#### Description + +When calling `NextClear` on a bitset where all bits are set, the function returns unexpected values instead of properly indicating that no clear bits exist within the bitset bounds. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/bits-and-blooms/bitset" +) + +func main() { + // Create a bitset and set all bits + bs := bitset.New(100) + bs.SetAll() + + // Try to find the next clear bit starting from position 0 + pos, found := bs.NextClear(0) + fmt.Printf("NextClear(0): pos=%d, found=%t\n", pos, found) + + // Expected: should find no clear bits within the bitset bounds + // Actual: returns unexpected position values +} +``` + +The issue occurs when searching for clear bits in a fully set bitset - the function should properly handle the case where no clear bits exist within the defined length of the bitset. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/provenance.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..9137e6e6a63581555c6c1f647bbe87a10ffff420 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/provenance.json @@ -0,0 +1,238 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "bitset_benchmark_test.go": { + "mode": "0o644", + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad", + "size": 15273 + }, + "bitset_iter_test.go": { + "mode": "0o644", + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3", + "size": 1483 + }, + "bitset_test.go": { + "mode": "0o644", + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f", + "size": 68283 + }, + "popcnt_test.go": { + "mode": "0o644", + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5", + "size": 1312 + } + }, + "public_files": { + ".github/FUNDING.yml": { + "mode": "0o644", + "sha256": "00c2ce055f1bb49c71ff95cfe4b03e61bbe458e72fd08264f956a4a9f08352c2", + "size": 292 + }, + ".github/SECURITY.md": { + "mode": "0o644", + "sha256": "625015bf5fbff4495115fbce18a8cf38d2d6bdb7cb15b9197f8d6f82c0710215", + "size": 885 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "01fcc43b305d562d8b9e315d1279ff28601af10bd349f778c6234050b3306313", + "size": 510 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "299d9f593f6bc092a21b514fa18a3eeab05a35c24fe0d22dbf4189b5df3996cc", + "size": 274 + }, + ".travis.yml": { + "mode": "0o644", + "sha256": "864ad720e4757601f643ab7d4beef8bd63198550c18056225def54cf658b175b", + "size": 663 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "size": 1480 + }, + "README.md": { + "mode": "0o644", + "sha256": "5c96bc6128649a48b97d0985eed44a9a09f6fde619e67b0751dfbf775a488f9b", + "size": 5189 + }, + "SECURITY.md": { + "mode": "0o644", + "sha256": "385a66054ea24984ce518078150d30f9e56647c69636075fab4e2c14044c58fd", + "size": 141 + }, + "azure-pipelines.yml": { + "mode": "0o644", + "sha256": "27022db62e79be1325231876ccb0960089a4449676d6e7667efde4a89cd6d216", + "size": 1088 + }, + "bitset.go": { + "mode": "0o644", + "sha256": "0ccc20bfa82d53e442ae1b92c21b968ac88e0f8b4c0349a5ce0d58d5f8aed460", + "size": 47833 + }, + "bitset_iter.go": { + "mode": "0o644", + "sha256": "11025b610c891c267a9116c418ef98ab5aecd72d681e49423dac60312d414750", + "size": 433 + }, + "cmd/pextgen/main.go": { + "mode": "0o644", + "sha256": "4f1f617e9666310a81f1ad9a984cd647de5b95c486574401797d376648bd5a63", + "size": 3016 + }, + "go.mod": { + "mode": "0o644", + "sha256": "e1d76f51cb52ad77a366c14e391f29ff1adba192135a9a4cbeca5e87ad7e41fd", + "size": 50 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "pext.gen.go": { + "mode": "0o644", + "sha256": "9724417f2842ce796ada58e2977eaf94447b16d4270a81daef99c630eabbe7b5", + "size": 504581 + }, + "popcnt.go": { + "mode": "0o644", + "sha256": "e2f45369cc4efecf44f2d9de1390459070ee7ac8e6dc4f8d9b18716732e00c58", + "size": 774 + }, + "select.go": { + "mode": "0o644", + "sha256": "01cc0f9ccc46ac016aa66cf636c08e73ec66984a1fce0af387200f06f2670854", + "size": 672 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5", + "os": "linux", + "sha256": "075017381224f6b8c124cc719b149e4aef030c7b185791efa9900bce59b796d5" + }, + "context_inventory_sha256": "5f2166c2434be302e821854d07eaa87013733b4a4390ca9cf636f23089360fc2", + "image": "registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "ee6e7b6a6436765517535d98499b1d9beede9ecd36def3f01ab114ee288aa839", + "receipt_path": "production/runtime-images-v1/resolutions/a91d078628985ab5/resolution.json", + "receipt_sha256": "d0541a43df1317bcf696ecdf61d064bc4cd6e9c68939405b75338cc3461e682f", + "registry_digest": "sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9", + "source_image": "docker.io/swebench/swesmith.x86_64.bits-and-blooms_1776_bitset.167865a2@sha256:b3c4ae327314db15d65691bda0636ea78b9540e9625d0f75b5a552ffc08aa220", + "source_receipt_sha256": "5663d8b5da4fcf901110c25cf006213fca1146690da60fc79dd6d90bb7190fb9", + "space_commit": "351f5bffbc68c56840dd655d1df279ea7f7b33e0", + "space_id": "harness-hub/scale800-a91d078628985ab5-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "e1a252322aa677e40c430c2e8ba8a50e7e9393ca65a2cd75746dd5dd3088bb1b", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "b3ca83159c6cd0a7d259d106cb81314891def2de6e6e8702d8576e77cf8ea53d", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j", + "cloud_launch_ready": false, + "healthy_mirror_commit": "1e494d9e9cc3e999c9eb416740d40df437a4c821", + "instruction_sha256": "3986d2aac0e1dc93c433e5c2e23248e412344eac30b7d9dc7db16dd252656824", + "is_fork": true, + "learner_path": "tasks/6f45be200fc7870f853ed2b6/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "3ef376b769105f14098dd45e9d08ed3568c77d38ad33c470634606048e62119f", + "spdx": "BSD-3-Clause", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/bits-and-blooms__bitset.167865a2/8c45ea8823af0e70f8bfdb1e65e673ce40c39f07/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "167865a24c4956c76a987f0a7612f9ac04b93a82", + "patch_sha256": "211ddaca045bf27df9a353cf0f0e711ffd3223c654e90b29e3f320978d098f97", + "provenance_path": "tasks/6f45be200fc7870f853ed2b6/source-proof.json", + "repository_lineage": [ + "swesmith/bits-and-blooms__bitset.167865a2", + "bits-and-blooms/bitset" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "8c45ea8823af0e70f8bfdb1e65e673ce40c39f07", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "d26d2b23a428dc5c3d4e27cd677444fa2b7cd9b6", + "source_kind": "mutation", + "source_repo": "swesmith/bits-and-blooms__bitset.167865a2", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j", + "task_sha256": "d07d556c4cbde300dc467acafc8d76e2033d56a3a1777492f7aaeb48b7420e7a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "bits-and-blooms/bitset", + "usage": "quarantine_only" + }, + "source_row_sha256": "3fc36b8dc2f1e0b2cdcdf046dd2f96005b13eb9fa6723212ed2fa9e2a7352590", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/SECURITY.md", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.travis.yml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/SECURITY.md", + "/testbed/azure-pipelines.yml", + "/testbed/bitset.go", + "/testbed/bitset_iter.go", + "/testbed/cmd/pextgen/main.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/pext.gen.go", + "/testbed/popcnt.go", + "/testbed/select.go" + ] +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/solution/solve.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bba10541ab808b5b31e6e6fc8190b097ad98d0e4 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bitset.go": {"data": "LyoKUGFja2FnZSBiaXRzZXQgaW1wbGVtZW50cyBiaXRzZXRzLCBhIG1hcHBpbmcKYmV0d2VlbiBub24tbmVnYXRpdmUgaW50ZWdlcnMgYW5kIGJvb2xlYW4gdmFsdWVzLiBJdCBzaG91bGQgYmUgbW9yZQplZmZpY2llbnQgdGhhbiBtYXBbdWludF0gYm9vbC4KCkl0IHByb3ZpZGVzIG1ldGhvZHMgZm9yIHNldHRpbmcsIGNsZWFyaW5nLCBmbGlwcGluZywgYW5kIHRlc3RpbmcKaW5kaXZpZHVhbCBpbnRlZ2Vycy4KCkJ1dCBpdCBhbHNvIHByb3ZpZGVzIHNldCBpbnRlcnNlY3Rpb24sIHVuaW9uLCBkaWZmZXJlbmNlLApjb21wbGVtZW50LCBhbmQgc3ltbWV0cmljIG9wZXJhdGlvbnMsIGFzIHdlbGwgYXMgdG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2sgZm9yIHRoaXMgYnl0ZQoJCWRlcG9zaXRlZCA6PSBwZGVwTFVUW2JdW21hc2tdCgoJCS8vIEFkZCB0byByZXN1bHQKCQlyZXN1bHQgfD0gdWludDY0KGRlcG9zaXRlZCkgPDwgc2hpZnQKCQlpblBvcyArPSB1aW50KGJpdHMpCgl9CgoJcmV0dXJuIHJlc3VsdAp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/task.toml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4e466348be571e307f837ae423e7a2bf94e5c6a3 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/hat@sha256:b2ef67556c0a513cd2e1b524c2f52a73f08d1bb02caf59b94d317eaede3b4e21" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_benchmark_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_benchmark_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c1891879c9daa3eecac28a9dd1c458e9f0b7ca86 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_benchmark_test.go @@ -0,0 +1,676 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "fmt" + "math/bits" + "math/rand" + "testing" +) + +func BenchmarkSet(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Set(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkGetTest(b *testing.B) { + b.StopTimer() + r := rand.New(rand.NewSource(0)) + sz := 100000 + s := New(uint(sz)) + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Test(uint(r.Int31n(int32(sz)))) + } +} + +func BenchmarkSetExpand(b *testing.B) { + b.StopTimer() + sz := uint(100000) + b.StartTimer() + for i := 0; i < b.N; i++ { + var s BitSet + s.Set(sz) + } +} + +// go test -bench=Count +func BenchmarkCount(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + b.StartTimer() + for i := 0; i < b.N; i++ { + s.Count() + } +} + +// go test -bench=Iterate +func BenchmarkIterate(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=SparseIterate +func BenchmarkSparseIterate(b *testing.B) { + b.StopTimer() + s := New(100000) + for i := 0; i < 100000; i += 30 { + s.Set(uint(i)) + } + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} + +// go test -bench=BitsetOps +func BenchmarkBitsetOps(b *testing.B) { + // let's not write into s inside the benchmarks + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + cpy := s.Clone() + + b.Run("Equal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + s.Equal(cpy) + } + }) + + b.Run("FlipRange", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.FlipRange(0, 100000) + } + }) + + b.Run("NextSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextSet(0) + } + }) + + b.Run("NextClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.NextClear(0) + } + }) + + b.Run("PreviousSet", func(b *testing.B) { + s = New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousSet(99999) + } + }) + + b.Run("PreviousClear", func(b *testing.B) { + s = New(100000) + s.FlipRange(0, 100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.PreviousClear(99999) + } + }) + + b.Run("DifferenceCardinality", func(b *testing.B) { + empty := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.DifferenceCardinality(empty) + } + }) + + b.Run("InPlaceDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceDifference(cpy) + } + }) + + b.Run("InPlaceUnion", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceUnion(cpy) + } + }) + + b.Run("InPlaceIntersection", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceIntersection(cpy) + } + }) + + b.Run("InPlaceSymmetricDifference", func(b *testing.B) { + s = s.Clone() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.InPlaceSymmetricDifference(cpy) + } + }) +} + +// go test -bench=LemireCreate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCreate(b *testing.B) { + for i := 0; i < b.N; i++ { + bitmap := New(0) // we force dynamic memory allocation + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + } +} + +// go test -bench=LemireCount +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireCount(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + sum += bitmap.Count() + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterate +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterate(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=LemireIterateb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + sum += j + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +// go test -bench=BenchmarkLemireIterateManyb +// see https://lemire.me/blog/2016/09/22/swift-versus-java-the-bitset-performance-test/ +func BenchmarkLemireIterateManyb(b *testing.B) { + bitmap := New(100000000) + for v := uint(0); v <= 100000000; v += 100 { + bitmap.Set(v) + } + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func setRnd(bits []uint64, halfings int) { + rnd := rand.NewSource(0).(rand.Source64) + for i := range bits { + bits[i] = 0xFFFFFFFFFFFFFFFF + for j := 0; j < halfings; j++ { + bits[i] &= rnd.Uint64() + } + } +} + +// go test -bench=BenchmarkFlorianUekermannIterateMany +func BenchmarkFlorianUekermannIterateMany(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + last, batch := bitmap.NextSetMany(0, buffer) + for len(batch) > 0 { + for _, idx := range batch { + checksum += idx + } + last, batch = bitmap.NextSetMany(last+1, batch) + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannIterateManyReg(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +// function provided by FlorianUekermann +func good(set []uint64) (checksum uint) { + for wordIdx, word := range set { + wordIdx := uint(wordIdx * 64) + for word != 0 { + bitIdx := uint(bits.TrailingZeros64(word)) + word ^= 1 << bitIdx + index := wordIdx + bitIdx + checksum += index + } + } + return checksum +} + +func BenchmarkFlorianUekermannIterateManyComp(b *testing.B) { + input := make([]uint64, 68) + setRnd(input, 4) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannLowDensityIterateMany +func BenchmarkFlorianUekermannLowDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannLowDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 50000; i++ { + input[rnd.Uint64()%1000000] = 1 + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +/////// Mid density + +// go test -bench=BenchmarkFlorianUekermannMidDensityIterateMany +func BenchmarkFlorianUekermannMidDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 3000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +////////// High density + +func BenchmarkFlorianUekermannMidStrongDensityIterateMany(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + buffer := make([]uint, 256) + b.ResetTimer() + sum := uint(0) + for i := 0; i < b.N; i++ { + j := uint(0) + j, buffer = bitmap.NextSetMany(j, buffer) + for ; len(buffer) > 0; j, buffer = bitmap.NextSetMany(j, buffer) { + for k := range buffer { + sum += buffer[k] + } + j++ + } + } + + if sum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyReg(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + bitmap := From(input) + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + for j, e := bitmap.NextSet(0); e; j, e = bitmap.NextSet(j + 1) { + checksum += j + } + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkFlorianUekermannMidStrongDensityIterateManyComp(b *testing.B) { + input := make([]uint64, 1000000) + rnd := rand.NewSource(0).(rand.Source64) + for i := 0; i < 20000000; i++ { + input[rnd.Uint64()%1000000] |= uint64(1) << (rnd.Uint64() % 64) + } + b.ResetTimer() + checksum := uint(0) + for i := 0; i < b.N; i++ { + checksum += good(input) + } + if checksum == 0 { // added just to fool ineffassign + return + } +} + +func BenchmarkBitsetReadWrite(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + buffer := bytes.Buffer{} + temp := New(100000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.WriteTo(&buffer) + temp.ReadFrom(&buffer) + buffer.Reset() + } +} + +func BenchmarkIsSuperSet(b *testing.B) { + new := func(len int, density float64) *BitSet { + r := rand.New(rand.NewSource(42)) + bs := New(uint(len)) + for i := 0; i < len; i++ { + bs.SetTo(uint(i), r.Float64() < density) + } + return bs + } + + bench := func(name string, lenS, lenSS int, density float64, overrideS, overrideSS map[int]bool, f func(*BitSet, *BitSet) bool) { + s := new(lenS, density) + ss := new(lenSS, density) + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = f(ss, s) + } + }) + } + + f := func(ss, s *BitSet) bool { + return ss.IsSuperSet(s) + } + fStrict := func(ss, s *BitSet) bool { + return ss.IsStrictSuperSet(s) + } + + for _, len := range []int{1, 10, 100, 1000, 10000, 100000} { + density := 0.5 + bench(fmt.Sprintf("equal, len=%d", len), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, len=%d, strict", len), + len, len, density, nil, nil, fStrict) + } + + for _, density := range []float64{0, 0.05, 0.2, 0.8, 0.95, 1} { + len := 10000 + bench(fmt.Sprintf("equal, density=%.2f", density), + len, len, density, nil, nil, f) + bench(fmt.Sprintf("equal, density=%.2f, strict", density), + len, len, density, nil, nil, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: true} + overrideSS := map[int]bool{diff: false} + bench(fmt.Sprintf("subset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("subset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } + + for _, diff := range []int{0, 100, 1000, 9999} { + len := 10000 + density := 0.5 + overrideS := map[int]bool{diff: false} + overrideSS := map[int]bool{diff: true} + bench(fmt.Sprintf("superset, len=%d, diff=%d", len, diff), + len, len, density, overrideS, overrideSS, f) + bench(fmt.Sprintf("superset, len=%d, diff=%d, strict", len, diff), + len, len, density, overrideS, overrideSS, fStrict) + } +} + +// clear the right most bit (C-RMS) +// test two different algorithms +func BenchmarkClearRMS(b *testing.B) { + var word uint64 + + // cryptic + b.Run("cryptic", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + t := word & ((^word) + 1) + word = word ^ t + } + }) + + // less cryptic + b.Run("simple", func(b *testing.B) { + word = 0xaaaa_aaaa_aaaa_aaaa + for i := 0; i < b.N; i++ { + word &= word - 1 + } + }) +} + +// go test -bench=Rank +func BenchmarkRank(b *testing.B) { + s := New(100000) + for i := 0; i < 100000; i += 100 { + s.Set(uint(i)) + } + for _, u := range []uint{1, 20, 50, 100, 200, 500, 1_000, 10_000, 20_000, 50_000, 100_000, 200_000} { + b.Run(fmt.Sprintf("Rank(%d)", u), func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = s.Rank(u) + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_iter_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_iter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1ca31a525aae008f5840052761923c0f77595b41 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_iter_test.go @@ -0,0 +1,74 @@ +//go:build go1.23 +// +build go1.23 + +package bitset + +import ( + "testing" +) + +func TestIter(t *testing.T) { + var b BitSet + b.Set(0).Set(3).Set(5).Set(6).Set(63).Set(64).Set(65).Set(127).Set(128).Set(1000000) + + // Expected values that should be set + expected := []uint{0, 3, 5, 6, 63, 64, 65, 127, 128, 1000000} + got := make([]uint, 0) + + // Collect all values from iterator + for i := range b.EachSet() { + got = append(got, i) + } + + // Test 1: Check length matches expected + if len(got) != len(expected) { + t.Errorf("Expected %d elements, got %d", len(expected), len(got)) + } + + // Test 2: Check all expected values are present and in correct order + for i, want := range expected { + if i >= len(got) { + t.Errorf("Missing expected value %d at position %d", want, i) + continue + } + if got[i] != want { + t.Errorf("At position %d: expected %d, got %d", i, want, got[i]) + } + } + + // Test 3: Check no extra values + if len(got) > len(expected) { + t.Errorf("Got extra values: %v", got[len(expected):]) + } +} +func BenchmarkIter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for range s.EachSet() { + c++ + } + } +} + +func BenchmarkNonInter(b *testing.B) { + b.StopTimer() + s := New(10000) + for i := 0; i < 10000; i += 3 { + s.Set(uint(i)) + } + + b.StartTimer() + for j := 0; j < b.N; j++ { + c := uint(0) + for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { + c++ + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4dfba5769bc17a556b2298ea84c30993b287cf9a --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/bitset_test.go @@ -0,0 +1,3037 @@ +// Copyright 2014 Will Fitzgerald. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file tests bit sets + +package bitset + +import ( + "bytes" + "compress/gzip" + "encoding" + "encoding/base64" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "math/bits" + "math/rand" + "reflect" + "strconv" + "testing" + "time" +) + +func TestStringer(t *testing.T) { + v := New(0) + for i := uint(0); i < 10; i++ { + v.Set(i) + } + if v.String() != "{0,1,2,3,4,5,6,7,8,9}" { + t.Error("bad string output") + } +} + +func TestStringLong(t *testing.T) { + v := New(0) + for i := uint(0); i < 262145; i++ { + v.Set(i) + } + str := v.String() + if len(str) != 1723903 { + t.Error("Unexpected string length: ", len(str)) + } +} + +func TestEmptyBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + b := New(0) + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestZeroValueBitSet(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("A zero-length bitset should be fine") + } + }() + var b BitSet + if b.Len() != 0 { + t.Errorf("Empty set should have capacity 0, not %d", b.Len()) + } +} + +func TestBitSetNew(t *testing.T) { + v := New(16) + if v.Test(0) { + t.Errorf("Unable to make a bit set and read its 0th value.") + } +} + +func TestBitSetHuge(t *testing.T) { + v := New(uint(math.MaxUint32)) + if v.Test(0) { + t.Errorf("Unable to make a huge bit set and read its 0th value.") + } +} + +func TestLen(t *testing.T) { + v := New(1000) + if v.Len() != 1000 { + t.Errorf("Len should be 1000, but is %d.", v.Len()) + } +} + +func TestLenIsNumberOfBitsNotBytes(t *testing.T) { + var b BitSet + if b.Len() != 0 { + t.Errorf("empty bitset should have Len 0, got %v", b.Len()) + } + + b.Set(0) + if b.Len() != 1 { + t.Errorf("bitset with first bit set should have Len 1, got %v", b.Len()) + } + + b.Set(8) + if b.Len() != 9 { + t.Errorf("bitset with 0th and 8th bit set should have Len 9, got %v", b.Len()) + } + + b.Set(1) + if b.Len() != 9 { + t.Errorf("bitset with 0th, 1st and 8th bit set should have Len 9, got %v", b.Len()) + } +} + +func ExampleBitSet_Len() { + var b BitSet + b.Set(8) + fmt.Println("len", b.Len()) + fmt.Println("count", b.Count()) + // Output: + // len 9 + // count 1 +} + +func TestBitSetIsClear(t *testing.T) { + v := New(1000) + for i := uint(0); i < 1000; i++ { + if v.Test(i) { + t.Errorf("Bit %d is set, and it shouldn't be.", i) + } + } +} + +func TestExtendOnBoundary(t *testing.T) { + v := New(32) + defer func() { + if r := recover(); r != nil { + t.Error("Border out of index error should not have caused a panic") + } + }() + v.Set(32) +} + +func TestExceedCap(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("Set to capacity should have caused a panic") + } + }() + NumHosts := uint(32768) + bmp := New(NumHosts) + bmp.ClearAll() + d := Cap() + bmp.Set(d) +} + +func TestExpand(t *testing.T) { + v := New(0) + defer func() { + if r := recover(); r != nil { + t.Error("Expansion should not have caused a panic") + } + }() + for i := uint(0); i < 1000; i++ { + v.Set(i) + } +} + +func TestBitSetAndGet(t *testing.T) { + v := New(1000) + v.Set(100) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestNextClear(t *testing.T) { + v := New(1000) + v.Set(0).Set(1) + next, found := v.NextClear(0) + if !found || next != 2 { + t.Errorf("Found next clear bit as %d, it should have been 2", next) + } + + v = New(1000) + for i := uint(0); i < 66; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if !found || next != 66 { + t.Errorf("Found next clear bit as %d, it should have been 66", next) + } + + v = New(1000) + for i := uint(0); i < 64; i++ { + v.Set(i) + } + v.Clear(45) + v.Clear(52) + next, found = v.NextClear(10) + if !found || next != 45 { + t.Errorf("Found next clear bit as %d, it should have been 45", next) + } + + v = New(1000) + for i := uint(0); i < 128; i++ { + v.Set(i) + } + v.Clear(73) + v.Clear(99) + next, found = v.NextClear(10) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + next, found = v.NextClear(72) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(73) + if !found || next != 73 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + next, found = v.NextClear(74) + if !found || next != 99 { + t.Errorf("Found next clear bit as %d, it should have been 73", next) + } + + v = New(128) + next, found = v.NextClear(0) + if !found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have been 0", next) + } + + for i := uint(0); i < 128; i++ { + v.Set(i) + } + _, found = v.NextClear(0) + if found { + t.Errorf("There are not clear bits") + } + + b := new(BitSet) + c, d := b.NextClear(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } + + v = New(100) + for i := uint(0); i != 100; i++ { + v.Set(i) + } + next, found = v.NextClear(0) + if found || next != 0 { + t.Errorf("Found next clear bit as %d, it should have return (0, false)", next) + } +} + +func TestIterate(t *testing.T) { + v := New(10000) + v.Set(0) + v.Set(1) + v.Set(2) + data := make([]uint, 3) + c := 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + v.Set(10) + v.Set(2000) + data = make([]uint, 5) + c = 0 + for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { + data[c] = i + c++ + } + if data[0] != 0 { + t.Errorf("bug 0") + } + if data[1] != 1 { + t.Errorf("bug 1") + } + if data[2] != 2 { + t.Errorf("bug 2") + } + if data[3] != 10 { + t.Errorf("bug 3") + } + if data[4] != 2000 { + t.Errorf("bug 4") + } +} + +func TestNextSet(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + startIdx uint + wantIdx uint + wantOk bool + }{ + { + name: "null", + set: []uint{}, + startIdx: 0, + wantIdx: 0, + wantOk: false, + }, + { + name: "zero", + set: []uint{0}, + startIdx: 0, + wantIdx: 0, + wantOk: true, + }, + { + name: "1,5", + set: []uint{1, 5}, + startIdx: 0, + wantIdx: 1, + wantOk: true, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 100, + wantIdx: 130, + wantOk: true, + }, + { + name: "many-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{130, 190, 300, 420}, + startIdx: 100, + wantIdx: 250, + wantOk: true, + }, + { + name: "last", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 511, + wantIdx: 511, + wantOk: true, + }, + { + name: "last-2", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{511}, + startIdx: 511, + wantIdx: 0, + wantOk: false, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, ok := b.NextSet(tc.startIdx) + + if ok != tc.wantOk { + t.Errorf("NextSet, %s: got ok: %v, want: %v", tc.name, ok, tc.wantOk) + } + if idx != tc.wantIdx { + t.Errorf("NextSet, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + } +} + +func TestNextSetMany(t *testing.T) { + testCases := []struct { + name string + // + set []uint + del []uint + // + buf []uint + wantData []uint + // + startIdx uint + wantIdx uint + }{ + { + name: "null", + set: []uint{}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "zero", + set: []uint{0}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{0}, // bit #0 is set + startIdx: 0, + wantIdx: 0, + }, + { + name: "1,5", + set: []uint{1, 5}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "many", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + startIdx: 0, + wantIdx: 511, + }, + { + name: "start idx", + set: []uint{1, 65, 130, 190, 250, 300, 380, 420, 480, 511}, + del: []uint{}, + buf: make([]uint, 0, 512), + wantData: []uint{250, 300, 380, 420, 480, 511}, + startIdx: 195, + wantIdx: 511, + }, + { + name: "zero buffer", + set: []uint{1, 2, 3, 4, 511}, + del: []uint{}, + buf: make([]uint, 0), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + { + name: "buffer too short, first word", + set: []uint{1, 2, 3, 4, 5, 6, 7, 8, 9}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{1, 2, 3, 4, 5}, + startIdx: 0, + wantIdx: 5, + }, + { + name: "buffer too short", + set: []uint{65, 66, 67, 68, 69, 70}, + del: []uint{}, + buf: make([]uint, 0, 5), // buffer + wantData: []uint{65, 66, 67, 68, 69}, + startIdx: 0, + wantIdx: 69, + }, + { + name: "special, last return", + set: []uint{1}, + del: []uint{1}, // delete without compact + buf: make([]uint, 0, 5), // buffer + wantData: []uint{}, + startIdx: 0, + wantIdx: 0, + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + for _, u := range tc.del { + b.Clear(u) // without compact + } + + idx, buf := b.NextSetMany(tc.startIdx, tc.buf) + + if idx != tc.wantIdx { + t.Errorf("NextSetMany, %s: got next idx: %d, want: %d", tc.name, idx, tc.wantIdx) + } + + if !reflect.DeepEqual(buf, tc.wantData) { + t.Errorf("NextSetMany, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, buf, tc.wantData) + } + } +} + +func TestAppendTo(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 0, 5), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 0), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AppendTo(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AppendTo, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestAsSlice(t *testing.T) { + testCases := []struct { + name string + set []uint + buf []uint + }{ + { + name: "null", + set: nil, + buf: nil, + }, + { + name: "one", + set: []uint{42}, + buf: make([]uint, 1), + }, + { + name: "many", + set: []uint{1, 42, 55, 258, 7211, 54666}, + buf: make([]uint, 6), + }, + } + + for _, tc := range testCases { + var b BitSet + for _, u := range tc.set { + b.Set(u) + } + + tc.buf = b.AsSlice(tc.buf) + + if !reflect.DeepEqual(tc.buf, tc.set) { + t.Errorf("AsSlice, %s: returned buf is not equal as expected:\ngot: %v\nwant: %v", + tc.name, tc.buf, tc.set) + } + } +} + +func TestPanicAppendTo(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error("AppendTo with empty buf should not have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AppendTo(nil) +} + +func TestPanicAsSlice(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("AsSlice with buf too small should have caused a panic") + } + }() + v := New(1000) + v.Set(1000) + _ = v.AsSlice(nil) +} + +func TestSetTo(t *testing.T) { + v := New(1000) + v.SetTo(100, true) + if !v.Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } + v.SetTo(100, false) + if v.Test(100) { + t.Errorf("Bit %d is set, and it shouldn't be.", 100) + } +} + +func TestChain(t *testing.T) { + if !New(1000).Set(100).Set(99).Clear(99).Test(100) { + t.Errorf("Bit %d is clear, and it shouldn't be.", 100) + } +} + +func TestOutOfBoundsLong(t *testing.T) { + v := New(64) + defer func() { + if r := recover(); r != nil { + t.Error("Long distance out of index error should not have caused a panic") + } + }() + v.Set(1000) +} + +func TestOutOfBoundsClose(t *testing.T) { + v := New(65) + defer func() { + if r := recover(); r != nil { + t.Error("Local out of index error should not have caused a panic") + } + }() + v.Set(66) +} + +func TestCount(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + checkLast := true + for i := uint(0); i < tot; i++ { + sz := uint(v.Count()) + if sz != i { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + checkLast = false + break + } + v.Set(i) + } + if checkLast { + sz := uint(v.Count()) + if sz != tot { + t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) + } + } +} + +// test setting every 3rd bit, just in case something odd is happening +func TestCount2(t *testing.T) { + tot := uint(64*4 + 11) // just some multi unit64 number + v := New(tot) + for i := uint(0); i < tot; i += 3 { + sz := uint(v.Count()) + if sz != i/3 { + t.Errorf("Count reported as %d, but it should be %d", sz, i) + break + } + v.Set(i) + } +} + +// nil tests +func TestNullTest(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Checking bit of null reference should have caused a panic") + } + }() + v.Test(66) +} + +func TestNullSet(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Setting bit of null reference should have caused a panic") + } + }() + v.Set(66) +} + +func TestNullClear(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Clearning bit of null reference should have caused a panic") + } + }() + v.Clear(66) +} + +func TestNullCount(t *testing.T) { + var v *BitSet + defer func() { + if r := recover(); r != nil { + t.Error("Counting null reference should not have caused a panic") + } + }() + cnt := v.Count() + if cnt != 0 { + t.Errorf("Count reported as %d, but it should be 0", cnt) + } +} + +func TestMustNew(t *testing.T) { + testCases := []struct { + length uint + nwords int + }{ + { + length: 0, + nwords: 0, + }, + { + length: 1, + nwords: 1, + }, + { + length: 64, + nwords: 1, + }, + { + length: 65, + nwords: 2, + }, + { + length: 512, + nwords: 8, + }, + { + length: 513, + nwords: 9, + }, + } + + for _, tc := range testCases { + b := MustNew(tc.length) + if len(b.set) != tc.nwords { + t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords) + } + } +} + +func TestPanicMustNew(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Error("length too big should have caused a panic") + } + }() + MustNew(Cap()) +} + +func TestPanicDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Difference(compare) +} + +func TestPanicUnionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicUnionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Union(compare) +} + +func TestPanicIntersectionBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicIntersectionCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.Intersection(compare) +} + +func TestPanicSymmetricDifferenceBNil(t *testing.T) { + var b *BitSet + compare := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil First should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { + var compare *BitSet + b := New(10) + defer func() { + if r := recover(); r == nil { + t.Error("Nil Second should should have caused a panic") + } + }() + b.SymmetricDifference(compare) +} + +func TestPanicComplementBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Complement() +} + +func TestPanicAnytBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.Any() +} + +func TestPanicNonetBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.None() +} + +func TestPanicAlltBNil(t *testing.T) { + var b *BitSet + defer func() { + if r := recover(); r == nil { + t.Error("Nil should should have caused a panic") + } + }() + b.All() +} + +func TestAll(t *testing.T) { + v := New(0) + if !v.All() { + t.Error("Empty sets should return true on All()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if !v.All() { + t.Error("Non-empty sets with all bits set should return true on All()") + } + v = New(2) + if v.All() { + t.Error("Non-empty sets with no bits set should return false on All()") + } + v = New(2) + v.SetTo(0, true) + if v.All() { + t.Error("Non-empty sets with some bits set should return false on All()") + } +} + +func TestShrink(t *testing.T) { + bs := New(10) + bs.Set(0) + bs.Shrink(63) + if !bs.Test(0) { + t.Error("0 should be set") + return + } + b := New(0) + + b.Set(0) + b.Set(1) + b.Set(2) + b.Set(3) + b.Set(64) + b.Compact() + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if !b.Test(3) { + t.Error("3 should be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + + b.Shrink(2) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if !b.Test(2) { + t.Error("2 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if b.Test(64) { + t.Error("64 should not be set") + return + } + + b.Set(24) + b.Shrink(100) + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b.Set(127) + b.Set(128) + b.Set(129) + b.Compact() + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if !b.Test(129) { + t.Error("129 be set") + return + } + + b.Shrink(128) + if !b.Test(127) { + t.Error("127 should be set") + return + } + if !b.Test(128) { + t.Error("128 should be set") + return + } + if b.Test(129) { + t.Error("129 should not be set") + return + } + + b.Set(129) + b.Shrink(129) + if !b.Test(129) { + t.Error("129 should be set") + return + } + + b.Set(1000) + b.Set(2000) + b.Set(3000) + b.Shrink(3000) + if len(b.set) != 3000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if !b.Test(3000) { + t.Error("3000 should be set") + return + } + + b.Shrink(2000) + if len(b.set) != 2000/64+1 { + t.Error("Wrong length of BitSet.set") + return + } + if b.Test(3000) { + t.Error("3000 should not be set") + return + } + if !b.Test(2000) { + t.Error("2000 should be set") + return + } + if !b.Test(1000) { + t.Error("1000 should be set") + return + } + if !b.Test(24) { + t.Error("24 should be set") + return + } + + b = New(110) + b.Set(80) + b.Shrink(70) + for _, word := range b.set { + if word != 0 { + t.Error("word should be 0", word) + } + } +} + +func TestInsertAtWithSet(t *testing.T) { + b := New(0) + b.Set(0) + b.Set(1) + b.Set(63) + b.Set(64) + b.Set(65) + + b.InsertAt(3) + if !b.Test(0) { + t.Error("0 should be set") + return + } + if !b.Test(1) { + t.Error("1 should be set") + return + } + if b.Test(3) { + t.Error("3 should not be set") + return + } + if !b.Test(64) { + t.Error("64 should be set") + return + } + if !b.Test(65) { + t.Error("65 should be set") + return + } + if !b.Test(66) { + t.Error("66 should be set") + return + } +} + +func TestInsertAt(t *testing.T) { + type testCase struct { + input []string + insertIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(62), + expected: []string{ + "1011111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(63), + expected: []string{ + "0111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(0), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111110", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(70), + expected: []string{ + "1111111111111111111111111111111111111111111111111111111111111111", + "1111111111111111111111111111111111111111111111111111111110111111", + "1111111111111111111111111111111111111111111111111111111111100001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1111111111111111111111111111111111111111111111111111111111110000", + }, + insertIdx: uint(10), + expected: []string{ + "1111111111111111111111111111111111111111111111111111101111110000", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.InsertAt(tc.insertIdx) + if len(b.set) != len(expected) { + t.Error("Length of sets should be equal") + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Error("Unexpected results found in set") + return + } + } + } +} + +func TestNone(t *testing.T) { + v := New(0) + if !v.None() { + t.Error("Empty sets should return true on None()") + } + v = New(2) + v.SetTo(0, true) + v.SetTo(1, true) + if v.None() { + t.Error("Non-empty sets with all bits set should return false on None()") + } + v = New(2) + if !v.None() { + t.Error("Non-empty sets with no bits set should return true on None()") + } + v = New(2) + v.SetTo(0, true) + if v.None() { + t.Error("Non-empty sets with some bits set should return false on None()") + } + v = new(BitSet) + if !v.None() { + t.Error("Empty sets should return true on None()") + } +} + +func TestEqual(t *testing.T) { + a := New(100) + b := New(99) + c := New(100) + if a.Equal(b) { + t.Error("Sets of different sizes should be not be equal") + } + if !a.Equal(c) { + t.Error("Two empty sets of the same size should be equal") + } + a.Set(99) + c.Set(0) + if a.Equal(c) { + t.Error("Two sets with differences should not be equal") + } + c.Set(99) + a.Set(0) + if !a.Equal(c) { + t.Error("Two sets with the same bits set should be equal") + } + if a.Equal(nil) { + t.Error("The sets should be different") + } + a = New(0) + b = New(0) + if !a.Equal(b) { + t.Error("Two empty set should be equal") + } + var x *BitSet + var y *BitSet + z := New(0) + if !x.Equal(y) { + t.Error("Two nil bitsets should be equal") + } + if x.Equal(z) { + t.Error("Nil receiver bitset should not be equal to non-nil bitset") + } +} + +func TestUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.UnionCardinality(b) != 200 { + t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b)) + } + if a.UnionCardinality(b) != b.UnionCardinality(a) { + t.Errorf("Union should be symmetric") + } + + c := a.Union(b) + d := b.Union(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestInPlaceUnion(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceUnion(b) + d := b.Clone() + d.InPlaceUnion(a) + if c.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", c.Count()) + } + if d.Count() != 200 { + t.Errorf("Union should have 200 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Union should be symmetric") + } +} + +func TestIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.IntersectionCardinality(b) != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b)) + } + if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) { + t.Errorf("Intersection should be symmetric") + } + c := a.Intersection(b) + d := b.Intersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestInplaceIntersection(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1).Set(i) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceIntersection(b) + d := b.Clone() + d.InPlaceIntersection(a) + if c.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 50 { + t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("Intersection should be symmetric") + } +} + +func TestDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.DifferenceCardinality(b) != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b)) + } + if b.DifferenceCardinality(a) != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a)) + } + + c := a.Difference(b) + d := b.Difference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestInPlaceDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) + b.Set(i - 1) + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceDifference(b) + d := b.Clone() + d.InPlaceDifference(a) + if c.Count() != 50 { + t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) + } + if c.Equal(d) { + t.Errorf("Difference, here, should not be symmetric") + } +} + +func TestSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + if a.SymmetricDifferenceCardinality(b) != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b)) + } + if b.SymmetricDifferenceCardinality(a) != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a)) + } + + c := a.SymmetricDifference(b) + d := b.SymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestInPlaceSymmetricDifference(t *testing.T) { + a := New(100) + b := New(200) + for i := uint(1); i < 100; i += 2 { + a.Set(i) // 01010101010 ... 0000000 + b.Set(i - 1).Set(i) // 11111111111111111000000 + } + for i := uint(100); i < 200; i++ { + b.Set(i) + } + c := a.Clone() + c.InPlaceSymmetricDifference(b) + d := b.Clone() + d.InPlaceSymmetricDifference(a) + if c.Count() != 150 { + t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) + } + if d.Count() != 150 { + t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) + } + if !c.Equal(d) { + t.Errorf("SymmetricDifference should be symmetric") + } +} + +func TestComplement(t *testing.T) { + a := New(50) + b := a.Complement() + if b.Count() != 50 { + t.Errorf("Complement failed, size should be 50, but was %d", b.Count()) + } + a = New(50) + a.Set(10).Set(20).Set(42) + b = a.Complement() + if b.Count() != 47 { + t.Errorf("Complement failed, size should be 47, but was %d", b.Count()) + } +} + +func TestIsSuperSet(t *testing.T) { + test := func(name string, lenS, lenSS int, overrideS, overrideSS map[int]bool, want, wantStrict bool) { + t.Run(name, func(t *testing.T) { + s := New(uint(lenS)) + ss := New(uint(lenSS)) + + l := lenS + if lenSS < lenS { + l = lenSS + } + + r := rand.New(rand.NewSource(42)) + for i := 0; i < l; i++ { + bit := r.Intn(2) == 1 + s.SetTo(uint(i), bit) + ss.SetTo(uint(i), bit) + } + + for i, v := range overrideS { + s.SetTo(uint(i), v) + } + for i, v := range overrideSS { + ss.SetTo(uint(i), v) + } + + if got := ss.IsSuperSet(s); got != want { + t.Errorf("IsSuperSet() = %v, want %v", got, want) + } + if got := ss.IsStrictSuperSet(s); got != wantStrict { + t.Errorf("IsStrictSuperSet() = %v, want %v", got, wantStrict) + } + }) + } + + test("empty", 0, 0, nil, nil, true, false) + test("empty vs non-empty", 0, 100, nil, nil, true, false) + test("non-empty vs empty", 100, 0, nil, nil, true, false) + test("equal", 100, 100, nil, nil, true, false) + + test("set is shorter, subset", 100, 200, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is shorter, equal", 100, 200, nil, nil, true, false) + test("set is shorter, superset", 100, 200, map[int]bool{50: false}, map[int]bool{50: true}, true, true) + test("set is shorter, neither", 100, 200, map[int]bool{50: true}, map[int]bool{50: false, 150: true}, false, false) + + test("set is longer, subset", 200, 100, map[int]bool{50: true}, map[int]bool{50: false}, false, false) + test("set is longer, equal", 200, 100, nil, nil, true, false) + test("set is longer, superset", 200, 100, nil, map[int]bool{150: true}, true, true) + test("set is longer, neither", 200, 100, map[int]bool{50: false, 150: true}, map[int]bool{50: true}, false, false) +} + +func TestDumpAsBits(t *testing.T) { + a := New(10).Set(10) + astr := "0000000000000000000000000000000000000000000000000000010000000000." + if a.DumpAsBits() != astr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits()) + } + var b BitSet // zero value (b.set == nil) + bstr := "." + if b.DumpAsBits() != bstr { + t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits()) + } +} + +func TestMarshalUnmarshalBinary(t *testing.T) { + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + + aSetBit := uint(128) + a = New(256).Set(aSetBit) + aExpectedMarshaledSize := 8 /* length: uint64 */ + 4*8 /* set : [4]uint64 */ + aMarshaled, err := a.MarshalBinary() + + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + shiftAmount := uint(72) + // https://github.com/bits-and-blooms/bitset/issues/114 + for i := uint(0); i < shiftAmount; i++ { + a.DeleteAt(0) + } + + aExpectedMarshaledSize = 8 /* length: uint64 */ + 3*8 /* set : [3]uint64 */ + aMarshaled, err = a.MarshalBinary() + if err != nil || aExpectedMarshaledSize != len(aMarshaled) || aExpectedMarshaledSize != a.BinaryStorageSize() { + t.Error("MarshalBinary failed to produce expected (", aExpectedMarshaledSize, ") number of bytes") + return + } + + copyBinary(t, a, b) + + if b.Len() != 256-shiftAmount || !b.Test(aSetBit-shiftAmount) { + t.Error("Shifted bitset is not copied correctly") + } +} + +func TestMarshalUnmarshalBinaryByLittleEndian(t *testing.T) { + LittleEndian() + defer func() { + // Revert when done. + binaryOrder = binary.BigEndian + }() + a := New(1010).Set(10).Set(1001) + b := new(BitSet) + + copyBinary(t, a, b) + + // BitSets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryUnmarshaler) { + data, err := from.MarshalBinary() + if err != nil { + t.Error(err.Error()) + return + } + + err = to.UnmarshalBinary(data) + if err != nil { + t.Error(err.Error()) + return + } +} + +func TestMarshalUnmarshalJSON(t *testing.T) { + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) +} + +func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + // appending some noise + data = data[:len(data)-3] // remove " + data = append(data, []byte(`AAAAAAAAAA"`)...) + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + // Do not over-reading when unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) { + Base64StdEncoding() + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Error(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Error(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } +} + +func TestSafeSet(t *testing.T) { + b := new(BitSet) + c := b.safeSet() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestSetBitsetFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := new(BitSet) + b.SetBitsetFrom(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestIssue116(t *testing.T) { + a := []uint64{2, 3, 5, 7, 11} + b := []uint64{2, 3, 5, 7, 11, 0, 1} + bitset1 := FromWithLength(320, a) + bitset2 := FromWithLength(320, b) + if !bitset1.Equal(bitset2) || !bitset2.Equal(bitset1) { + t.Error("Bitsets should be equal irrespective of the underlying capacity") + } +} + +func TestFrom(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + outType := fmt.Sprintf("%T", b) + expType := "*bitset.BitSet" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } +} + +func TestWords(t *testing.T) { + b := new(BitSet) + c := b.Words() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +// Bytes is deprecated +func TestBytes(t *testing.T) { + b := new(BitSet) + c := b.Bytes() + outType := fmt.Sprintf("%T", c) + expType := "[]uint64" + if outType != expType { + t.Error("Expecting type: ", expType, ", gotf:", outType) + return + } + if len(c) != 0 { + t.Error("The slice should be empty") + return + } +} + +func TestCap(t *testing.T) { + c := Cap() + if c <= 0 { + t.Error("The uint capacity should be >= 0") + return + } +} + +func TestWordsNeededLong(t *testing.T) { + i := Cap() + out := wordsNeeded(i) + if out <= 0 { + t.Error("Unexpected value: ", out) + return + } +} + +func TestTestTooLong(t *testing.T) { + b := new(BitSet) + if b.Test(1) { + t.Error("Unexpected value: true") + return + } +} + +func TestClearTooLong(t *testing.T) { + b := new(BitSet) + c := b.Clear(1) + if b != c { + t.Error("Unexpected value") + return + } +} + +func TestClearAll(t *testing.T) { + u := []uint64{2, 3, 5, 7, 11} + b := From(u) + c := b.ClearAll() + if c.length != 320 { + t.Error("Unexpected length: ", b.length) + return + } + if c.Test(0) || c.Test(1) || c.Test(2) || c.Test(3) || c.Test(4) || c.Test(5) { + t.Error("All bits should be unset") + return + } +} + +func TestRankSelect(t *testing.T) { + u := []uint{2, 3, 5, 7, 11, 700, 1500} + b := BitSet{} + for _, v := range u { + b.Set(v) + } + + if b.Rank(5) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(6) != 3 { + t.Error("Unexpected rank") + return + } + if b.Rank(1500) != 7 { + t.Error("Unexpected rank") + return + } + if b.Select(0) != 2 { + t.Error("Unexpected select") + return + } + if b.Select(1) != 3 { + t.Error("Unexpected select") + return + } + if b.Select(2) != 5 { + t.Error("Unexpected select") + return + } + + if b.Select(5) != 700 { + t.Error("Unexpected select") + return + } +} + +func TestFlip(t *testing.T) { + b := new(BitSet) + c := b.Flip(11) + if c.length != 12 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.Flip(7) + if d.length != 12 { + t.Error("Unexpected value: ", d.length) + return + } +} + +func TestFlipRange(t *testing.T) { + b := new(BitSet) + b.Set(1).Set(3).Set(5).Set(7).Set(9).Set(11).Set(13).Set(15) + c := b.FlipRange(4, 25) + if c.length != 25 { + t.Error("Unexpected value: ", c.length) + return + } + d := c.FlipRange(8, 24) + if d.length != 25 { + t.Error("Unexpected value: ", d.length) + return + } + // + for i := uint(0); i < 256; i++ { + for j := uint(0); j <= i; j++ { + bits := New(i) + bits.FlipRange(0, j) + c := bits.Count() + if c != j { + t.Error("Unexpected value: ", c, " expected: ", j) + return + } + } + } +} + +func TestCopy(t *testing.T) { + a := New(10) + if a.Copy(nil) != 0 { + t.Error("No values should be copied") + return + } + a = New(10) + b := New(20) + if a.Copy(b) != 10 { + t.Error("Unexpected value") + return + } +} + +func TestCopyUnaligned(t *testing.T) { + a := New(16) + a.FlipRange(0, 16) + b := New(1) + a.Copy(b) + if b.Count() > b.Len() { + t.Errorf("targets copied set count (%d) should never be larger than target's length (%d)", b.Count(), b.Len()) + } + if !b.Test(0) { + t.Errorf("first bit should still be set in copy: %+v", b) + } + + // Test a more complex scenario with a mix of bits set in the unaligned space to verify no bits are lost. + a = New(32) + a.Set(0).Set(3).Set(4).Set(16).Set(17).Set(29).Set(31) + b = New(19) + a.Copy(b) + + const expectedCount = 5 + if b.Count() != expectedCount { + t.Errorf("targets copied set count: %d, want %d", b.Count(), expectedCount) + } + + if !(b.Test(0) && b.Test(3) && b.Test(4) && b.Test(16) && b.Test(17)) { + t.Errorf("expected set bits are not set: %+v", b) + } +} + +func TestCopyFull(t *testing.T) { + a := New(10) + b := &BitSet{} + a.CopyFull(b) + if b.length != a.length || len(b.set) != len(a.set) { + t.Error("Expected full length copy") + return + } + for i, v := range a.set { + if v != b.set[i] { + t.Error("Unexpected value") + return + } + } +} + +func TestNextSetError(t *testing.T) { + b := new(BitSet) + c, d := b.NextSet(1) + if c != 0 || d { + t.Error("Unexpected values") + return + } +} + +func TestDeleteWithBitStrings(t *testing.T) { + type testCase struct { + input []string + deleteIdx uint + expected []string + } + + testCases := []testCase{ + { + input: []string{ + "1110000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "0110000000000000000000000000000000000000000000000000000000000001", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000010101", + }, + deleteIdx: uint(0), + expected: []string{ + "0100000000000000000000000000000000000000000000000000000000001010", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000111000", + }, + deleteIdx: uint(4), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000011000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "1010000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(63), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000001", + "0101000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1000000000000000000000000000000000000000000000000000000000000001", + "1000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(64), + expected: []string{ + "1000000000000000000000000000000000000000000000000000000000000000", + "1100000000000000000000000000000000000000000000000000000000000000", + "0100000000000000000000000000000000000000000000000000000000000000", + }, + }, + { + input: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + }, + deleteIdx: uint(256), + expected: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000000", + }, + }, + } + + for _, tc := range testCases { + var input []uint64 + for _, inputElement := range tc.input { + parsed, _ := strconv.ParseUint(inputElement, 2, 64) + input = append(input, parsed) + } + + var expected []uint64 + for _, expectedElement := range tc.expected { + parsed, _ := strconv.ParseUint(expectedElement, 2, 64) + expected = append(expected, parsed) + } + + b := From(input) + b.DeleteAt(tc.deleteIdx) + if len(b.set) != len(expected) { + t.Errorf("Length of sets expected to be %d, but was %d", len(expected), len(b.set)) + return + } + for i := range b.set { + if b.set[i] != expected[i] { + t.Errorf("Unexpected output\nExpected: %b\nGot: %b", expected[i], b.set[i]) + return + } + } + } +} + +func TestDeleteWithBitSetInstance(t *testing.T) { + length := uint(256) + bitSet := New(length) + + // the indexes that get set in the bit set + indexesToSet := []uint{0, 1, 126, 127, 128, 129, 170, 171, 200, 201, 202, 203, 255} + + // the position we delete from the bitset + deleteAt := uint(127) + + // the indexes that we expect to be set after the delete + expectedToBeSet := []uint{0, 1, 126, 127, 128, 169, 170, 199, 200, 201, 202, 254} + + expected := make(map[uint]struct{}) + for _, index := range expectedToBeSet { + expected[index] = struct{}{} + } + + for _, index := range indexesToSet { + bitSet.Set(index) + } + + bitSet.DeleteAt(deleteAt) + + for i := uint(0); i < length; i++ { + if _, ok := expected[i]; ok { + if !bitSet.Test(i) { + t.Errorf("Expected index %d to be set, but wasn't", i) + } + } else { + if bitSet.Test(i) { + t.Errorf("Expected index %d to not be set, but was", i) + } + } + } +} + +func TestWriteTo(t *testing.T) { + const length = 9585 + const oneEvery = 97 + addBuf := []byte(`12345678`) + bs := New(length) + // Add some bits + for i := uint(0); i < length; i += oneEvery { + bs = bs.Set(i) + } + + var buf bytes.Buffer + n, err := bs.WriteTo(&buf) + if err != nil { + t.Fatal(err) + } + wantSz := buf.Len() // Size of the serialized data in bytes. + if n != int64(wantSz) { + t.Errorf("want write size to be %d, got %d", wantSz, n) + } + buf.Write(addBuf) // Add additional data on stream. + + // Generate test input for regression tests: + if false { + gzout := bytes.NewBuffer(nil) + gz, err := gzip.NewWriterLevel(gzout, 9) + if err != nil { + t.Fatal(err) + } + gz.Write(buf.Bytes()) + gz.Close() + t.Log("Encoded:", base64.StdEncoding.EncodeToString(gzout.Bytes())) + } + + // Read back. + bs = New(length) + n, err = bs.ReadFrom(&buf) + if err != nil { + t.Fatal(err) + } + if n != int64(wantSz) { + t.Errorf("want read size to be %d, got %d", wantSz, n) + } + // Check bits + for i := uint(0); i < length; i += oneEvery { + if !bs.Test(i) { + t.Errorf("bit %d was not set", i) + } + } + + more, err := io.ReadAll(&buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(more, addBuf) { + t.Fatalf("extra mismatch. got %v, want %v", more, addBuf) + } +} + +type inCompleteRetBufReader struct { + returnEvery int64 + reader io.Reader + offset int64 +} + +func (ir *inCompleteRetBufReader) Read(b []byte) (n int, err error) { + if ir.returnEvery > 0 { + maxRead := ir.returnEvery - (ir.offset % ir.returnEvery) + if len(b) > int(maxRead) { + b = b[:maxRead] + } + } + n, err = ir.reader.Read(b) + ir.offset += int64(n) + return +} + +func TestReadFrom(t *testing.T) { + addBuf := []byte(`12345678`) // Bytes after stream + tests := []struct { + length uint + oneEvery uint + input string // base64+gzipped + wantErr error + returnEvery int64 + }{ + { + length: 9585, + oneEvery: 97, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwMSACVgYGBg4sIgLMDAwKGARd2BgYGjAFB41noDx6IAJajw64IAajw4UoMajg4ZR4/EaP5pQh1g+MDQyNjE1M7cABAAA//9W5OoOwAQAAA==", + returnEvery: 127, + }, + { + length: 1337, + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA1ZLBgYWEIPRAUQKgJkMcCZYisEBzkSSYkSTYqCxAYZGxiamZuYWgAAAAP//D0wyWbgAAAA=", + }, + { + length: 1337, // Truncated input. + oneEvery: 42, + input: "H4sIAAAAAAAC/2IAA9VCCM3AyMDAwARmAQIAAP//vR3xdRkAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + { + length: 1337, // Empty input. + oneEvery: 42, + input: "H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=", + wantErr: io.ErrUnexpectedEOF, + }, + } + + for i, test := range tests { + t.Run(fmt.Sprint(i), func(t *testing.T) { + fatalErr := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + + var buf bytes.Buffer + b, err := base64.StdEncoding.DecodeString(test.input) + fatalErr(err) + gz, err := gzip.NewReader(bytes.NewBuffer(b)) + fatalErr(err) + _, err = io.Copy(&buf, gz) + fatalErr(err) + fatalErr(gz.Close()) + + bs := New(test.length) + _, err = bs.ReadFrom(&inCompleteRetBufReader{returnEvery: test.returnEvery, reader: &buf}) + if err != nil { + if errors.Is(err, test.wantErr) { + // Correct, nothing more we can test. + return + } + t.Fatalf("did not get expected error %v, got %v", test.wantErr, err) + } else { + if test.wantErr != nil { + t.Fatalf("did not get expected error %v", test.wantErr) + } + } + fatalErr(err) + + // Test if correct bits are set. + for i := uint(0); i < test.length; i++ { + want := i%test.oneEvery == 0 + got := bs.Test(i) + if want != got { + t.Errorf("bit %d was %v, should be %v", i, got, want) + } + } + + more, err := io.ReadAll(&buf) + fatalErr(err) + + if !bytes.Equal(more, addBuf) { + t.Errorf("extra mismatch. got %v, want %v", more, addBuf) + } + }) + } +} + +func TestSetAll(t *testing.T) { + test := func(name string, bs *BitSet, want uint) { + t.Run(name, func(t *testing.T) { + bs.SetAll() + if bs.Count() != want { + t.Errorf("expected %d bits to be set, got %d", want, bs.Count()) + } + }) + } + + test("nil", nil, 0) + for _, length := range []uint{0, 1, 10, 63, 64, 65, 100, 640} { + test(fmt.Sprintf("length %d", length), New(length), length) + } +} + +func TestShiftLeft(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftLeft(bits) + + if int(b.Count()) != len(data) { + t.Error("bad bits count") + } + + for _, i := range data { + if !b.Test(i + bits) { + t.Errorf("bit %v is not set", i+bits) + } + } + }) + } + + test("zero", 0) + test("no page change", 19) + test("shift to full page", 38) + test("full page shift", 64) + test("no page split", 80) + test("with page split", 114) + test("with extension", 242) +} + +func TestShiftRight(t *testing.T) { + data := []uint{5, 28, 45, 72, 89} + + test := func(name string, bits uint) { + t.Run(name, func(t *testing.T) { + b := New(200) + for _, i := range data { + b.Set(i) + } + + b.ShiftRight(bits) + + count := 0 + for _, i := range data { + if i > bits { + count++ + + if !b.Test(i - bits) { + t.Errorf("bit %v is not set", i-bits) + } + } + } + + if int(b.Count()) != count { + t.Error("bad bits count") + } + }) + } + + test("zero", 0) + test("no page change", 3) + test("no page split", 20) + test("with page split", 40) + test("full page shift", 64) + test("with extension", 70) + test("full shift", 89) + test("remove all", 242) +} + +func TestWord(t *testing.T) { + data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5} + testCases := map[string]struct { + index uint + expected uint64 + }{ + "first word": { + index: 0, + expected: 0x0bfd85fc01af96dd, + }, + "third word": { + index: 128, + expected: 0x7aa412221245dee1, + }, + "off the edge": { + index: 256, + expected: 0, + }, + "way off the edge": { + index: 6346235235, + expected: 0, + }, + "split between two words": { + index: 96, + expected: 0x1245dee13fe212a7, + }, + "partly off edge": { + index: 254, + expected: 1, + }, + "skip one nibble": { + index: 4, + expected: 0x40bfd85fc01af96d, + }, + "slightly offset results": { + index: 65, + expected: 0x9ff10953f5708a0a, + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + bitSet := From(data) + output := bitSet.GetWord64AtBit(testCase.index) + + if output != testCase.expected { + t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output) + } + }) + } +} + +func TestPreviousSet(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, true}, + {1, 0, true}, + {2, 2, true}, + {3, 2, true}, + {4, 4, true}, + {5, 4, true}, + {100, 4, true}, + {120, 120, true}, + {121, 120, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.ClearAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousSet(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousSet(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestPreviousClear(t *testing.T) { + v := New(128) + v.Set(0) + v.Set(2) + v.Set(4) + v.Set(120) + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {1, 1, true}, + {2, 1, true}, + {3, 3, true}, + {4, 3, true}, + {5, 5, true}, + {100, 100, true}, + {120, 119, true}, + {121, 121, true}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } + v.SetAll() + for _, tt := range []struct { + index uint + want uint + wantFound bool + }{ + {0, 0, false}, + {120, 0, false}, + {1024, 0, false}, + } { + t.Run(fmt.Sprintf("@%d", tt.index), func(t *testing.T) { + got, found := v.PreviousClear(tt.index) + if got != tt.want || found != tt.wantFound { + t.Errorf("PreviousClear(%d) = %d, %v, want %d, %v", tt.index, got, found, tt.want, tt.wantFound) + } + }) + } +} + +func TestBitSetOnesBetween(t *testing.T) { + testCases := []struct { + name string + input *BitSet + from uint + to uint + expected uint + }{ + {"empty range", New(64).Set(0).Set(1), 5, 5, 0}, + {"invalid range", New(64).Set(0).Set(1), 5, 3, 0}, + {"single word", New(64).Set(1).Set(2).Set(3), 1, 3, 2}, + {"single word full", New(64).Set(0).Set(1).Set(2).Set(3), 0, 4, 4}, + {"cross word boundary", New(128).Set(63).Set(64).Set(65), 63, 66, 3}, + {"multiple words", New(256).Set(0).Set(63).Set(64).Set(127).Set(128), 0, 129, 5}, + {"large gap", New(256).Set(0).Set(100).Set(200), 0, 201, 3}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := tc.input.OnesBetween(tc.from, tc.to) + if got != tc.expected { + t.Errorf("OnesBetween(%d, %d) = %d, want %d", + tc.from, tc.to, got, tc.expected) + } + }) + } + + // Property-based testing + const numTests = 1e5 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + size := uint(rng.Intn(1024) + 64) + bs := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + bs.Set(uint(rng.Intn(int(size)))) + } + + // Generate random range + from := uint(rng.Intn(int(size))) + to := from + uint(rng.Intn(int(size-from))) + + // Compare with naive implementation + got := bs.OnesBetween(from, to) + want := uint(0) + for j := from; j < to; j++ { + if bs.Test(j) { + want++ + } + } + + if got != want { + t.Errorf("Case %d: OnesBetween(%d, %d) = %d, want %d", + i, from, to, got, want) + } + } +} + +func BenchmarkBitSetOnesBetween(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384} + densities := []float64{0.1, 0.5, 0.9} // Different bit densities to test + rng := rand.New(rand.NewSource(42)) + + for _, size := range sizes { + for _, density := range densities { + // Create bitset with given density + bs := New(uint(size)) + for i := 0; i < int(float64(size)*density); i++ { + bs.Set(uint(rng.Intn(size))) + } + + // Generate random ranges + ranges := make([][2]uint, 1000) + for i := range ranges { + from := uint(rng.Intn(size)) + to := from + uint(rng.Intn(size-int(from))) + ranges[i] = [2]uint{from, to} + } + + name := fmt.Sprintf("size=%d/density=%.1f", size, density) + b.Run(name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + r := ranges[i%len(ranges)] + _ = bs.OnesBetween(r[0], r[1]) + } + }) + } + } +} + +func generatePextTestCases(n int) [][2]uint64 { + cases := make([][2]uint64, n) + for i := range cases { + cases[i][0] = rand.Uint64() + cases[i][1] = rand.Uint64() + } + return cases +} + +func BenchmarkPEXT(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pext(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func BenchmarkPDEP(b *testing.B) { + // Generate test cases + testCases := generatePextTestCases(1000) + + b.ResetTimer() + + var r uint64 + for i := 0; i < b.N; i++ { + tc := testCases[i%len(testCases)] + r = pdep(tc[0], tc[1]) + } + _ = r // prevent optimization +} + +func TestPext(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() + m := rng.Uint64() + result := pext(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if popCount > 0 && result >= (uint64(1)< bits.OnesCount64(w&m) { + t.Fatalf("Case %d: result has more 1s than masked input: result=%x, input&mask=%x", + i, result, w&m) + } + + // Test that extracted bits preserve relative ordering: + // For each bit position that's set in the mask (m): + // 1. Extract a bit from result (resultCopy&1) + // 2. Get corresponding input bit from w (w>>j&1) + // 3. XOR them - if different, bits weren't preserved correctly + resultCopy := result + for j := 0; j < 64; j++ { + // Check if mask bit is set at position j + if m&(uint64(1)<>j&1 gets bit j from original input + // XOR (^) checks if they match + if (resultCopy&1)^(w>>j&1) != 0 { + t.Fatalf("Case %d: bit ordering violation at position %d", i, j) + } + // Shift to examine next bit in packed result + resultCopy >>= 1 + } + } + } +} + +func TestPdep(t *testing.T) { + const numTests = 1e6 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + w := rng.Uint64() // value to deposit + m := rng.Uint64() // mask + result := pdep(w, m) + popCount := bits.OnesCount64(m) + + // Test invariants + if result&^m != 0 { + t.Fatalf("Case %d: result %x has bits set outside of mask %x", + i, result, m) + } + + if bits.OnesCount64(result) > bits.OnesCount64(w) { + t.Fatalf("Case %d: result has more 1s than input: result=%x, input=%x", + i, result, w) + } + + // Verify by using PEXT to extract bits back + // The composition of PEXT(PDEP(x,m),m) should equal x masked to popcount bits + extracted := pext(result, m) + maskBits := (uint64(1) << popCount) - 1 + if (extracted & maskBits) != (w & maskBits) { + t.Fatalf("Case %d: PEXT(PDEP(w,m),m) != w: got=%x, want=%x (w=%x, m=%x)", + i, extracted&maskBits, w&maskBits, w, m) + } + } +} + +func TestBitSetExtract(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(size)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Extract bits + src.ExtractTo(mask, dst) + + // Test invariants + if dst.Count() > src.IntersectionCardinality(mask) { + t.Errorf("Case %d: result has more 1s than masked input", i) + } + + // Test bits are properly extracted and packed + pos := uint(0) + for j := uint(0); j < size; j++ { + if mask.Test(j) { + if src.Test(j) != dst.Test(pos) { + t.Errorf("Case %d: bit ordering violation at source position %d", i, j) + } + pos++ + } + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits + mask *BitSet // mask bits + expected *BitSet // expected extracted bits + }{ + { + name: "single bit", + src: New(8).Set(1), // 0b01 + mask: New(8).Set(1), // 0b01 + expected: New(8).Set(0), // 0b1 + }, + { + name: "two sequential bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(1), // 0b11 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "sparse bits", + src: New(16).Set(0).Set(10), // 0b10000000001 + mask: New(16).Set(0).Set(5).Set(10), // 0b10000100001 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1).Set(2).Set(3), // 0b1111 + mask: New(8).Set(0).Set(2), // 0b0101 + expected: New(8).Set(0).Set(1), // 0b11 + }, + { + name: "cross word boundary", + src: New(128).Set(63).Set(64).Set(65), + mask: New(128).Set(63).Set(64).Set(65), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "large gap", + src: New(256).Set(0).Set(100).Set(200), + mask: New(256).Set(0).Set(100).Set(200), + expected: New(8).Set(0).Set(1).Set(2), + }, + { + name: "extracting zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dst := New(tc.expected.Len()) + tc.src.ExtractTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship within the mask bits + deposited := New(tc.src.Len()) + dst.DepositTo(tc.mask, deposited) + + // Only bits selected by the mask should match between source and deposited + maskedSource := tc.src.Intersection(tc.mask) + maskedDeposited := deposited.Intersection(tc.mask) + + if !maskedSource.Equal(maskedDeposited) { + t.Error("DepositTo(ExtractTo(x,m),m) doesn't preserve masked source bits") + } + }) + } +} + +func TestBitSetDeposit(t *testing.T) { + // Property-based tests + const numTests = 1e4 + seed := time.Now().UnixNano() + rng := rand.New(rand.NewSource(seed)) + t.Logf("Seed: %d", seed) + + for i := 0; i < numTests; i++ { + // Create random bitsets + size := uint(rng.Intn(1024) + 64) // Random size between 64-1087 bits + src := New(size) + mask := New(size) + dst := New(size) + + // Set random bits + for j := 0; j < int(size/4); j++ { + src.Set(uint(rng.Intn(int(mask.Count() + 1)))) + mask.Set(uint(rng.Intn(int(size)))) + } + + // Deposit bits + src.DepositTo(mask, dst) + + // Test invariants + if dst.Count() > src.Count() { + t.Errorf("Case %d: result has more 1s than input", i) + } + + if (dst.Bytes()[0] &^ mask.Bytes()[0]) != 0 { + t.Errorf("Case %d: result has bits set outside of mask", i) + } + + // Extract bits back and verify + extracted := New(size) + dst.ExtractTo(mask, extracted) + maskBits := New(size) + for j := uint(0); j < mask.Count(); j++ { + maskBits.Set(j) + } + srcMasked := src.Clone() + srcMasked.InPlaceIntersection(maskBits) + if !extracted.Equal(srcMasked) { + t.Errorf("Case %d: ExtractTo(DepositTo(x,m),m) != x", i) + } + } + + // Keep existing test cases + testCases := []struct { + name string + src *BitSet // source bits (packed in low positions) + mask *BitSet // mask bits (positions to deposit into) + dst *BitSet // destination bits (initially set) + expected *BitSet // expected result + }{ + { + name: "sparse bits", + src: New(8).Set(0), // 0b01 + mask: New(8).Set(0).Set(5), // 0b100001 + expected: New(8).Set(0), // 0b000001 + }, + { + name: "masked off bits", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(8).Set(0).Set(2), // 0b101 + expected: New(8).Set(0).Set(2), // 0b101 + }, + { + name: "cross word boundary", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(63).Set(64), // bits across word boundary + expected: New(128).Set(63).Set(64), // bits deposited across boundary + }, + { + name: "large gaps", + src: New(8).Set(0).Set(1), // 0b11 + mask: New(128).Set(0).Set(100), // widely spaced bits + expected: New(128).Set(0).Set(100), // deposited into sparse positions + }, + { + name: "depositing zeros", + src: New(8), // 0b00 + mask: New(8).Set(0).Set(1).Set(2), // 0b111 + expected: New(8), // 0b000 + }, + { + name: "preserve unmasked bits", + src: New(8), // empty source + mask: New(8), // empty mask + dst: New(8).Set(1).Set(2).Set(3), // dst has some bits set + expected: New(8).Set(1).Set(2).Set(3), // should remain unchanged + }, + { + name: "preserve bits outside mask within word", + src: New(8).Set(0), // source has bit 0 set + mask: New(8).Set(1), // only depositing into bit 1 + dst: New(8).Set(0).Set(2).Set(3), // dst has bits 0,2,3 set + expected: New(8).Set(0).Set(1).Set(2).Set(3), // bits 0,2,3 should remain, bit 1 should be set + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var dst *BitSet + if tc.dst == nil { + dst = New(tc.expected.Len()) + } else { + dst = tc.dst.Clone() + } + tc.src.DepositTo(tc.mask, dst) + if !dst.Equal(tc.expected) { + t.Errorf("got %v, expected %v", dst, tc.expected) + } + + // Verify inverse relationship for set bits up to mask cardinality + extracted := New(tc.src.Len()) + dst.ExtractTo(tc.mask, extracted) + + if !extracted.Equal(tc.src) { + t.Error("ExtractTo(DepositTo(x,m),m) doesn't preserve source bits that were selected by mask") + } + }) + } +} + +func BenchmarkBitSetExtractDeposit(b *testing.B) { + sizes := []int{64, 256, 1024, 4096, 16384, 2 << 15} + rng := rand.New(rand.NewSource(42)) // fixed seed for reproducibility + + for _, size := range sizes { + // Create source with random bits + src := New(uint(size)) + for i := 0; i < size/4; i++ { // Set ~25% of bits + src.Set(uint(rng.Intn(size))) + } + + // Create mask with random bits + mask := New(uint(size)) + for i := 0; i < size/4; i++ { + mask.Set(uint(rng.Intn(size))) + } + + b.Run(fmt.Sprintf("size=%d/fn=ExtractTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.ExtractTo(mask, dst) + dst.ClearAll() + } + }) + + b.Run(fmt.Sprintf("size=%d/fn=DepositTo", size), func(b *testing.B) { + dst := New(uint(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + src.DepositTo(mask, dst) + dst.ClearAll() + } + }) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/popcnt_test.go b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/popcnt_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac62bc7e9fa87a6bbd8abc1d9a7451d23968bd55 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/frozen/popcnt_test.go @@ -0,0 +1,56 @@ +// This file tests the popcnt functions + +package bitset + +import ( + "testing" +) + +func TestPopcntSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + res := popcntSlice(s) + const l uint64 = 27 + if res != l { + t.Errorf("Wrong popcount %d != %d", res, l) + } +} + +func TestPopcntMaskSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntMaskSlice(s, m) + const l uint64 = 9 + if res != l { + t.Errorf("Wrong mask %d != %d", res, l) + } +} + +func TestPopcntAndSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntAndSlice(s, m) + const l uint64 = 18 + if res != l { + t.Errorf("Wrong And %d != %d", res, l) + } +} + +func TestPopcntOrSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntOrSlice(s, m) + const l uint64 = 50 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} + +func TestPopcntXorSlice(t *testing.T) { + s := []uint64{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + m := []uint64{31, 37, 41, 43, 47, 53, 59, 61, 67, 71} + res := popcntXorSlice(s, m) + const l uint64 = 32 + if res != l { + t.Errorf("Wrong OR %d != %d", res, l) + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/grade.py b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/manifest.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..025837faee8000809db0b399af146dcd9cafc4ab --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/manifest.json @@ -0,0 +1,1049 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestStringLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEmptyBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestZeroValueBitSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetHuge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestLenIsNumberOfBitsNotBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetIsClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExtendOnBoundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExceedCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestExpand" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetAndGet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIterate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetMany" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAppendTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAsSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestChain" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestOutOfBoundsClose" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCount2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullTest" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNullCount" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicMustNew" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicUnionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicIntersectionCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicSymmetricDifferenceCompareNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicComplementBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAnytBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicNonetBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPanicAlltBNil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShrink" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAtWithSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInsertAt" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNone" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestEqual" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceUnion" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInplaceIntersection" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestInPlaceSymmetricDifference" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestComplement" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/empty_vs_non-empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/non-empty_vs_empty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_shorter,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_subset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_equal" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_superset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIsSuperSet/set_is_longer,_neither" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDumpAsBits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalBinaryByLittleEndian" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/value" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSON/pointer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONWithTrailingData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestMarshalUnmarshalJSONByStdEncoding" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSafeSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetBitsetFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestIssue116" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWords" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBytes" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWordsNeededLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestTestTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearTooLong" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestClearAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestRankSelect" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlip" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestFlipRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyUnaligned" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestCopyFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestNextSetError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitStrings" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestDeleteWithBitSetInstance" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWriteTo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestReadFrom/3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/nil" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_10" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_63" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_65" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestSetAll/length_640" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/shift_to_full_page" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftLeft/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_change" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/no_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_page_split" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_page_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/with_extension" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/full_shift" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestShiftRight/remove_all" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/slightly_offset_results" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/first_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/third_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/way_off_the_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/split_between_two_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/partly_off_edge" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestWord/skip_one_nibble" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousSet/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@2" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@3" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@4" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@5" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@100" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@121" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@0#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@120#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPreviousClear/@1024#01" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/empty_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/invalid_range" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/single_word_full" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/multiple_words" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetOnesBetween/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPext" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPdep" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/single_bit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/two_sequential_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/large_gap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetExtract/extracting_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/sparse_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/masked_off_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/cross_word_boundary" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/large_gaps" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/depositing_zeros" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_unmasked_bits" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestBitSetDeposit/preserve_bits_outside_mask_within_word" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntMaskSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntAndSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntOrSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "TestPopcntXorSlice" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/bits-and-blooms/bitset", + "test": "ExampleBitSet_Len" + } + ], + "frozen_files": { + "bitset_benchmark_test.go": { + "mode": 420, + "sha256": "790dd661ee439e4f930b485b6038858f36cd673c11c3eaf1217c2fe1e4d9b1ad" + }, + "bitset_iter_test.go": { + "mode": 420, + "sha256": "69ddef9f967c051c10bcfb1445ce3580810e965a2456f23379030f9db1783fa3" + }, + "bitset_test.go": { + "mode": 420, + "sha256": "36810260202d7304c38dab2dfe634bf786d75999337144d1f73e04236645fe1f" + }, + "popcnt_test.go": { + "mode": 420, + "sha256": "3b598125af8ba5b207052ddb406851157e79f5a36640e080467f170861f90cd5" + } + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/test.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/delete-tests.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/original-bug.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/stale-reward.sh b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/openenv.json b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..ae8de16bd7858d16f8211b298150af5fa4a4e957 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__5mu4gd7j/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "ec5a1cb1141b696c779210efbe5a088dbb60451ccadba0996032e8fbf25bef7d", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/Dockerfile b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0517f6d49dfeebaf999a70890fc63a50015939 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-a91d078628985ab5-starter-v1@sha256:f13aa4ff52b15391e35fbe1d0ce02c59fbee52539ff28c2059045cc80c7ff8d9 +WORKDIR /testbed diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/FUNDING.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..19183fed9955dcb135acfdc194fe1b5189670d30 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# You can add one username per supported platform and one custom link +patreon: # Replace with your Patreon username +open_collective: # Replace with your Open Collective username +ko_fi: # Replace with your Ko-fi username +custom: https://donate.mcc.org/ # Replace with your custom donation URL diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/SECURITY.md b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9c9754136b3ff1d23e93e0264cd9c8422e172328 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Security updates are applied only to the latest release. + +## Reporting a Vulnerability + +If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. + +Please use the following contact information for reporting a vulnerability: + +- [Daniel Lemire](https://github.com/lemire) - [daniel@lemire.me](mailto:daniel@lemire.me) + +In your report, please include: + +- A description of the vulnerability and its impact +- How to reproduce the it +- Affected versions + +This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/dependabot.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..322a2b6ea8f9f6a0dbb408d4b810c40bcd82b1f7 --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + github-actions: + patterns: + - "*" diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.gitignore b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5c204d28b0e369e444489127428a98fb948d443e --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +target diff --git a/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.travis.yml b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..094aa5ce070ccbb2e129761eaf516477268a055f --- /dev/null +++ b/tasks/bits-and-blooms__bitset.167865a2.lm_rewrite__ahkutdgr/environment/source/.travis.yml @@ -0,0 +1,37 @@ +language: go + +sudo: false + +branches: + except: + - release + +branches: + only: + - master + - travis + +go: + - "1.11.x" + - tip + +matrix: + allow_failures: + - go: tip + +before_install: + - if [ -n "$GH_USER" ]; then git config --global github.user ${GH_USER}; fi; + - if [ -n "$GH_TOKEN" ]; then git config --global github.token ${GH_TOKEN}; fi; + - go get github.com/mattn/goveralls + +before_script: + - make deps + +script: + - make qa + +after_failure: + - cat ./target/test/report.xml + +after_success: + - if [ "$TRAVIS_GO_VERSION" = "1.11.1" ]; then $HOME/gopath/bin/goveralls -covermode=count -coverprofile=target/report/coverage.out -service=travis-ci; fi;