instance_id
stringlengths
12
57
base_commit
stringlengths
40
40
created_at
stringdate
2015-01-06 14:05:07
2025-04-29 17:56:51
environment_setup_commit
stringlengths
40
40
hints_text
stringlengths
0
158k
patch
stringlengths
261
20.8k
problem_statement
stringlengths
11
52.5k
repo
stringlengths
7
53
test_patch
stringlengths
280
206k
meta
dict
version
stringclasses
463 values
install_config
dict
requirements
stringlengths
93
34k
environment
stringlengths
772
20k
FAIL_TO_PASS
sequencelengths
1
856
FAIL_TO_FAIL
sequencelengths
0
536
PASS_TO_PASS
sequencelengths
0
7.87k
PASS_TO_FAIL
sequencelengths
0
92
license_name
stringclasses
35 values
__index_level_0__
int64
11
21.4k
num_tokens_patch
int64
103
4.99k
before_filepaths
sequencelengths
0
14
tobymao__sqlglot-3392
e7021df397a1dc5e726d1e391ef6428a3190856d
2024-05-01 16:14:15
d1b4f1f256cd772bec366d6bf13d9589e1fdfc4b
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py index 085063da..770dad2f 100644 --- a/sqlglot/dialects/postgres.py +++ b/sqlglot/dialects/postgres.py @@ -266,24 +266,25 @@ class Postgres(Dialect): "BIGSERIAL": TokenType.BIGSERIAL, "CHARACTER VARYING": TokenType.VARCHAR, "CONSTRAINT TRIGGER": TokenType.COMMAND, + "CSTRING": TokenType.PSEUDO_TYPE, "DECLARE": TokenType.COMMAND, "DO": TokenType.COMMAND, "EXEC": TokenType.COMMAND, "HSTORE": TokenType.HSTORE, + "INT8": TokenType.BIGINT, "JSONB": TokenType.JSONB, "MONEY": TokenType.MONEY, + "NAME": TokenType.NAME, + "OID": TokenType.OBJECT_IDENTIFIER, + "ONLY": TokenType.ONLY, + "OPERATOR": TokenType.OPERATOR, "REFRESH": TokenType.COMMAND, "REINDEX": TokenType.COMMAND, "RESET": TokenType.COMMAND, "REVOKE": TokenType.COMMAND, "SERIAL": TokenType.SERIAL, "SMALLSERIAL": TokenType.SMALLSERIAL, - "NAME": TokenType.NAME, "TEMP": TokenType.TEMPORARY, - "CSTRING": TokenType.PSEUDO_TYPE, - "OID": TokenType.OBJECT_IDENTIFIER, - "ONLY": TokenType.ONLY, - "OPERATOR": TokenType.OPERATOR, "REGCLASS": TokenType.OBJECT_IDENTIFIER, "REGCOLLATION": TokenType.OBJECT_IDENTIFIER, "REGCONFIG": TokenType.OBJECT_IDENTIFIER,
[BUG]In PostgreSQL, int8 represents the 64-bit integer type, not tinyint **Fully reproducible code snippet** ```python3 import sqlglot if __name__ == '__main__': sql = """create table a_table ( column_id int8 not null constraint a_table_pk primary key, column_2 date, column_3 varchar(2000), column_4 int2, column_5 int4 ); """ expressions = sqlglot.parse(sql, dialect="postgres") expression = expressions[0] print(expression.sql()) ``` output ```txt CREATE TABLE a_table (column_id **TINYINT** NOT NULL CONSTRAINT a_table_pk PRIMARY KEY, column_2 DATE, column_3 VARCHAR(2000), column_4 SMALLINT, column_5 INT) ``` "int8" being mistranslated as "tinyint" **Official Documentation** postgresql 10 official document: [https://www.postgresql.org/docs/10/datatype.html#DATATYPE-TABLE](https://www.postgresql.org/docs/10/datatype.html#DATATYPE-TABLE)
tobymao/sqlglot
diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py index 85701025..7cfba94a 100644 --- a/tests/dialects/test_postgres.py +++ b/tests/dialects/test_postgres.py @@ -320,6 +320,10 @@ class TestPostgres(Validator): "SELECT SUBSTRING('afafa' for 1)", "SELECT SUBSTRING('afafa' FROM 1 FOR 1)", ) + self.validate_identity( + "CAST(x AS INT8)", + "CAST(x AS BIGINT)", + ) self.validate_all( "CREATE TABLE t (c INT)",
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
23.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.3.2 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@e7021df397a1dc5e726d1e391ef6428a3190856d#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.3.2 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_postgres.py::TestPostgres::test_postgres" ]
[]
[ "tests/dialects/test_postgres.py::TestPostgres::test_array_offset", "tests/dialects/test_postgres.py::TestPostgres::test_bool_or", "tests/dialects/test_postgres.py::TestPostgres::test_ddl", "tests/dialects/test_postgres.py::TestPostgres::test_operator", "tests/dialects/test_postgres.py::TestPostgres::test_regexp_binary", "tests/dialects/test_postgres.py::TestPostgres::test_string_concat", "tests/dialects/test_postgres.py::TestPostgres::test_unnest", "tests/dialects/test_postgres.py::TestPostgres::test_unnest_json_array", "tests/dialects/test_postgres.py::TestPostgres::test_variance" ]
[]
MIT License
18,313
391
[ "sqlglot/dialects/postgres.py" ]
tobymao__sqlglot-3394
641b296017591b65ffc223d28b37e51886789ca7
2024-05-01 17:39:01
d1b4f1f256cd772bec366d6bf13d9589e1fdfc4b
diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py index 2e04aca3..cc1d6208 100644 --- a/sqlglot/dialects/dialect.py +++ b/sqlglot/dialects/dialect.py @@ -903,9 +903,7 @@ def regexp_extract_sql(self: Generator, expression: exp.RegexpExtract) -> str: def regexp_replace_sql(self: Generator, expression: exp.RegexpReplace) -> str: - bad_args = list( - filter(expression.args.get, ("position", "occurrence", "parameters", "modifiers")) - ) + bad_args = list(filter(expression.args.get, ("position", "occurrence", "modifiers"))) if bad_args: self.unsupported(f"REGEXP_REPLACE does not support the following arg(s): {bad_args}") diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py index 770dad2f..bdc42186 100644 --- a/sqlglot/dialects/postgres.py +++ b/sqlglot/dialects/postgres.py @@ -32,7 +32,7 @@ from sqlglot.dialects.dialect import ( trim_sql, ts_or_ds_add_cast, ) -from sqlglot.helper import seq_get +from sqlglot.helper import is_int, seq_get from sqlglot.parser import binary_range_parser from sqlglot.tokens import TokenType @@ -204,6 +204,29 @@ def _json_extract_sql( return _generate +def _build_regexp_replace(args: t.List) -> exp.RegexpReplace: + # The signature of REGEXP_REPLACE is: + # regexp_replace(source, pattern, replacement [, start [, N ]] [, flags ]) + # + # Any one of `start`, `N` and `flags` can be column references, meaning that + # unless we can statically see that the last argument is a non-integer string + # (eg. not '0'), then it's not possible to construct the correct AST + if len(args) > 3: + last = args[-1] + if not is_int(last.name): + if not last.type or last.is_type(exp.DataType.Type.UNKNOWN, exp.DataType.Type.NULL): + from sqlglot.optimizer.annotate_types import annotate_types + + last = annotate_types(last) + + if last.is_type(*exp.DataType.TEXT_TYPES): + regexp_replace = exp.RegexpReplace.from_arg_list(args[:-1]) + regexp_replace.set("modifiers", last) + return regexp_replace + + return exp.RegexpReplace.from_arg_list(args) + + class Postgres(Dialect): INDEX_OFFSET = 1 TYPED_DIVISION = True @@ -321,6 +344,7 @@ class Postgres(Dialect): "MAKE_TIME": exp.TimeFromParts.from_arg_list, "MAKE_TIMESTAMP": exp.TimestampFromParts.from_arg_list, "NOW": exp.CurrentTimestamp.from_arg_list, + "REGEXP_REPLACE": _build_regexp_replace, "TO_CHAR": build_formatted_time(exp.TimeToStr, "postgres"), "TO_TIMESTAMP": _build_to_timestamp, "UNNEST": exp.Explode.from_arg_list, diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index af1e1bc0..5005519e 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -5567,7 +5567,6 @@ class RegexpReplace(Func): "replacement": False, "position": False, "occurrence": False, - "parameters": False, "modifiers": False, } diff --git a/sqlglot/lineage.py b/sqlglot/lineage.py index f4a3dec5..5c28e97d 100644 --- a/sqlglot/lineage.py +++ b/sqlglot/lineage.py @@ -8,6 +8,7 @@ from dataclasses import dataclass, field from sqlglot import Schema, exp, maybe_parse from sqlglot.errors import SqlglotError from sqlglot.optimizer import Scope, build_scope, find_all_in_scope, normalize_identifiers, qualify +from sqlglot.optimizer.scope import ScopeType if t.TYPE_CHECKING: from sqlglot.dialects.dialect import DialectType @@ -255,7 +256,12 @@ def to_node( source = scope.sources.get(table) if isinstance(source, Scope): - selected_node, _ = scope.selected_sources.get(table, (None, None)) + reference_node_name = None + if source.scope_type == ScopeType.DERIVED_TABLE and table not in source_names: + reference_node_name = table + elif source.scope_type == ScopeType.CTE: + selected_node, _ = scope.selected_sources.get(table, (None, None)) + reference_node_name = selected_node.name if selected_node else None # The table itself came from a more specific scope. Recurse into that one using the unaliased column name. to_node( c.name, @@ -264,7 +270,7 @@ def to_node( scope_name=table, upstream=node, source_name=source_names.get(table) or source_name, - reference_node_name=selected_node.name if selected_node else None, + reference_node_name=reference_node_name, trim_selects=trim_selects, ) else:
sqlglot removes options from the regexp_replace function Hey, I have a problem. Sqlglot removes options from the regexp_replace function when translating from a Postgres script to a duckdb one. **Fully reproducible code snippet** ``` sqlglot.transpile("select regexp_replace('mr .', '[^a-zA-Z]', '', 'g')", read="postgres", write="duckdb")[0] "SELECT REGEXP_REPLACE('mr .', '[^a-zA-Z]', '')" ``` **Official Documentation** DuckdDb regexp_replace https://duckdb.org/docs/sql/functions/regular_expressions.html#using-regexp_replace Postgres: https://www.postgresql.org/docs/current/functions-matching.html#:~:text=The%20regexp_replace%20function%20provides%20substitution,be%20given%20in%20any%20case.)
tobymao/sqlglot
diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py index 7cfba94a..fa8cf60c 100644 --- a/tests/dialects/test_postgres.py +++ b/tests/dialects/test_postgres.py @@ -325,6 +325,13 @@ class TestPostgres(Validator): "CAST(x AS BIGINT)", ) + self.validate_all( + "SELECT REGEXP_REPLACE('mr .', '[^a-zA-Z]', '', 'g')", + write={ + "duckdb": "SELECT REGEXP_REPLACE('mr .', '[^a-zA-Z]', '', 'g')", + "postgres": "SELECT REGEXP_REPLACE('mr .', '[^a-zA-Z]', '', 'g')", + }, + ) self.validate_all( "CREATE TABLE t (c INT)", read={ diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py index a328940d..a6c933a8 100644 --- a/tests/dialects/test_snowflake.py +++ b/tests/dialects/test_snowflake.py @@ -1580,7 +1580,7 @@ FROM persons AS p, LATERAL FLATTEN(input => p.c, path => 'contact') AS _flattene "REGEXP_REPLACE(subject, pattern, replacement, position, occurrence, parameters)", write={ "bigquery": "REGEXP_REPLACE(subject, pattern, replacement)", - "duckdb": "REGEXP_REPLACE(subject, pattern, replacement)", + "duckdb": "REGEXP_REPLACE(subject, pattern, replacement, parameters)", "hive": "REGEXP_REPLACE(subject, pattern, replacement)", "snowflake": "REGEXP_REPLACE(subject, pattern, replacement, position, occurrence, parameters)", "spark": "REGEXP_REPLACE(subject, pattern, replacement, position)", diff --git a/tests/test_lineage.py b/tests/test_lineage.py index cbadf7bb..3e17f956 100644 --- a/tests/test_lineage.py +++ b/tests/test_lineage.py @@ -300,6 +300,7 @@ class TestLineage(unittest.TestCase): self.assertEqual(node.name, "a") node = node.downstream[0] self.assertEqual(node.name, "cte.a") + self.assertEqual(node.reference_node_name, "cte") node = node.downstream[0] self.assertEqual(node.name, "z.a") @@ -338,6 +339,27 @@ class TestLineage(unittest.TestCase): node = a.downstream[0] self.assertEqual(node.name, "foo.a") + # Select from derived table + node = lineage( + "a", + "SELECT a FROM (SELECT a FROM x) subquery", + ) + self.assertEqual(node.name, "a") + self.assertEqual(len(node.downstream), 1) + node = node.downstream[0] + self.assertEqual(node.name, "subquery.a") + self.assertEqual(node.reference_node_name, "subquery") + + node = lineage( + "a", + "SELECT a FROM (SELECT a FROM x)", + ) + self.assertEqual(node.name, "a") + self.assertEqual(len(node.downstream), 1) + node = node.downstream[0] + self.assertEqual(node.name, "_q_0.a") + self.assertEqual(node.reference_node_name, "_q_0") + def test_lineage_cte_union(self) -> None: query = """ WITH dataset AS (
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 4 }
23.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 coverage==7.8.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.3.2 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@641b296017591b65ffc223d28b37e51886789ca7#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - coverage==7.8.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.3.2 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_postgres.py::TestPostgres::test_postgres", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_replace", "tests/test_lineage.py::TestLineage::test_subquery" ]
[]
[ "tests/dialects/test_postgres.py::TestPostgres::test_array_offset", "tests/dialects/test_postgres.py::TestPostgres::test_bool_or", "tests/dialects/test_postgres.py::TestPostgres::test_ddl", "tests/dialects/test_postgres.py::TestPostgres::test_operator", "tests/dialects/test_postgres.py::TestPostgres::test_regexp_binary", "tests/dialects/test_postgres.py::TestPostgres::test_string_concat", "tests/dialects/test_postgres.py::TestPostgres::test_unnest", "tests/dialects/test_postgres.py::TestPostgres::test_unnest_json_array", "tests/dialects/test_postgres.py::TestPostgres::test_variance", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_describe_table", "tests/dialects/test_snowflake.py::TestSnowflake::test_flatten", "tests/dialects/test_snowflake.py::TestSnowflake::test_historical_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_snowflake.py::TestSnowflake::test_minus", "tests/dialects/test_snowflake.py::TestSnowflake::test_null_treatment", "tests/dialects/test_snowflake.py::TestSnowflake::test_parse_like_any", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_substr", "tests/dialects/test_snowflake.py::TestSnowflake::test_sample", "tests/dialects/test_snowflake.py::TestSnowflake::test_semi_structured_types", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_columns", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_imported_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_objects", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_primary_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_schemas", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_sequences", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_tables", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_unique_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_users", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_views", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_snowflake.py::TestSnowflake::test_staged_files", "tests/dialects/test_snowflake.py::TestSnowflake::test_storage_integration", "tests/dialects/test_snowflake.py::TestSnowflake::test_stored_procedures", "tests/dialects/test_snowflake.py::TestSnowflake::test_swap", "tests/dialects/test_snowflake.py::TestSnowflake::test_table_literal", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/dialects/test_snowflake.py::TestSnowflake::test_try_cast", "tests/dialects/test_snowflake.py::TestSnowflake::test_user_defined_functions", "tests/dialects/test_snowflake.py::TestSnowflake::test_values", "tests/test_lineage.py::TestLineage::test_ddl_lineage", "tests/test_lineage.py::TestLineage::test_lineage", "tests/test_lineage.py::TestLineage::test_lineage_cte_name_appears_in_schema", "tests/test_lineage.py::TestLineage::test_lineage_cte_union", "tests/test_lineage.py::TestLineage::test_lineage_external_col", "tests/test_lineage.py::TestLineage::test_lineage_lateral_flatten", "tests/test_lineage.py::TestLineage::test_lineage_normalize", "tests/test_lineage.py::TestLineage::test_lineage_source_union", "tests/test_lineage.py::TestLineage::test_lineage_source_with_cte", "tests/test_lineage.py::TestLineage::test_lineage_source_with_star", "tests/test_lineage.py::TestLineage::test_lineage_sql_with_cte", "tests/test_lineage.py::TestLineage::test_lineage_union", "tests/test_lineage.py::TestLineage::test_lineage_values", "tests/test_lineage.py::TestLineage::test_select_star", "tests/test_lineage.py::TestLineage::test_trim", "tests/test_lineage.py::TestLineage::test_unnest" ]
[]
MIT License
18,314
1,276
[ "sqlglot/dialects/dialect.py", "sqlglot/dialects/postgres.py", "sqlglot/expressions.py", "sqlglot/lineage.py" ]
feder-observatory__stellarphot-315
a7415f6222ef2c331ca5f228fbf245ed68d054d9
2024-05-01 19:09:28
740b6deaa7877834eafeffb2f1270540d93d10ae
codecov-commenter: ## [Codecov](https://app.codecov.io/gh/feder-observatory/stellarphot/pull/315?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feder-observatory) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 73.90%. Comparing base [(`d901d65`)](https://app.codecov.io/gh/feder-observatory/stellarphot/commit/d901d65473ae1f34f00ef9b7dc88c655df7dc798?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feder-observatory) to head [(`955e174`)](https://app.codecov.io/gh/feder-observatory/stellarphot/pull/315?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feder-observatory). > Report is 4 commits behind head on main. <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #315 +/- ## ========================================== + Coverage 73.86% 73.90% +0.03% ========================================== Files 27 27 Lines 3409 3414 +5 ========================================== + Hits 2518 2523 +5 Misses 891 891 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/feder-observatory/stellarphot/pull/315?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feder-observatory). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feder-observatory).
diff --git a/stellarphot/settings/custom_widgets.py b/stellarphot/settings/custom_widgets.py index 1a26f59..e50a9c3 100644 --- a/stellarphot/settings/custom_widgets.py +++ b/stellarphot/settings/custom_widgets.py @@ -224,6 +224,9 @@ class ChooseOrMakeNew(ipw.VBox): # Update the current state of the widget self._editing = True + # Enable the revert button so that the user can cancel the edit + self._item_widget.savebuttonbar.bn_revert.disabled = False + def _set_disable_state_nested_models(self, top, value): """ When a one model contains another and the top-level model widget @@ -297,9 +300,26 @@ class ChooseOrMakeNew(ipw.VBox): # Make sure the edit button is displayed self._edit_button.layout.display = "flex" + def revert_to_saved_value(): + """ + Revert the widget to the saved value and end editing. + + This should only apply while editing. If you are making a new + item you can either select a different item (if there are any) or + you really need to make a new one. + """ + if self._editing: + # We have a selection so we need to stop editing... + self._editing = False + + # ...and trigger the selection handler. + self._handle_selection({"new": self._choose_existing.value}) + # This is the mechanism for adding callbacks to the save button. new_widget.savebuttonbar.fns_onsave_add_action(saver) new_widget.savebuttonbar.fns_onsave_add_action(update_choices_and_select_new) + new_widget.savebuttonbar.fns_onrevert_add_action(revert_to_saved_value) + return new_widget, new_widget.value.copy() def _handle_confirmation(self):
Need way to cancel an edit of a camera, etc Right now there is no easy way to stop editing something if you decide you don't want to make any changes. The obvious way to do that is with the "Revert" button (the yellow counter-clockwise arrow button). Clicking on that button should set the UI to the same state it would be in if you had selected that item.
feder-observatory/stellarphot
diff --git a/stellarphot/settings/tests/test_custom_widgets.py b/stellarphot/settings/tests/test_custom_widgets.py index 153fd3b..d26f767 100644 --- a/stellarphot/settings/tests/test_custom_widgets.py +++ b/stellarphot/settings/tests/test_custom_widgets.py @@ -331,6 +331,76 @@ class TestChooseOrMakeNew: # The save button should be disabled assert choose_or_make_new._item_widget.savebuttonbar.bn_save.disabled + def test_revert_button_is_enabled_after_clicking_edit(self, tmp_path): + # The revert button should be enabled after clicking the edit button so + # the user can cancel the edit. + saved = SavedSettings(_testing_path=tmp_path) + camera = Camera(**TEST_CAMERA_VALUES) + saved.add_item(camera) + + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) + # Simulate a click on the edit button... + choose_or_make_new._edit_button.click() + + # The revert button should be enabled + assert not choose_or_make_new._item_widget.savebuttonbar.bn_revert.disabled + + def test_clicking_revert_button_cancels_edit(self, tmp_path): + # Clicking the revert button should cancel the edit + saved = SavedSettings(_testing_path=tmp_path) + camera = Camera(**TEST_CAMERA_VALUES) + saved.add_item(camera) + + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) + # Simulate a click on the edit button... + choose_or_make_new._edit_button.click() + + # Simulate a click on the revert button... + choose_or_make_new._item_widget.savebuttonbar.bn_revert.click() + + # The camera should not have been changed + assert choose_or_make_new._item_widget.value == TEST_CAMERA_VALUES + + # The edit button should be displayed + assert choose_or_make_new._edit_button.layout.display != "none" + + # We should not be in editing mode anymore + assert not choose_or_make_new._editing + + def test_revert_button_remains_enabled_with_invalid_value_and_actually_reverts( + self, tmp_path + ): + # The revert button should remain enabled if the value is invalid and reverting + # should actually revert the value. + saved = SavedSettings(_testing_path=tmp_path) + camera = Camera(**TEST_CAMERA_VALUES) + saved.add_item(camera) + + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) + # Simulate a click on the edit button... + choose_or_make_new._edit_button.click() + + # Set an invalid value + choose_or_make_new._item_widget.di_widgets["name"].value = "" + + # unsaved_changes should be true + assert choose_or_make_new._item_widget.savebuttonbar.unsaved_changes + + # Make sure the change is really there + assert choose_or_make_new._item_widget.value != TEST_CAMERA_VALUES + + # The revert button should be enabled + assert not choose_or_make_new._item_widget.savebuttonbar.bn_revert.disabled + + # Save should still be disabled + assert choose_or_make_new._item_widget.savebuttonbar.bn_save.disabled + + # Click the revert button + choose_or_make_new._item_widget.savebuttonbar.bn_revert.click() + + # The camera should not have been changed + assert choose_or_make_new._item_widget.value == TEST_CAMERA_VALUES + class TestConfirm: def test_initial_value(self):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.10", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aggdraw==1.3.19 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 annotated-types==0.7.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asciitree==0.3.3 astropy==6.1.7 astropy-iers-data==0.2025.3.31.0.36.18 astropy_healpix==1.1.2 astroquery==0.4.10 astroscrappy==1.2.0 astrowidgets==0.3.0 asttokens==3.0.0 async-lru==2.0.5 async-timeout==5.0.1 attrs==25.3.0 babel==2.17.0 backports.tarfile==1.2.0 beautifulsoup4==4.13.3 black==25.1.0 bleach==6.2.0 Bottleneck==1.4.2 bqplot==0.12.44 bracex==2.5.post1 cachetools==5.5.2 ccdproc==2.4.3 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.1 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2025.3.0 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 distlib==0.3.9 et_xmlfile==2.0.0 exceptiongroup==1.2.2 executing==2.2.0 fasteners==0.19 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 gast==0.4.0 ginga==5.2.0 h11==0.14.0 html5lib==1.1 httpcore==1.0.7 httpx==0.28.1 hypothesis==6.130.5 identify==2.6.9 idna==3.10 imageio==2.37.0 immutables==0.21 importlib_metadata==8.6.1 iniconfig==2.1.0 ipyautoui==0.7.24 ipydatagrid==1.4.0 ipyevents==2.0.2 ipyfilechooser==0.6.0 ipykernel==6.29.5 ipython==8.34.0 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jedi==0.19.2 jeepney==0.9.0 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonref==1.1.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_app_launcher==0.3.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 keyring==25.6.0 kiwisolver==1.4.8 lazy_loader==0.4 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.10.1 matplotlib-inline==0.1.7 mistune==3.1.3 more-itertools==10.6.0 multidict==6.2.0 mypy-extensions==1.0.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 networkx==3.4.2 nodeenv==1.9.1 notebook_shim==0.2.4 numcodecs==0.13.1 numpy==2.2.4 openpyxl==3.1.5 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pathspec==0.12.1 pexpect==4.9.0 photutils==2.0.2 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 puremagic==1.28 py2vega==0.6.1 pycparser==2.22 pydantic==2.11.1 pydantic-extra-types==2.10.3 pydantic-settings==2.8.1 pydantic_core==2.33.0 pyerfa==2.0.1.5 Pygments==2.19.1 pyparsing==3.2.3 pyproject-api==1.9.0 pytest==8.3.5 pytest-arraydiff==0.6.1 pytest-astropy==0.11.0 pytest-astropy-header==0.2.2 pytest-cov==6.0.0 pytest-doctestplus==1.4.0 pytest-filter-subpackage==0.2.0 pytest-mock==3.14.0 pytest-remotedata==0.4.1 python-dateutil==2.9.0.post0 python-dotenv==1.1.0 python-json-logger==3.3.0 pytz==2025.2 pyvo==1.6.1 PyYAML==6.0.2 pyzmq==26.3.0 QtPy==2.4.3 referencing==0.36.2 reproject==0.14.1 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 ruff==0.11.2 scikit-image==0.25.2 scipy==1.15.2 SecretStorage==3.3.3 Send2Trash==1.8.3 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 sortedcontainers==2.4.0 soupsieve==2.6 stack-data==0.6.3 -e git+https://github.com/feder-observatory/stellarphot.git@a7415f6222ef2c331ca5f228fbf245ed68d054d9#egg=stellarphot stringcase==1.2.0 terminado==0.18.1 tifffile==2025.3.30 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tox==4.25.0 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 virtualenv==20.29.3 wcmatch==10.0 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 yarl==1.18.3 zarr==2.18.3 zipp==3.21.0
name: stellarphot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py310h06a4308_0 - python=3.10.16=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py310h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py310h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aggdraw==1.3.19 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - annotated-types==0.7.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asciitree==0.3.3 - astropy==6.1.7 - astropy-healpix==1.1.2 - astropy-iers-data==0.2025.3.31.0.36.18 - astroquery==0.4.10 - astroscrappy==1.2.0 - astrowidgets==0.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - async-timeout==5.0.1 - attrs==25.3.0 - babel==2.17.0 - backports-tarfile==1.2.0 - beautifulsoup4==4.13.3 - black==25.1.0 - bleach==6.2.0 - bottleneck==1.4.2 - bqplot==0.12.44 - bracex==2.5.post1 - cachetools==5.5.2 - ccdproc==2.4.3 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.1 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2025.3.0 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - distlib==0.3.9 - et-xmlfile==2.0.0 - exceptiongroup==1.2.2 - executing==2.2.0 - fasteners==0.19 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - gast==0.4.0 - ginga==5.2.0 - h11==0.14.0 - html5lib==1.1 - httpcore==1.0.7 - httpx==0.28.1 - hypothesis==6.130.5 - identify==2.6.9 - idna==3.10 - imageio==2.37.0 - immutables==0.21 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipyautoui==0.7.24 - ipydatagrid==1.4.0 - ipyevents==2.0.2 - ipyfilechooser==0.6.0 - ipykernel==6.29.5 - ipython==8.34.0 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jedi==0.19.2 - jeepney==0.9.0 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonref==1.1.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-app-launcher==0.3.2 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - keyring==25.6.0 - kiwisolver==1.4.8 - lazy-loader==0.4 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.10.1 - matplotlib-inline==0.1.7 - mistune==3.1.3 - more-itertools==10.6.0 - multidict==6.2.0 - mypy-extensions==1.0.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - networkx==3.4.2 - nodeenv==1.9.1 - notebook-shim==0.2.4 - numcodecs==0.13.1 - numpy==2.2.4 - openpyxl==3.1.5 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pathspec==0.12.1 - pexpect==4.9.0 - photutils==2.0.2 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - puremagic==1.28 - py2vega==0.6.1 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pydantic-extra-types==2.10.3 - pydantic-settings==2.8.1 - pyerfa==2.0.1.5 - pygments==2.19.1 - pyparsing==3.2.3 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-arraydiff==0.6.1 - pytest-astropy==0.11.0 - pytest-astropy-header==0.2.2 - pytest-cov==6.0.0 - pytest-doctestplus==1.4.0 - pytest-filter-subpackage==0.2.0 - pytest-mock==3.14.0 - pytest-remotedata==0.4.1 - python-dateutil==2.9.0.post0 - python-dotenv==1.1.0 - python-json-logger==3.3.0 - pytz==2025.2 - pyvo==1.6.1 - pyyaml==6.0.2 - pyzmq==26.3.0 - qtpy==2.4.3 - referencing==0.36.2 - reproject==0.14.1 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - ruff==0.11.2 - scikit-image==0.25.2 - scipy==1.15.2 - secretstorage==3.3.3 - send2trash==1.8.3 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - sortedcontainers==2.4.0 - soupsieve==2.6 - stack-data==0.6.3 - stellarphot==1.3.10.dev734+ga7415f6 - stringcase==1.2.0 - terminado==0.18.1 - tifffile==2025.3.30 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tox==4.25.0 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - virtualenv==20.29.3 - wcmatch==10.0 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - yarl==1.18.3 - zarr==2.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/stellarphot
[ "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_revert_button_is_enabled_after_clicking_edit", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_clicking_revert_button_cancels_edit", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_revert_button_remains_enabled_with_invalid_value_and_actually_reverts" ]
[]
[ "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation_without_type_raises_error", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation_unknown_item_type_raises_error", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[camera]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[observatory]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[passband_map]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[Camera]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[PassbandMap]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[Observatory]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_initial_configuration_with_no_items", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_makes_a_new_item", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[camera-setting0]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[observatory-setting1]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[passband_map-setting2]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_requires_confirmation", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_item_saved_after_confirm", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_item_not_saved_after_cancel", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_selecting_make_new_as_selection_works", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_choosing_different_item_updates_display", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_passband_map_buttons_are_disabled_or_enabled", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_passband_map", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_no_edit_button_when_there_are_no_items", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_button_returns_after_making_new_item", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_save_button_disabled_when_no_changes", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_initial_value", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_initial_display", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_message", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_widget_structure", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_show[None]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_show[other_widget1]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[None-yes]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[None-no]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[other_widget1-yes]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[other_widget1-no]" ]
[]
BSD 3-Clause "New" or "Revised" License
18,315
434
[ "stellarphot/settings/custom_widgets.py" ]
fitbenchmarking__fitbenchmarking-1279
0b3ea8a82a1d74db4f5859927347a8b15628a063
2024-05-02 00:03:08
7fcd2778e2b9a7a86ce36c96078e3f6712d5cd12
coveralls: [![Coverage Status](https://coveralls.io/builds/67254785/badge)](https://coveralls.io/builds/67254785) coverage: 90.82% (-0.01%) from 90.832% when pulling **b1a7dabddae3df01c937185e22f0d82c9bc8e269 on RabiyaF:1245-error-bars** into **76eb8d7dd3c0c9c108768946cb2e82e4d7dfab8d on fitbenchmarking:master**.
diff --git a/fitbenchmarking/results_processing/plots.py b/fitbenchmarking/results_processing/plots.py index a2350fa8..da108f4a 100644 --- a/fitbenchmarking/results_processing/plots.py +++ b/fitbenchmarking/results_processing/plots.py @@ -18,32 +18,36 @@ class Plot: """ Class providing plotting functionality. """ - data_marker = {"symbol": "x", - "color": "black"} - best_fit_line = {"dash": "dot", - "color": '#6699ff'} - legend_options = {"yanchor": "top", - "y": 0.99, - "xanchor": "left", - "x": 0.01, - "bgcolor": 'rgba(0,0,0,0.1)'} - summary_best_plot_line = {"width": 2} - summary_plot_line = {"width": 1} + _data_marker = {"symbol": "x", + "color": "black"} + _best_fit_line = {"dash": "dot", + "color": '#6699ff'} + _legend_options = {"yanchor": "top", + "y": 0.99, + "xanchor": "left", + "x": 0.01, + "bgcolor": 'rgba(0,0,0,0.1)'} + _summary_best_plot_line = {"width": 2} + _summary_plot_line = {"width": 1} + _error_dict = dict(type='data', + array=None, + thickness=1, + width=4) def __init__(self, best_result, options, figures_dir): self.result = best_result + self.plots_failed = False - self.plots_failed = True if self.result.multivariate: + self.plots_failed = True raise PlottingError( 'Plots cannot be generated for multivariate problems') if self.result.problem_format == 'horace': + self.plots_failed = True raise PlottingError( 'Plots cannot be generated for Horace problems') - self.plots_failed = False self.options = options - self.figures_dir = figures_dir @staticmethod @@ -85,14 +89,16 @@ class Plot: color="minimizer", title=self.result.name, markers=True) + self._error_dict['array'] = df["e"][df["minimizer"] == 'Data'] # add the raw data as a scatter plot fig.add_trace(go.Scatter( x=df["x"][df["minimizer"] == 'Data'], y=df["y"][df["minimizer"] == 'Data'], + error_y=self._error_dict, mode='markers', name='Data', - marker=self.data_marker)) - fig.update_layout(legend=self.legend_options) + marker=self._data_marker)) + fig.update_layout(legend=self._legend_options) if self.result.plot_scale in ["loglog", "logx"]: fig.update_xaxes(type="log") @@ -139,6 +145,7 @@ class Plot: y_best = df["y"][df["best"]] x_data = df["x"][df["minimizer"] == 'Data'] y_data = df["y"][df["minimizer"] == 'Data'] + self._error_dict['array'] = df["e"][df["minimizer"] == 'Data'] for minimizer in df['minimizer'].unique(): if minimizer not in ["Data", "Starting Guess"]: @@ -157,16 +164,17 @@ class Plot: y=y_best, mode='lines', name=name, - line=self.best_fit_line)) + line=self._best_fit_line)) # add the raw data as a scatter plot fig.add_trace( go.Scatter( x=x_data, y=y_data, + error_y=self._error_dict, mode='markers', name='Data', - marker=self.data_marker)) - fig.update_layout(legend=self.legend_options) + marker=self._data_marker)) + fig.update_layout(legend=self._legend_options) if self.result.plot_scale in ["loglog", "logx"]: fig.update_xaxes(type="log") @@ -266,22 +274,22 @@ class Plot: error_y=error_y, mode='markers', name='Data', - marker=cls.data_marker)) + marker=cls._data_marker)) for (key, results), colour in zip(categories.items(), plotly_colours): # Plot category for result in results: if result.params is not None: - line = cls.summary_best_plot_line \ - if result.is_best_fit else cls.summary_plot_line + line = cls._summary_best_plot_line \ + if result.is_best_fit else cls._summary_plot_line line["color"] = colour label = key if result.is_best_fit else '' if result.is_best_fit: - line = cls.summary_best_plot_line + line = cls._summary_best_plot_line line["color"] = colour else: - line = cls.summary_plot_line + line = cls._summary_plot_line transparency = 0.5 line["color"] = 'rgba' + colour[3:-1] + ', ' + \ str(transparency) + ')'
Add error bars We need to add error bars to the fitting report.
fitbenchmarking/fitbenchmarking
diff --git a/fitbenchmarking/results_processing/tests/test_plots.py b/fitbenchmarking/results_processing/tests/test_plots.py index acfcf69c..4b129d7b 100644 --- a/fitbenchmarking/results_processing/tests/test_plots.py +++ b/fitbenchmarking/results_processing/tests/test_plots.py @@ -45,6 +45,15 @@ def load_mock_result(): return results +def find_error_bar_count(path): + """ + Reads an html file and counts the error_y count + """ + with open(path, 'r', encoding='utf-8') as file: + html_content = file.read() + return html_content.count("error_y") + + class PlotTests(unittest.TestCase): """ Test the plot object is correct. @@ -108,7 +117,8 @@ class PlotTests(unittest.TestCase): def test_plot_initial_guess_create_files(self): """ - Test that initial plot creates a file. + Test that initial plot creates a file and errorbars are + added to the plot. """ file_name = self.plot.plot_initial_guess( self.df[('Fake_Test_Data', 'prob_1')]) @@ -116,6 +126,7 @@ class PlotTests(unittest.TestCase): self.assertEqual(file_name, 'start_for_prob_1.html') path = os.path.join(self.figures_dir, file_name) self.assertTrue(os.path.exists(path)) + self.assertEqual(find_error_bar_count(path), 2) def test_best_filename_return(self): """ @@ -127,15 +138,24 @@ class PlotTests(unittest.TestCase): def test_plotly_fit_create_files(self): """ - Test that plotly_fit creates a file. + Test that plotly_fit creates a file and errorbars are + added to the plot. """ file_names = self.plot.plotly_fit( self.df[('Fake_Test_Data', 'prob_1')]) - self.assertEqual(file_names['m10_[s1]_jj0'], - 'm10_[s1]_jj0_fit_for_cf1_prob_1.html') - path = os.path.join(self.figures_dir, file_names['m10_[s1]_jj0']) - self.assertTrue(os.path.exists(path)) + for m, s, j in zip(['m10', 'm11', 'm01', 'm00', + 'm10', 'm11', 'm01', 'm00'], + ['s1', 's1', 's0', 's0', + 's1', 's1', 's0', 's0'], + ['jj0', 'jj0', 'jj0', 'jj0', + 'jj1', 'jj1', 'jj1', 'jj1']): + file_name_prefix = f'{m}_[{s}]_{j}' + self.assertEqual(file_names[file_name_prefix], + file_name_prefix+'_fit_for_cf1_prob_1.html') + path = os.path.join(self.figures_dir, file_names[file_name_prefix]) + self.assertTrue(os.path.exists(path)) + self.assertEqual(find_error_bar_count(path), 2) def test_multivariate_plot(self): """
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pylint", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 anyio==4.9.0 arrow==1.3.0 astroid==2.6.6 babel==2.17.0 blinker==1.9.0 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 codecarbon==2.8.3 configparser==7.2.0 contourpy==1.3.0 coverage==7.8.0 coveralls==4.0.1 cryptography==44.0.2 cycler==0.12.1 dash==3.0.1 dill==0.3.9 distlib==0.3.9 docopt==0.6.2 docutils==0.20.1 exceptiongroup==1.2.2 fief-client==0.20.0 filelock==3.18.0 -e git+https://github.com/fitbenchmarking/fitbenchmarking.git@0b3ea8a82a1d74db4f5859927347a8b15628a063#egg=FitBenchmarking flake8==3.9.2 Flask==3.0.3 fonttools==4.56.0 h11==0.14.0 httpcore==1.0.7 httpx==0.27.2 identify==2.6.9 idna==3.10 imagesize==1.4.1 iminuit==2.30.1 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 isort==5.13.2 itsdangerous==2.2.0 Jinja2==3.1.6 jwcrypto==1.5.6 kiwisolver==1.4.7 lazy-object-proxy==1.10.0 lxml==5.3.1 markdown-it-py==3.0.0 MarkupSafe==3.0.2 matplotlib==3.9.4 mccabe==0.6.1 mdurl==0.1.2 mistune==3.1.3 narwhals==1.32.0 nest-asyncio==1.6.0 nodeenv==1.9.1 numpy==1.23.5 nvidia-ml-py==12.570.86 packaging==24.2 pandas==2.2.3 parameterized==0.9.0 pillow==11.1.0 platformdirs==4.3.7 plotly==6.0.1 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 psutil==7.0.0 py-cpuinfo==9.0.0 pycodestyle==2.7.0 pycparser==2.22 pyflakes==2.3.1 Pygments==2.19.1 pylint==2.9.5 pylint-exit==1.2.0 pynvml==12.0.0 pyparsing==3.2.3 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 questionary==2.1.0 RapidFuzz==3.12.2 requests==2.32.3 retrying==1.3.4 rich==14.0.0 scipy==1.13.1 shellingham==1.5.4 six==1.17.0 sniffio==1.3.1 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-rtd-theme==2.0.0 sphinx_mdinclude==0.6.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 termcolor==2.3.0 toml==0.10.2 tomli==2.2.1 tomlkit==0.13.2 tqdm==4.67.1 typer==0.15.2 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 Werkzeug==3.0.6 wrapt==1.12.1 yaspin==3.1.0 zipp==3.21.0
name: fitbenchmarking channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - anyio==4.9.0 - arrow==1.3.0 - astroid==2.6.6 - babel==2.17.0 - blinker==1.9.0 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - codecarbon==2.8.3 - configparser==7.2.0 - contourpy==1.3.0 - coverage==7.8.0 - coveralls==4.0.1 - cryptography==44.0.2 - cycler==0.12.1 - dash==3.0.1 - dill==0.3.9 - distlib==0.3.9 - docopt==0.6.2 - docutils==0.20.1 - exceptiongroup==1.2.2 - fief-client==0.20.0 - filelock==3.18.0 - fitbenchmarking==0.0.0.dev1 - flake8==3.9.2 - flask==3.0.3 - fonttools==4.56.0 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.27.2 - identify==2.6.9 - idna==3.10 - imagesize==1.4.1 - iminuit==2.30.1 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - isort==5.13.2 - itsdangerous==2.2.0 - jinja2==3.1.6 - jwcrypto==1.5.6 - kiwisolver==1.4.7 - lazy-object-proxy==1.10.0 - lxml==5.3.1 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - matplotlib==3.9.4 - mccabe==0.6.1 - mdurl==0.1.2 - mistune==3.1.3 - narwhals==1.32.0 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - numpy==1.23.5 - nvidia-ml-py==12.570.86 - packaging==24.2 - pandas==2.2.3 - parameterized==0.9.0 - pillow==11.1.0 - platformdirs==4.3.7 - plotly==6.0.1 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - psutil==7.0.0 - py-cpuinfo==9.0.0 - pycodestyle==2.7.0 - pycparser==2.22 - pyflakes==2.3.1 - pygments==2.19.1 - pylint==2.9.5 - pylint-exit==1.2.0 - pynvml==12.0.0 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - questionary==2.1.0 - rapidfuzz==3.12.2 - requests==2.32.3 - retrying==1.3.4 - rich==14.0.0 - scipy==1.13.1 - shellingham==1.5.4 - six==1.17.0 - sniffio==1.3.1 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-mdinclude==0.6.2 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - termcolor==2.3.0 - toml==0.10.2 - tomli==2.2.1 - tomlkit==0.13.2 - tqdm==4.67.1 - typer==0.15.2 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - werkzeug==3.0.6 - wrapt==1.12.1 - yaspin==3.1.0 - zipp==3.21.0 prefix: /opt/conda/envs/fitbenchmarking
[ "fitbenchmarking/results_processing/tests/test_plots.py::PlotTests::test_plot_initial_guess_create_files", "fitbenchmarking/results_processing/tests/test_plots.py::PlotTests::test_plotly_fit_create_files" ]
[]
[ "fitbenchmarking/results_processing/tests/test_plots.py::PlotTests::test_best_filename_return", "fitbenchmarking/results_processing/tests/test_plots.py::PlotTests::test_multivariate_plot", "fitbenchmarking/results_processing/tests/test_plots.py::PlotTests::test_write_html_with_link_plotlyjs" ]
[]
BSD 3-Clause "New" or "Revised" License
18,317
1,249
[ "fitbenchmarking/results_processing/plots.py" ]
feder-observatory__stellarphot-318
3c79d736978daaaa6873c26a9ee781f2da01e8c2
2024-05-03 00:24:25
740b6deaa7877834eafeffb2f1270540d93d10ae
diff --git a/stellarphot/settings/custom_widgets.py b/stellarphot/settings/custom_widgets.py index 160192e..1a26f59 100644 --- a/stellarphot/settings/custom_widgets.py +++ b/stellarphot/settings/custom_widgets.py @@ -72,7 +72,7 @@ class ChooseOrMakeNew(ipw.VBox): message=f"Replace value of this {self._display_name}?", ) - self._item_widget = self._make_new_widget() + self._item_widget, self._widget_value_new_item = self._make_new_widget() self._edit_button.on_click(self._edit_button_action) @@ -156,6 +156,14 @@ class ChooseOrMakeNew(ipw.VBox): # This sets the ui back to its original state when created, i.e. # everything is empty. self._item_widget._init_ui() + + # Fun fact: _init_ui does not reset the value of the widget. Also, + # setting the value fails if you try to set it to an empty dict because that + # is not a valid value for the pydantic model for the widget. + # So we have to set each of the values individually. + for key, value in self._widget_value_new_item.items(): + self._item_widget.value[key] = value + self._item_widget.show_savebuttonbar = True self._item_widget.disabled = False @@ -253,6 +261,8 @@ class ChooseOrMakeNew(ipw.VBox): def _make_new_widget(self): """ Make a new widget for the item type and set up actions for the save button. + + Also returns the initial value of the widget for resetting the widget value. """ match self._item_type_name: case "camera" | Camera.__name__: @@ -290,7 +300,7 @@ class ChooseOrMakeNew(ipw.VBox): # This is the mechanism for adding callbacks to the save button. new_widget.savebuttonbar.fns_onsave_add_action(saver) new_widget.savebuttonbar.fns_onsave_add_action(update_choices_and_select_new) - return new_widget + return new_widget, new_widget.value.copy() def _handle_confirmation(self): """
Making a new item confuses the widget If you have at least one item, e.g. camera, and you select the "Make new..." option and then select the original item again then the widget display is blank. The reason is that the private method `_init_ui` from ipyautoui resets the values of each individual text box (or whatever) but does not change the value of the widget as a whole. As a result, after selecting "Make new..." with widget value is still the value for the existing item. So when this custom widget tries to redisplay after you select the existing item again, the UI isn't updated because the UI thinks nothing has changed, so no handlers are triggered. This description is probably a little confusing, but trust me it is an issue. Fix incoming momentarily.
feder-observatory/stellarphot
diff --git a/stellarphot/settings/tests/test_custom_widgets.py b/stellarphot/settings/tests/test_custom_widgets.py index f37c1c5..153fd3b 100644 --- a/stellarphot/settings/tests/test_custom_widgets.py +++ b/stellarphot/settings/tests/test_custom_widgets.py @@ -71,6 +71,34 @@ class TestChooseOrMakeNew: assert len(cameras.as_dict) == 1 assert list(cameras.as_dict.values())[0].model_dump() == TEST_CAMERA_VALUES + @pytest.mark.parametrize( + "item_type,setting", + [ + ("camera", TEST_CAMERA_VALUES), + ("observatory", DEFAULT_OBSERVATORY_SETTINGS), + ("passband_map", DEFAULT_PASSBAND_MAP), + ], + ) + def test_make_new_with_existing_item_resets_value( + self, tmp_path, item_type, setting + ): + # When "make a new" item is selected the value of the widget should be + # the same as when a widget of that type is created. + + # Make a camera widget just to get the value for a new item. + choose_or_make_new = ChooseOrMakeNew(item_type, _testing_path=tmp_path) + value_when_new = choose_or_make_new._item_widget.value.copy() + + # Make a camera + saved = SavedSettings(_testing_path=tmp_path) + item = choose_or_make_new._item_widget.model(**setting) + saved.add_item(item) + + # Make a camera widget and select "Make new" + choose_or_make_new = ChooseOrMakeNew(item_type, _testing_path=tmp_path) + choose_or_make_new._choose_existing.value = "none" + assert choose_or_make_new._item_widget.value == value_when_new + def test_edit_requires_confirmation(self, tmp_path): # Should require confirmation if the item already exists saved = SavedSettings(_testing_path=tmp_path)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": [ ".rtd-environment.yml" ], "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.10", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aggdraw==1.3.19 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 annotated-types==0.7.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asciitree==0.3.3 astropy==6.1.7 astropy-iers-data==0.2025.3.31.0.36.18 astropy_healpix==1.1.2 astroquery==0.4.10 astroscrappy==1.2.0 astrowidgets==0.3.0 asttokens==3.0.0 async-lru==2.0.5 async-timeout==5.0.1 attrs==25.3.0 babel==2.17.0 backports.tarfile==1.2.0 beautifulsoup4==4.13.3 black==25.1.0 bleach==6.2.0 Bottleneck==1.4.2 bqplot==0.12.44 bracex==2.5.post1 cachetools==5.5.2 ccdproc==2.4.3 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.1 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2025.3.0 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 distlib==0.3.9 et_xmlfile==2.0.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fasteners==0.19 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.2 gast==0.4.0 ginga==5.2.0 h11==0.14.0 html5lib==1.1 httpcore==1.0.7 httpx==0.28.1 hypothesis==6.130.6 identify==2.6.9 idna==3.10 imageio==2.37.0 immutables==0.21 importlib_metadata==8.6.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipyautoui==0.7.24 ipydatagrid==1.4.0 ipyevents==2.0.2 ipyfilechooser==0.6.0 ipykernel==6.29.5 ipython==8.34.0 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jedi==0.19.2 jeepney==0.9.0 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonref==1.1.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_app_launcher==0.3.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 keyring==25.6.0 kiwisolver==1.4.8 lazy_loader==0.4 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.10.1 matplotlib-inline==0.1.7 mistune==3.1.3 more-itertools==10.6.0 multidict==6.2.0 mypy-extensions==1.0.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 networkx==3.4.2 nodeenv==1.9.1 notebook_shim==0.2.4 numcodecs==0.13.1 numpy==2.2.4 openpyxl==3.1.5 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pathspec==0.12.1 pexpect==4.9.0 photutils==2.0.2 pillow==11.1.0 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 puremagic==1.28 py2vega==0.6.1 pycparser==2.22 pydantic==2.11.1 pydantic-extra-types==2.10.3 pydantic-settings==2.8.1 pydantic_core==2.33.0 pyerfa==2.0.1.5 Pygments==2.19.1 pyparsing==3.2.3 pyproject-api==1.9.0 pytest @ file:///croot/pytest_1738938843180/work pytest-arraydiff==0.6.1 pytest-astropy==0.11.0 pytest-astropy-header==0.2.2 pytest-cov==6.0.0 pytest-doctestplus==1.4.0 pytest-filter-subpackage==0.2.0 pytest-mock==3.14.0 pytest-remotedata==0.4.1 python-dateutil==2.9.0.post0 python-dotenv==1.1.0 python-json-logger==3.3.0 pytz==2025.2 pyvo==1.6.1 PyYAML==6.0.2 pyzmq==26.3.0 QtPy==2.4.3 referencing==0.36.2 reproject==0.14.1 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 ruff==0.11.2 scikit-image==0.25.2 scipy==1.15.2 SecretStorage==3.3.3 Send2Trash==1.8.3 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 sortedcontainers==2.4.0 soupsieve==2.6 stack-data==0.6.3 -e git+https://github.com/feder-observatory/stellarphot.git@3c79d736978daaaa6873c26a9ee781f2da01e8c2#egg=stellarphot stringcase==1.2.0 terminado==0.18.1 tifffile==2025.3.30 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tox==4.25.0 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 virtualenv==20.30.0 wcmatch==10.0 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 yarl==1.18.3 zarr==2.18.3 zipp==3.21.0
name: stellarphot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py310h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py310h06a4308_0 - pip=25.0=py310h06a4308_0 - pluggy=1.5.0=py310h06a4308_0 - pytest=8.3.4=py310h06a4308_0 - python=3.10.16=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py310h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py310h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aggdraw==1.3.19 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - annotated-types==0.7.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asciitree==0.3.3 - astropy==6.1.7 - astropy-healpix==1.1.2 - astropy-iers-data==0.2025.3.31.0.36.18 - astroquery==0.4.10 - astroscrappy==1.2.0 - astrowidgets==0.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - async-timeout==5.0.1 - attrs==25.3.0 - babel==2.17.0 - backports-tarfile==1.2.0 - beautifulsoup4==4.13.3 - black==25.1.0 - bleach==6.2.0 - bottleneck==1.4.2 - bqplot==0.12.44 - bracex==2.5.post1 - cachetools==5.5.2 - ccdproc==2.4.3 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.1 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2025.3.0 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - distlib==0.3.9 - et-xmlfile==2.0.0 - executing==2.2.0 - fasteners==0.19 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.2 - gast==0.4.0 - ginga==5.2.0 - h11==0.14.0 - html5lib==1.1 - httpcore==1.0.7 - httpx==0.28.1 - hypothesis==6.130.6 - identify==2.6.9 - idna==3.10 - imageio==2.37.0 - immutables==0.21 - importlib-metadata==8.6.1 - ipyautoui==0.7.24 - ipydatagrid==1.4.0 - ipyevents==2.0.2 - ipyfilechooser==0.6.0 - ipykernel==6.29.5 - ipython==8.34.0 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jedi==0.19.2 - jeepney==0.9.0 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonref==1.1.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-app-launcher==0.3.2 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - keyring==25.6.0 - kiwisolver==1.4.8 - lazy-loader==0.4 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.10.1 - matplotlib-inline==0.1.7 - mistune==3.1.3 - more-itertools==10.6.0 - multidict==6.2.0 - mypy-extensions==1.0.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - networkx==3.4.2 - nodeenv==1.9.1 - notebook-shim==0.2.4 - numcodecs==0.13.1 - numpy==2.2.4 - openpyxl==3.1.5 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pathspec==0.12.1 - pexpect==4.9.0 - photutils==2.0.2 - pillow==11.1.0 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - puremagic==1.28 - py2vega==0.6.1 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pydantic-extra-types==2.10.3 - pydantic-settings==2.8.1 - pyerfa==2.0.1.5 - pygments==2.19.1 - pyparsing==3.2.3 - pyproject-api==1.9.0 - pytest-arraydiff==0.6.1 - pytest-astropy==0.11.0 - pytest-astropy-header==0.2.2 - pytest-cov==6.0.0 - pytest-doctestplus==1.4.0 - pytest-filter-subpackage==0.2.0 - pytest-mock==3.14.0 - pytest-remotedata==0.4.1 - python-dateutil==2.9.0.post0 - python-dotenv==1.1.0 - python-json-logger==3.3.0 - pytz==2025.2 - pyvo==1.6.1 - pyyaml==6.0.2 - pyzmq==26.3.0 - qtpy==2.4.3 - referencing==0.36.2 - reproject==0.14.1 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - ruff==0.11.2 - scikit-image==0.25.2 - scipy==1.15.2 - secretstorage==3.3.3 - send2trash==1.8.3 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - sortedcontainers==2.4.0 - soupsieve==2.6 - stack-data==0.6.3 - stellarphot==1.3.10.dev732+g3c79d73 - stringcase==1.2.0 - terminado==0.18.1 - tifffile==2025.3.30 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tox==4.25.0 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - virtualenv==20.30.0 - wcmatch==10.0 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - yarl==1.18.3 - zarr==2.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/stellarphot
[ "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[camera-setting0]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[observatory-setting1]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[passband_map-setting2]" ]
[]
[ "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation_without_type_raises_error", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation_unknown_item_type_raises_error", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[camera]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[observatory]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[passband_map]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[Camera]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[PassbandMap]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[Observatory]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_initial_configuration_with_no_items", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_makes_a_new_item", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_requires_confirmation", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_item_saved_after_confirm", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_item_not_saved_after_cancel", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_selecting_make_new_as_selection_works", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_choosing_different_item_updates_display", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_passband_map_buttons_are_disabled_or_enabled", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_passband_map", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_no_edit_button_when_there_are_no_items", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_button_returns_after_making_new_item", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_save_button_disabled_when_no_changes", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_initial_value", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_initial_display", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_message", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_widget_structure", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_show[None]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_show[other_widget1]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[None-yes]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[None-no]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[other_widget1-yes]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[other_widget1-no]" ]
[]
BSD 3-Clause "New" or "Revised" License
18,326
522
[ "stellarphot/settings/custom_widgets.py" ]
stfc__PSyclone-2572
d334f74b642048be6f262343c68e2c9927d330b8
2024-05-03 12:24:11
539a5cc0243f734d788a52b09a393e4ef7d5a0c9
diff --git a/src/psyclone/psyir/symbols/symbol_table.py b/src/psyclone/psyir/symbols/symbol_table.py index bb253970e..3b50de37c 100644 --- a/src/psyclone/psyir/symbols/symbol_table.py +++ b/src/psyclone/psyir/symbols/symbol_table.py @@ -1798,7 +1798,19 @@ class SymbolTable(): header += ":" header += "\n" + "-" * len(header) + "\n" - return header + "\n".join(map(str, self._symbols.values())) + "\n" + # Unique types of symbols, alpha-sorted. + symbol_types = list({type(symbol) + for symbol in self._symbols.values()}) + symbol_types.sort(key=lambda t: t.__name__) + for symbol_type in symbol_types: + header += symbol_type.__name__ + ":\n" + # _symbols is an OrderDict so these are alpha-sorted. + for symbol in self._symbols.values(): + # pylint: disable=unidiomatic-typecheck + if type(symbol) is symbol_type: + header += f" {symbol}\n" + + return header @property def scope(self):
SymbolTable view() output needs sorting/ordering It's a nice-to-have but it would be good if view() output the symbols grouped by type and in alpha-order within each group.
stfc/PSyclone
diff --git a/src/psyclone/tests/psyir/symbols/symbol_table_test.py b/src/psyclone/tests/psyir/symbols/symbol_table_test.py index d604cc352..5add7456c 100644 --- a/src/psyclone/tests/psyir/symbols/symbol_table_test.py +++ b/src/psyclone/tests/psyir/symbols/symbol_table_test.py @@ -1399,15 +1399,61 @@ def test_wildcard_imports(): def test_view(): '''Test the view method of the SymbolTable class, it should return a - representation of the full SymbolTable.''' + representation of the full SymbolTable, sorted by symbol type and + alphabetically ordered.''' sym_table = symbols.SymbolTable() sym_table.add(symbols.DataSymbol("var1", symbols.REAL_TYPE)) sym_table.add(symbols.DataSymbol("var2", symbols.INTEGER_TYPE)) output = sym_table.view() assert "Symbol Table:\n" in output + assert "DataSymbol:\n" in output assert "var1" in output assert "var2" in output + sym_table_2 = sym_table.deep_copy() + + sym_table.add(symbols.RoutineSymbol("func", symbols.REAL_TYPE)) + output = sym_table.view() + assert "Symbol Table:\n" in output + assert "DataSymbol:\n" in output + assert "var1" in output + assert "var2" in output + assert "RoutineSymbol:\n" in output + assert "func" in output + assert output.index("DataSymbol:\n") < output.index("RoutineSymbol:\n") + assert output.index("var1") < output.index("var2") + assert output == ("Symbol Table:\n" + "-------------\n" + "DataSymbol:\n" + " var1: DataSymbol<Scalar<REAL, UNDEFINED>, " + "Automatic>\n" + " var2: DataSymbol<Scalar<INTEGER, UNDEFINED>, " + "Automatic>\n" + "RoutineSymbol:\n" + " func: RoutineSymbol<Scalar<REAL, UNDEFINED>, " + "pure=unknown, elemental=unknown>\n") + + Routine("func", symbol_table=sym_table_2) + output = sym_table_2.view() + assert "Symbol Table of Routine 'func':\n" in output + assert "DataSymbol:\n" in output + assert "var1" in output + assert "var2" in output + assert "RoutineSymbol:\n" in output + assert "func" in output + assert output.index("DataSymbol:\n") < output.index("RoutineSymbol:\n") + assert output.index("var1") < output.index("var2") + assert output == ("Symbol Table of Routine 'func':\n" + "-------------------------------\n" + "DataSymbol:\n" + " var1: DataSymbol<Scalar<REAL, UNDEFINED>, " + "Automatic>\n" + " var2: DataSymbol<Scalar<INTEGER, UNDEFINED>, " + "Automatic>\n" + "RoutineSymbol:\n" + " func: RoutineSymbol<NoType, pure=unknown, " + "elemental=unknown>\n") + def test_can_be_printed(): '''Test that a SymbolTable instance can always be printed. (i.e. is
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
2.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist graphviz termcolor", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y graphviz doxygen" ], "python": "3.8", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.2.4 attrs==25.3.0 configparser==7.1.0 coverage==7.6.1 dill==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 flake8==7.1.2 fparser==0.2.0 graphviz==0.20.3 importlib_resources==6.4.5 iniconfig==2.1.0 isort==5.13.2 jsonschema==4.23.0 jsonschema-specifications==2023.12.1 mccabe==0.7.0 mpmath==1.3.0 packaging==24.2 pkgutil_resolve_name==1.3.10 platformdirs==4.3.6 pluggy==1.5.0 -e git+https://github.com/stfc/PSyclone.git@d334f74b642048be6f262343c68e2c9927d330b8#egg=PSyclone pycodestyle==2.12.1 pyflakes==3.2.0 pylint==3.2.7 pyparsing==3.1.4 pytest==8.3.5 pytest-cov==5.0.0 pytest-xdist==3.6.1 referencing==0.35.1 rpds-py==0.20.1 setuptools-scm==8.2.0 sympy==1.13.3 termcolor==2.4.0 tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0 zipp==3.20.2
name: PSyclone channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=24.2=py38h06a4308_0 - python=3.8.20=he870216_0 - readline=8.2=h5eee18b_0 - setuptools=75.1.0=py38h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.44.0=py38h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.2.4 - attrs==25.3.0 - configparser==7.1.0 - coverage==7.6.1 - dill==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - flake8==7.1.2 - fparser==0.2.0 - graphviz==0.20.3 - importlib-resources==6.4.5 - iniconfig==2.1.0 - isort==5.13.2 - jsonschema==4.23.0 - jsonschema-specifications==2023.12.1 - mccabe==0.7.0 - mpmath==1.3.0 - packaging==24.2 - pkgutil-resolve-name==1.3.10 - platformdirs==4.3.6 - pluggy==1.5.0 - pycodestyle==2.12.1 - pyflakes==3.2.0 - pylint==3.2.7 - pyparsing==3.1.4 - pytest==8.3.5 - pytest-cov==5.0.0 - pytest-xdist==3.6.1 - referencing==0.35.1 - rpds-py==0.20.1 - setuptools-scm==8.2.0 - sympy==1.13.3 - termcolor==2.4.0 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 - zipp==3.20.2 prefix: /opt/conda/envs/PSyclone
[ "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_view" ]
[]
[ "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_instance", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_default_vis_symbol_table", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_parent_symbol_table", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_symboltable_is_empty", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_next_available_name_1", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_next_available_name_2", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_next_available_name_3", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_next_available_name_4", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_new_symbol_5", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_new_symbol_import_interface", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_new_symbol_fails_on_duplicate_without_renaming", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_add_1", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_add_with_tags_1", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_add_with_tags_hierachical", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_symbols_imported_from", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_remove_genericsymbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_remove_routineymbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_no_remove_routinesymbol_called", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_no_remove_routinesymbol_interface", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_remove_containersymbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_remove_unsupported_types", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_remove_case_insensitive[var1]", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_remove_case_insensitive[vAr1]", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_remove_case_insensitive[VAR1]", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_swap_symbol", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_check_for_clashes_imports", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_check_for_clashes_cannot_rename", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_check_for_clashes_wildcard_import", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_table_merge", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_merge_container_syms", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_merge_same_routine_symbol", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_merge_with_use_renaming", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_add_container_symbols_from_table", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_add_symbols_from_table_import_error", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_add_symbols_from_table_wildcard_import", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_add_symbols_from_table_rename_existing", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_swap_symbol_properties", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_lookup_1", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_lookup_2", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_lookup_3", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_lookup_4", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_lookup_with_tag_1", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_lookup_with_tag_2", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_lookup_with_tag_3", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_wildcard_imports", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_can_be_printed", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_specify_argument_list", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_specify_arg_list_errors", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_argument_list_errors", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_validate_non_args", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_contains", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_symbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_automatic_datasymbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_argument_datasymbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_datatypesymbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_imported_symbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_unresolved_datasymbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_precision_datasymbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_abstract_properties", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_copy_external_import", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_normalization", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_shallow_copy", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_deep_copy", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_get_symbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_get_tags", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_symbols_tags_dict", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_new_symbol", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_new_symbol_with_private_default_visibility", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_find_or_create", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_find_or_create_tag", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_rename_symbol", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_rename_symbol_errors", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_rename_codeblock_error", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_different_capitalization", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_name_clashes", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_private_symbols", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_with_datatypes", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_common_symbol[dependency_order0]", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_common_symbol[dependency_order1]", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_parent_scope", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_from_child_symtab", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_from_child_symtab_uft", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_from_child_symtabs", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_resolve_imports_from_child_symtabs_utf", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_scope", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_detach", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_attach", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_has_same_name", "src/psyclone/tests/psyir/symbols/symbol_table_test.py::test_equality" ]
[]
BSD 3-Clause "New" or "Revised" License
18,330
302
[ "src/psyclone/psyir/symbols/symbol_table.py" ]
feder-observatory__stellarphot-322
92f44fc5dc348f6f2e2c553e14c0152cfec390a7
2024-05-03 14:42:22
740b6deaa7877834eafeffb2f1270540d93d10ae
diff --git a/stellarphot/settings/custom_widgets.py b/stellarphot/settings/custom_widgets.py index e50a9c3..46ff21a 100644 --- a/stellarphot/settings/custom_widgets.py +++ b/stellarphot/settings/custom_widgets.py @@ -14,6 +14,8 @@ from stellarphot.settings import ( ui_generator, ) +DEFAULT_BUTTON_WIDTH = "300px" + class ChooseOrMakeNew(ipw.VBox): """ @@ -52,6 +54,12 @@ class ChooseOrMakeNew(ipw.VBox): # keep track of whether we are editing an existing item self._editing = False + # also track whether we are in the midst of a delete confirmation + self._deleting = False + + # and track if we are making a new item + self._making_new = False + self._display_name = item_type_name.replace("_", " ") # Create the child widgets @@ -61,27 +69,32 @@ class ChooseOrMakeNew(ipw.VBox): self._choose_existing = ipw.Dropdown(description="") - self._edit_button = ipw.Button( - description=f"Edit this {self._display_name}", + self._edit_delete_container = ipw.HBox( # width below was chosen to match the dropdown...would prefer to # determine this programmatically but don't know how. - layout={"width": "300px"}, + layout={"width": DEFAULT_BUTTON_WIDTH} + ) + + self._edit_button = ipw.Button( + description=f"Edit this {self._display_name}", ) - self._confirm_edit = Confirm( - message=f"Replace value of this {self._display_name}?", + self._delete_button = ipw.Button( + description=f"Delete this {self._display_name}", ) - self._item_widget, self._widget_value_new_item = self._make_new_widget() + self._edit_delete_container.children = [self._edit_button, self._delete_button] - self._edit_button.on_click(self._edit_button_action) + self._confirm_edit_delete = Confirm() + + self._item_widget, self._widget_value_new_item = self._make_new_widget() # Build the main widget self.children = [ self._title, self._choose_existing, - self._edit_button, - self._confirm_edit, + self._edit_delete_container, + self._confirm_edit_delete, self._item_widget, ] @@ -107,14 +120,20 @@ class ChooseOrMakeNew(ipw.VBox): # Set up some observers + # Respond to user clicking the edit button + self._edit_button.on_click(self._edit_button_action) + + # Respond to user clicking the delete button + self._delete_button.on_click(self._delete_button_action) + # Respond to user clicking the save button self._item_widget.savebuttonbar.fns_onsave_add_action(self._save_confirmation()) # Respond to user interacting with a confirmation widget # Hide the save button bar so the user gets the confirmation instead - self._confirm_edit.widget_to_hide = self._item_widget.savebuttonbar + self._confirm_edit_delete.widget_to_hide = self._item_widget.savebuttonbar # Add the observer - self._confirm_edit.observe(self._handle_confirmation(), names="value") + self._confirm_edit_delete.observe(self._handle_confirmation(), names="value") # Respond when user wants to make a new thing self._choose_existing.observe(self._handle_selection, names="value") @@ -130,7 +149,8 @@ class ChooseOrMakeNew(ipw.VBox): # we only want to ask for confirmation if we are editing an existing item # rather than saving a new one. if self._editing: - self._confirm_edit.show() + self._set_confirm_message() + self._confirm_edit_delete.show() return f @@ -151,7 +171,7 @@ class ChooseOrMakeNew(ipw.VBox): # We are making a new item... # Hide the edit button - self._edit_button.layout.display = "none" + self._edit_delete_container.layout.display = "none" # This sets the ui back to its original state when created, i.e. # everything is empty. @@ -180,6 +200,9 @@ class ChooseOrMakeNew(ipw.VBox): self._item_widget.open_nested = False self._item_widget.open_nested = True + # Note that we are making a new item + self._making_new = True + else: # Display the selected item... self._item_widget.show_savebuttonbar = False @@ -188,7 +211,7 @@ class ChooseOrMakeNew(ipw.VBox): self._item_widget.value = self._get_item(change["new"].name) # Display the edit button - self._edit_button.layout.display = "flex" + self._edit_delete_container.layout.display = "flex" # Really only applies to PassbandMap, which has nested models, # but does no harm in the other cases @@ -199,7 +222,7 @@ class ChooseOrMakeNew(ipw.VBox): Handle the edit button being clicked. """ # Replace the display of the edit button with the save button bar... - self._edit_button.layout.display = "none" + self._edit_delete_container.layout.display = "none" self._item_widget.show_savebuttonbar = True # ...enable the widget... self._item_widget.disabled = False @@ -227,6 +250,20 @@ class ChooseOrMakeNew(ipw.VBox): # Enable the revert button so that the user can cancel the edit self._item_widget.savebuttonbar.bn_revert.disabled = False + def _delete_button_action(self, _): + """ + Handle the delete button being clicked. + """ + # Change our state + self._deleting = True + + # Hide the edit/delete buttons + self._edit_delete_container.layout.display = "none" + + # Show the confirmation widget + self._set_confirm_message() + self._confirm_edit_delete.show() + def _set_disable_state_nested_models(self, top, value): """ When a one model contains another and the top-level model widget @@ -261,6 +298,17 @@ class ChooseOrMakeNew(ipw.VBox): # No children... pass + def _set_confirm_message(self): + """ + Set the message for the confirmation widget. + """ + if self._editing or self._making_new: + self._confirm_edit_delete.message = ( + f"Replace value of this {self._display_name}?" + ) + elif self._deleting: + self._confirm_edit_delete.message = f"Delete this {self._display_name}?" + def _make_new_widget(self): """ Make a new widget for the item type and set up actions for the save button. @@ -282,10 +330,14 @@ class ChooseOrMakeNew(ipw.VBox): try: self._saved_settings.add_item(new_widget.model(**new_widget.value)) except ValueError: - # This will happen if the item already exists - self._confirm_edit.show() + # This will happen in two circumstances if the item already exists: + # 1. User is editing an existing item + # 2. User is making a new item with the same name as an existing one + self._set_confirm_message() + self._confirm_edit_delete.show() else: # If saving works, we update the choices and select the new item + self._making_new = False update_choices_and_select_new() def update_choices_and_select_new(): @@ -293,12 +345,12 @@ class ChooseOrMakeNew(ipw.VBox): Update the choices after a new item is saved, update the choices and select the new item. """ - if not self._editing: + if not (self._editing or self._making_new): value_to_select = new_widget.model(**new_widget.value) self._construct_choices() self._choose_existing.value = value_to_select # Make sure the edit button is displayed - self._edit_button.layout.display = "flex" + self._edit_delete_container.layout.display = "flex" def revert_to_saved_value(): """ @@ -328,16 +380,18 @@ class ChooseOrMakeNew(ipw.VBox): """ # Use a closure here to capture the current state of the widget - def save_confirm_handler(change): + def confirm_handler(change): """ This handles interactions with the confirmation widget, which is displayed - when the user either tries to save a new item with the same name as an - existing one or tries to save an edited item with the same name as an - existing one. + when the user has done any of these things: + + + tried to save a new item with the same name as an existing one + + tried to save an existing item they have edited + + tried to delete an existing item. The widget has three possible values: True (yes), False (no), and None - This widget is called whent the widget value changes, which can happen two + This widget is called when the widget value changes, which can happen two ways: 1. The user clicks the "yes" or "no" button, in which case the value will @@ -350,28 +404,56 @@ class ChooseOrMakeNew(ipw.VBox): # value of None means the widget has been reset to not answered if change["new"] is not None: item = self._item_widget.model(**self._item_widget.value) - if change["new"]: - # Use has said yes to updating the item, which we do by - # deleting the old one and adding the new one. - self._saved_settings.delete_item(item, confirm=True) - self._saved_settings.add_item(item) - # Rebuild the dropdown list - self._construct_choices() - # Select the edited item - self._choose_existing.value = item - else: - # Use has said no to updating the item, so we just - # act as though the user has selected this item. - self._handle_selection({"new": item}) + if self._editing or self._making_new: + if change["new"]: + # User has said yes to updating the item, which we do by + # deleting the old one and adding the new one. + self._saved_settings.delete_item(item, confirm=True) + self._saved_settings.add_item(item) + # Rebuild the dropdown list + self._construct_choices() + # Select the edited item + self._choose_existing.value = item + else: + # User has said no to updating the item, so we just + # act as though the user has selected this item. + if self._editing: + self._handle_selection({"new": item}) + else: + # Set the selection to the first choice if there is one + self._choose_existing.value = self._choose_existing.options[ + 0 + ][1] + # We are done editing/making new regardless of + # the confirmation outcome + self._editing = False + self._making_new = False + + elif self._deleting: + if change["new"]: + # User has confirmed the deletion + self._saved_settings.delete_item(item, confirm=True) + # Rebuild the dropdown list + self._construct_choices() + + # Select the first item... + self._choose_existing.value = self._choose_existing.options[0][ + 1 + ] + # ...but if there is only one option, the line above doesn't + # trigger the _choose_existing observer because the value is set + # when the options are set. So we need to trigger it manually. + if len(self._choose_existing.options) == 1: + self._handle_selection({"new": self._choose_existing.value}) + else: + # User has decided not to delete the item + self._handle_selection({"new": item}) + self._deleting = False # Reset the confirmation widget to unanswered - self._confirm_edit.value = None - # We are done editing regardless of the confirmation outcome - self._editing = False - # Bring the edit button back - self._edit_button.layout.display = "flex" + self._confirm_edit_delete.value = None - return save_confirm_handler + return confirm_handler def _get_item(self, item_name): """
Add a delete button for the saveable settings I suppose errors will happen and it would be nice to be able to delete them.
feder-observatory/stellarphot
diff --git a/stellarphot/settings/tests/test_custom_widgets.py b/stellarphot/settings/tests/test_custom_widgets.py index d26f767..072d083 100644 --- a/stellarphot/settings/tests/test_custom_widgets.py +++ b/stellarphot/settings/tests/test_custom_widgets.py @@ -16,6 +16,15 @@ class TestChooseOrMakeNew: Class for testing the ChooseOrMakeNew widget. """ + def make_test_camera(self, path): + """ + Make a camera with the default testing values and save it. This came + up often enough to warrant its own method. + """ + saved = SavedSettings(_testing_path=path) + camera = Camera(**TEST_CAMERA_VALUES) + saved.add_item(camera) + def test_creation_without_type_raises_error(self): # Should raise an error if no type is provided with pytest.raises(TypeError): @@ -65,6 +74,9 @@ class TestChooseOrMakeNew: # No need for the confirmation dialog because we are not overwriting # anything. + # making sure the widget state is properly updated + assert choose_or_make_new._making_new is False + # Check what we created using SavedSettings... saved = SavedSettings(_testing_path=tmp_path) cameras = saved.get_items("camera") @@ -101,20 +113,18 @@ class TestChooseOrMakeNew: def test_edit_requires_confirmation(self, tmp_path): # Should require confirmation if the item already exists - saved = SavedSettings(_testing_path=tmp_path) - camera = Camera(**TEST_CAMERA_VALUES) - saved.add_item(camera) + self.make_test_camera(tmp_path) choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # the edit button should be displayed and the confirm widget should be hidden # note: display typically start as None or an empty string, so we just check # that it is not "none", which is what it will be set to when it is hidden. - assert choose_or_make_new._edit_button.layout.display != "none" - assert choose_or_make_new._confirm_edit.layout.display == "none" + assert choose_or_make_new._edit_delete_container.layout.display != "none" + assert choose_or_make_new._confirm_edit_delete.layout.display == "none" # Simulate a click on the edit button... choose_or_make_new._edit_button.click() # The edit button should now be hidden - assert choose_or_make_new._edit_button.layout.display == "none" + assert choose_or_make_new._edit_delete_container.layout.display == "none" # The savebuttonbar should be displayed assert choose_or_make_new._item_widget.savebuttonbar.layout.display != "none" @@ -123,13 +133,15 @@ class TestChooseOrMakeNew: choose_or_make_new._item_widget.savebuttonbar.bn_save.click() # The confirm dialog should be displayed - assert choose_or_make_new._confirm_edit.layout.display != "none" + assert choose_or_make_new._confirm_edit_delete.layout.display != "none" + + # The confirmation dialog should contain the word "replace" + assert "replace" in choose_or_make_new._confirm_edit_delete.message.lower() def test_edit_item_saved_after_confirm(self, tmp_path): # Should save the item after confirmation - saved = SavedSettings(_testing_path=tmp_path) - camera = Camera(**TEST_CAMERA_VALUES) - saved.add_item(camera) + self.make_test_camera(tmp_path) + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # Simulate a click on the edit button... choose_or_make_new._edit_button.click() @@ -140,16 +152,16 @@ class TestChooseOrMakeNew: # Simulate a click on the save button... choose_or_make_new._item_widget.savebuttonbar.bn_save.click() # Simulate a click on the confirm button... - choose_or_make_new._confirm_edit._yes.click() + choose_or_make_new._confirm_edit_delete._yes.click() + saved = SavedSettings(_testing_path=tmp_path) cameras = saved.get_items("camera") - assert cameras.as_dict[camera.name].gain == new_gain + assert cameras.as_dict[TEST_CAMERA_VALUES["name"]].gain == new_gain def test_edit_item_not_saved_after_cancel(self, tmp_path): # Should not save the item after clicking the No button - saved = SavedSettings(_testing_path=tmp_path) - camera = Camera(**TEST_CAMERA_VALUES) - saved.add_item(camera) + self.make_test_camera(tmp_path) + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # Simulate a click on the edit button... choose_or_make_new._edit_button.click() @@ -160,25 +172,27 @@ class TestChooseOrMakeNew: # Simulate a click on the save button... choose_or_make_new._item_widget.savebuttonbar.bn_save.click() # Simulate a click on the cancel button... - choose_or_make_new._confirm_edit._no.click() + choose_or_make_new._confirm_edit_delete._no.click() + saved = SavedSettings(_testing_path=tmp_path) cameras = saved.get_items("camera") - assert cameras.as_dict[camera.name].gain == TEST_CAMERA_VALUES["gain"] + assert ( + cameras.as_dict[TEST_CAMERA_VALUES["name"]].gain + == TEST_CAMERA_VALUES["gain"] + ) def test_selecting_make_new_as_selection_works(self, tmp_path): # Should allow the user to select "Make new" as a selection # Make a camera so that we can test that selecting "Make new" works - saved = SavedSettings(_testing_path=tmp_path) - camera = Camera(**TEST_CAMERA_VALUES) - saved.add_item(camera) + self.make_test_camera(tmp_path) choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # This is the value for the "Make new...." option choose_or_make_new._choose_existing.value = "none" # edit button should go away - assert choose_or_make_new._edit_button.layout.display == "none" + assert choose_or_make_new._edit_delete_container.layout.display == "none" # Widget should be enabled assert choose_or_make_new._item_widget.disabled is False @@ -206,8 +220,6 @@ class TestChooseOrMakeNew: # Make sure the correct first observatory is selected assert choose_or_make_new._choose_existing.value == observatory - print(f"{choose_or_make_new._item_widget.value=}") - print(f"{observatory.model_dump()=}") assert Observatory(**choose_or_make_new._item_widget.value) == observatory # Select the other observatory @@ -264,7 +276,7 @@ class TestChooseOrMakeNew: assert len(saved.get_items("camera").as_dict) == 0 choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) - assert choose_or_make_new._edit_button.layout.display == "none" + assert choose_or_make_new._edit_delete_container.layout.display == "none" def test_edit_button_returns_after_making_new_item(self, tmp_path): # After making a new item the edit button should be displayed @@ -273,7 +285,7 @@ class TestChooseOrMakeNew: choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # Make sure the edit button is hidden - assert choose_or_make_new._edit_button.layout.display == "none" + assert choose_or_make_new._edit_delete_container.layout.display == "none" # Change a value in the camera so we can check that the new value is saved. choose_or_make_new._item_widget.value = TEST_CAMERA_VALUES @@ -281,19 +293,19 @@ class TestChooseOrMakeNew: choose_or_make_new._item_widget.savebuttonbar.bn_save.click() # The edit button should now be displayed - assert choose_or_make_new._edit_button.layout.display != "none" + assert choose_or_make_new._edit_delete_container.layout.display != "none" # Select Make a new camera again choose_or_make_new._choose_existing.value = "none" # The edit button should now be hidden - assert choose_or_make_new._edit_button.layout.display == "none" + assert choose_or_make_new._edit_delete_container.layout.display == "none" # Select the camera we made choose_or_make_new._choose_existing.value = Camera(**TEST_CAMERA_VALUES) # The edit button should now be displayed - assert choose_or_make_new._edit_button.layout.display != "none" + assert choose_or_make_new._edit_delete_container.layout.display != "none" def test_save_button_disabled_when_no_changes(self, tmp_path): # Immediately after the edit button has been clicked, the save button should be @@ -301,9 +313,7 @@ class TestChooseOrMakeNew: # # That should remain true even after the user makes a change, then saves it # and then edits again but has not yet made any changes. - saved = SavedSettings(_testing_path=tmp_path) - camera = Camera(**TEST_CAMERA_VALUES) - saved.add_item(camera) + self.make_test_camera(tmp_path) choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # Simulate a click on the edit button... @@ -323,7 +333,7 @@ class TestChooseOrMakeNew: choose_or_make_new._item_widget.savebuttonbar.bn_save.click() # Confirm the save - choose_or_make_new._confirm_edit._yes.click() + choose_or_make_new._confirm_edit_delete._yes.click() # Edit again... choose_or_make_new._edit_button.click() @@ -334,9 +344,7 @@ class TestChooseOrMakeNew: def test_revert_button_is_enabled_after_clicking_edit(self, tmp_path): # The revert button should be enabled after clicking the edit button so # the user can cancel the edit. - saved = SavedSettings(_testing_path=tmp_path) - camera = Camera(**TEST_CAMERA_VALUES) - saved.add_item(camera) + self.make_test_camera(tmp_path) choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # Simulate a click on the edit button... @@ -347,9 +355,7 @@ class TestChooseOrMakeNew: def test_clicking_revert_button_cancels_edit(self, tmp_path): # Clicking the revert button should cancel the edit - saved = SavedSettings(_testing_path=tmp_path) - camera = Camera(**TEST_CAMERA_VALUES) - saved.add_item(camera) + self.make_test_camera(tmp_path) choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # Simulate a click on the edit button... @@ -362,7 +368,7 @@ class TestChooseOrMakeNew: assert choose_or_make_new._item_widget.value == TEST_CAMERA_VALUES # The edit button should be displayed - assert choose_or_make_new._edit_button.layout.display != "none" + assert choose_or_make_new._edit_delete_container.layout.display != "none" # We should not be in editing mode anymore assert not choose_or_make_new._editing @@ -372,9 +378,7 @@ class TestChooseOrMakeNew: ): # The revert button should remain enabled if the value is invalid and reverting # should actually revert the value. - saved = SavedSettings(_testing_path=tmp_path) - camera = Camera(**TEST_CAMERA_VALUES) - saved.add_item(camera) + self.make_test_camera(tmp_path) choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) # Simulate a click on the edit button... @@ -401,6 +405,151 @@ class TestChooseOrMakeNew: # The camera should not have been changed assert choose_or_make_new._item_widget.value == TEST_CAMERA_VALUES + def test_delete_button_click_displays_confirm_dialog(self, tmp_path): + # Clicking "Delete" should display a confirmation dialog + + # Make an item to ensure an existing item is displayed when the widget is made + self.make_test_camera(tmp_path) + + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) + choose_or_make_new._delete_button.click() + + # Confirm dialog should be displayed + assert choose_or_make_new._confirm_edit_delete.layout.display != "none" + # edit/delete buttons should be hidden + assert choose_or_make_new._edit_delete_container.layout.display == "none" + # The confirm dialog should indicate you are deleting + assert "delete" in choose_or_make_new._confirm_edit_delete.message.lower() + + @pytest.mark.parametrize("click_yes", [True, False]) + def test_delete_actions_after_confirmation(self, tmp_path, click_yes): + # Clicking "Yes" in the confirmation dialog should delete the item + self.make_test_camera(tmp_path) + + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) + choose_or_make_new._delete_button.click() + + if click_yes: + # Simulate a click on the "Yes" button in the confirm dialog + choose_or_make_new._confirm_edit_delete._yes.click() + + # The camera should be gone + saved = SavedSettings(_testing_path=tmp_path) + cameras = saved.get_items("camera") + assert len(cameras.as_dict) == 0 + else: + # Simulate a click on the "No" button in the confirm dialog + choose_or_make_new._confirm_edit_delete._no.click() + + # The camera should still be there + saved = SavedSettings(_testing_path=tmp_path) + cameras = saved.get_items("camera") + assert len(cameras.as_dict) == 1 + assert list(cameras.as_dict.values())[0].model_dump() == TEST_CAMERA_VALUES + + # Regardless of the choice, the confirm dialog should be hidden + assert choose_or_make_new._confirm_edit_delete.layout.display == "none" + + # We should also no longer be deleting + assert not choose_or_make_new._deleting + + # If the user clicked "No" the edit/delete buttons should be displayed because + # there is still an item to edit or delete. + if not click_yes: + assert choose_or_make_new._edit_delete_container.layout.display != "none" + # If the user clicked "Yes" the edit/delete buttons should be hidden because + # there is no item to edit or delete. + else: + assert choose_or_make_new._edit_delete_container.layout.display == "none" + + def test_correct_item_selected_after_delete_and_yes(self, tmp_path): + # The correct item should be selected after an item is deleted and the user + # clicks "Yes" in the confirmation dialog. + # Make two cameras + self.make_test_camera(tmp_path) + saved = SavedSettings(_testing_path=tmp_path) + camera2 = Camera(**TEST_CAMERA_VALUES) + camera2.name = "zzzz" + camera2.name + saved.add_item(camera2) + + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) + # Select the first camera... + choose_or_make_new._choose_existing.value = saved.cameras.as_dict[ + TEST_CAMERA_VALUES["name"] + ] + # ...and delete it + choose_or_make_new._delete_button.click() + choose_or_make_new._confirm_edit_delete._yes.click() + # Are the edit/delete buttons being shown? + assert choose_or_make_new._edit_delete_container.layout.display != "none" + # Is the correct camera selected? + assert choose_or_make_new._choose_existing.value == camera2 + + @pytest.mark.parametrize("click_yes", [True, False]) + def test_making_new_with_same_name_as_existing(self, tmp_path, click_yes): + # Making a new item with the same name as an existing item should require + # confirmation + self.make_test_camera(tmp_path) + + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) + + # Click the "Make new" button + choose_or_make_new._choose_existing.value = "none" + + # set the item widget value to the existing camera with double the gain + camera_values = TEST_CAMERA_VALUES.copy() + camera_values["gain"] = 2 * camera_values["gain"] + choose_or_make_new._item_widget.value = Camera(**camera_values) + + # Simulate a click on the save button... + choose_or_make_new._item_widget.savebuttonbar.bn_save.click() + + # The confirm dialog should be displayed + assert choose_or_make_new._confirm_edit_delete.layout.display != "none" + # The confirm dialog should contain the word "replace" + assert "replace" in choose_or_make_new._confirm_edit_delete.message.lower() + + if click_yes: + # ...click confirm + choose_or_make_new._confirm_edit_delete._yes.click() + expected_camera = Camera(**camera_values) + else: + # ...click cancel + choose_or_make_new._confirm_edit_delete._no.click() + expected_camera = Camera(**TEST_CAMERA_VALUES) + + # Check the value of the camera + chosen_cam = Camera(**choose_or_make_new._item_widget.value) + assert chosen_cam == choose_or_make_new._choose_existing.value + + assert chosen_cam == expected_camera + + def test_weird_sequence_of_no_clicks(self, tmp_path): + # This is a regression test for #320 + # Make a camera + self.make_test_camera(tmp_path) + + # Make a new camera... + choose_or_make_new = ChooseOrMakeNew("camera", _testing_path=tmp_path) + choose_or_make_new._choose_existing.value = "none" + choose_or_make_new._item_widget.value = TEST_CAMERA_VALUES + + # ...click save... + choose_or_make_new._item_widget.savebuttonbar.bn_save.click() + # ...but say no to confirm + choose_or_make_new._confirm_edit_delete._no.click() + + # Check that we are back to our selected camera + assert choose_or_make_new._choose_existing.value == Camera(**TEST_CAMERA_VALUES) + + # Click delete... + choose_or_make_new._delete_button.click() + # ...but say no to confirm... + choose_or_make_new._confirm_edit_delete._no.click() + + # ...the edit/delete buttons should be displayed + assert choose_or_make_new._edit_delete_container.layout.display != "none" + class TestConfirm: def test_initial_value(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.10", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aggdraw==1.3.19 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 annotated-types==0.7.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asciitree==0.3.3 astropy==6.1.7 astropy-iers-data==0.2025.3.31.0.36.18 astropy_healpix==1.1.2 astroquery==0.4.10 astroscrappy==1.2.0 astrowidgets==0.3.0 asttokens==3.0.0 async-lru==2.0.5 async-timeout==5.0.1 attrs==25.3.0 babel==2.17.0 backports.tarfile==1.2.0 beautifulsoup4==4.13.3 black==25.1.0 bleach==6.2.0 Bottleneck==1.4.2 bqplot==0.12.44 bracex==2.5.post1 cachetools==5.5.2 ccdproc==2.4.3 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.1 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2025.3.0 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 distlib==0.3.9 et_xmlfile==2.0.0 exceptiongroup==1.2.2 executing==2.2.0 fasteners==0.19 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.2 gast==0.4.0 ginga==5.2.0 h11==0.14.0 html5lib==1.1 httpcore==1.0.7 httpx==0.28.1 hypothesis==6.130.6 identify==2.6.9 idna==3.10 imageio==2.37.0 immutables==0.21 importlib_metadata==8.6.1 iniconfig==2.1.0 ipyautoui==0.7.24 ipydatagrid==1.4.0 ipyevents==2.0.2 ipyfilechooser==0.6.0 ipykernel==6.29.5 ipython==8.34.0 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jedi==0.19.2 jeepney==0.9.0 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonref==1.1.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_app_launcher==0.3.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 keyring==25.6.0 kiwisolver==1.4.8 lazy_loader==0.4 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.10.1 matplotlib-inline==0.1.7 mistune==3.1.3 more-itertools==10.6.0 multidict==6.2.0 mypy-extensions==1.0.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 networkx==3.4.2 nodeenv==1.9.1 notebook_shim==0.2.4 numcodecs==0.13.1 numpy==2.2.4 openpyxl==3.1.5 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pathspec==0.12.1 pexpect==4.9.0 photutils==2.0.2 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 puremagic==1.28 py2vega==0.6.1 pycparser==2.22 pydantic==2.11.1 pydantic-extra-types==2.10.3 pydantic-settings==2.8.1 pydantic_core==2.33.0 pyerfa==2.0.1.5 Pygments==2.19.1 pyparsing==3.2.3 pyproject-api==1.9.0 pytest==8.3.5 pytest-arraydiff==0.6.1 pytest-astropy==0.11.0 pytest-astropy-header==0.2.2 pytest-cov==6.0.0 pytest-doctestplus==1.4.0 pytest-filter-subpackage==0.2.0 pytest-mock==3.14.0 pytest-remotedata==0.4.1 python-dateutil==2.9.0.post0 python-dotenv==1.1.0 python-json-logger==3.3.0 pytz==2025.2 pyvo==1.6.1 PyYAML==6.0.2 pyzmq==26.3.0 QtPy==2.4.3 referencing==0.36.2 reproject==0.14.1 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 ruff==0.11.2 scikit-image==0.25.2 scipy==1.15.2 SecretStorage==3.3.3 Send2Trash==1.8.3 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 sortedcontainers==2.4.0 soupsieve==2.6 stack-data==0.6.3 -e git+https://github.com/feder-observatory/stellarphot.git@92f44fc5dc348f6f2e2c553e14c0152cfec390a7#egg=stellarphot stringcase==1.2.0 terminado==0.18.1 tifffile==2025.3.30 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tox==4.25.0 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 virtualenv==20.30.0 wcmatch==10.0 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 yarl==1.18.3 zarr==2.18.3 zipp==3.21.0
name: stellarphot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py310h06a4308_0 - python=3.10.16=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py310h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py310h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aggdraw==1.3.19 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - annotated-types==0.7.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asciitree==0.3.3 - astropy==6.1.7 - astropy-healpix==1.1.2 - astropy-iers-data==0.2025.3.31.0.36.18 - astroquery==0.4.10 - astroscrappy==1.2.0 - astrowidgets==0.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - async-timeout==5.0.1 - attrs==25.3.0 - babel==2.17.0 - backports-tarfile==1.2.0 - beautifulsoup4==4.13.3 - black==25.1.0 - bleach==6.2.0 - bottleneck==1.4.2 - bqplot==0.12.44 - bracex==2.5.post1 - cachetools==5.5.2 - ccdproc==2.4.3 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.1 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2025.3.0 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - distlib==0.3.9 - et-xmlfile==2.0.0 - exceptiongroup==1.2.2 - executing==2.2.0 - fasteners==0.19 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.2 - gast==0.4.0 - ginga==5.2.0 - h11==0.14.0 - html5lib==1.1 - httpcore==1.0.7 - httpx==0.28.1 - hypothesis==6.130.6 - identify==2.6.9 - idna==3.10 - imageio==2.37.0 - immutables==0.21 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipyautoui==0.7.24 - ipydatagrid==1.4.0 - ipyevents==2.0.2 - ipyfilechooser==0.6.0 - ipykernel==6.29.5 - ipython==8.34.0 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jedi==0.19.2 - jeepney==0.9.0 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonref==1.1.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-app-launcher==0.3.2 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - keyring==25.6.0 - kiwisolver==1.4.8 - lazy-loader==0.4 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.10.1 - matplotlib-inline==0.1.7 - mistune==3.1.3 - more-itertools==10.6.0 - multidict==6.2.0 - mypy-extensions==1.0.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - networkx==3.4.2 - nodeenv==1.9.1 - notebook-shim==0.2.4 - numcodecs==0.13.1 - numpy==2.2.4 - openpyxl==3.1.5 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pathspec==0.12.1 - pexpect==4.9.0 - photutils==2.0.2 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - puremagic==1.28 - py2vega==0.6.1 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pydantic-extra-types==2.10.3 - pydantic-settings==2.8.1 - pyerfa==2.0.1.5 - pygments==2.19.1 - pyparsing==3.2.3 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-arraydiff==0.6.1 - pytest-astropy==0.11.0 - pytest-astropy-header==0.2.2 - pytest-cov==6.0.0 - pytest-doctestplus==1.4.0 - pytest-filter-subpackage==0.2.0 - pytest-mock==3.14.0 - pytest-remotedata==0.4.1 - python-dateutil==2.9.0.post0 - python-dotenv==1.1.0 - python-json-logger==3.3.0 - pytz==2025.2 - pyvo==1.6.1 - pyyaml==6.0.2 - pyzmq==26.3.0 - qtpy==2.4.3 - referencing==0.36.2 - reproject==0.14.1 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - ruff==0.11.2 - scikit-image==0.25.2 - scipy==1.15.2 - secretstorage==3.3.3 - send2trash==1.8.3 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - sortedcontainers==2.4.0 - soupsieve==2.6 - stack-data==0.6.3 - stellarphot==1.3.10.dev736+g92f44fc - stringcase==1.2.0 - terminado==0.18.1 - tifffile==2025.3.30 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tox==4.25.0 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - virtualenv==20.30.0 - wcmatch==10.0 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - yarl==1.18.3 - zarr==2.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/stellarphot
[ "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_makes_a_new_item", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_requires_confirmation", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_item_saved_after_confirm", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_item_not_saved_after_cancel", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_selecting_make_new_as_selection_works", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_no_edit_button_when_there_are_no_items", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_edit_button_returns_after_making_new_item", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_save_button_disabled_when_no_changes", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_clicking_revert_button_cancels_edit", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_delete_button_click_displays_confirm_dialog", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_delete_actions_after_confirmation[True]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_delete_actions_after_confirmation[False]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_correct_item_selected_after_delete_and_yes", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_making_new_with_same_name_as_existing[True]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_making_new_with_same_name_as_existing[False]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_weird_sequence_of_no_clicks" ]
[]
[ "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation_without_type_raises_error", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation_unknown_item_type_raises_error", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[camera]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[observatory]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[passband_map]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[Camera]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[PassbandMap]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_creation[Observatory]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_initial_configuration_with_no_items", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[camera-setting0]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[observatory-setting1]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_new_with_existing_item_resets_value[passband_map-setting2]", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_choosing_different_item_updates_display", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_passband_map_buttons_are_disabled_or_enabled", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_make_passband_map", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_revert_button_is_enabled_after_clicking_edit", "stellarphot/settings/tests/test_custom_widgets.py::TestChooseOrMakeNew::test_revert_button_remains_enabled_with_invalid_value_and_actually_reverts", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_initial_value", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_initial_display", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_message", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_widget_structure", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_show[None]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_show[other_widget1]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[None-yes]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[None-no]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[other_widget1-yes]", "stellarphot/settings/tests/test_custom_widgets.py::TestConfirm::test_clicking_yes_or_no[other_widget1-no]" ]
[]
BSD 3-Clause "New" or "Revised" License
18,332
2,947
[ "stellarphot/settings/custom_widgets.py" ]
lbl-anp__becquerel-408
1580ab4bebbf6bccac8a7e16ef045f68a5d497c0
2024-05-03 22:07:58
1580ab4bebbf6bccac8a7e16ef045f68a5d497c0
diff --git a/becquerel/core/spectrum.py b/becquerel/core/spectrum.py index feff92a..a343c78 100644 --- a/becquerel/core/spectrum.py +++ b/becquerel/core/spectrum.py @@ -811,9 +811,9 @@ class Spectrum: kwargs = {"cps": self.cps + other.cps} if self.is_calibrated and other.is_calibrated: - spect_obj = Spectrum(bin_edges_kev=self.bin_edges_kev, **kwargs) + spect_obj = self.__class__(bin_edges_kev=self.bin_edges_kev, **kwargs) else: - spect_obj = Spectrum(bin_edges_raw=self.bin_edges_raw, **kwargs) + spect_obj = self.__class__(bin_edges_raw=self.bin_edges_raw, **kwargs) return spect_obj def __sub__(self, other): @@ -867,9 +867,9 @@ class Spectrum: ) if self.is_calibrated and other.is_calibrated: - spect_obj = Spectrum(bin_edges_kev=self.bin_edges_kev, **kwargs) + spect_obj = self.__class__(bin_edges_kev=self.bin_edges_kev, **kwargs) else: - spect_obj = Spectrum(bin_edges_raw=self.bin_edges_raw, **kwargs) + spect_obj = self.__class__(bin_edges_raw=self.bin_edges_raw, **kwargs) return spect_obj def _add_sub_error_checking(self, other): @@ -990,9 +990,9 @@ class Spectrum: data_arg = {"cps": self.cps * multiplier} if self.is_calibrated: - spect_obj = Spectrum(bin_edges_kev=self.bin_edges_kev, **data_arg) + spect_obj = self.__class__(bin_edges_kev=self.bin_edges_kev, **data_arg) else: - spect_obj = Spectrum(bin_edges_raw=self.bin_edges_raw, **data_arg) + spect_obj = self.__class__(bin_edges_raw=self.bin_edges_raw, **data_arg) return spect_obj def attenuate(self, material, areal_density_gcm2: float, **kwargs): @@ -1083,13 +1083,13 @@ class Spectrum: new_counts = np.random.binomial(old_counts, 1.0 / f) if self.is_calibrated: - return Spectrum( + return self.__class__( counts=new_counts, bin_edges_kev=self.bin_edges_kev, livetime=new_livetime, ) else: - return Spectrum( + return self.__class__( counts=new_counts, bin_edges_raw=self.bin_edges_raw, livetime=new_livetime, @@ -1296,7 +1296,7 @@ class Spectrum: "bin_edges_kev": combined_bin_edges, "livetime": self.livetime, } - obj = Spectrum(**kwargs) + obj = self.__class__(**kwargs) return obj def rebin( @@ -1355,7 +1355,7 @@ class Spectrum: zero_pad_warnings=zero_pad_warnings, include_overflows=include_overflows, ) - return Spectrum( + return self.__class__( counts=out_spec, uncs=np.sqrt(out_spec), bin_edges_kev=out_edges,
replace calls to Spectrum() with self.__class__() etc. Throughout `Spectrum` (and probably other classes) there are many points where a `Spectrum` method returns a new `Spectrum` object by doing `return Spectrum(...)`. However this is kind of bad practice as downstream users may derive their own classes from `Spectrum`, in which case `Spectrum` methods will return a `Spectrum` rather than the subclass. The fix is simple: replace calls to `Spectrum()` (etc.) with `self.__class__()`
lbl-anp/becquerel
diff --git a/tests/spectrum_test.py b/tests/spectrum_test.py index 595d6d8..ce96627 100644 --- a/tests/spectrum_test.py +++ b/tests/spectrum_test.py @@ -1242,3 +1242,28 @@ def test_spectrum_rebin_like(): spec2_rebin = spec2.rebin_like(spec1) assert np.all(np.isclose(spec1.bin_edges_kev, spec2_rebin.bin_edges_kev)) assert np.isclose(spec2.counts_vals.sum(), spec2_rebin.counts_vals.sum()) + + +# ---------------------------------------------- +# Test Spectrum inheritance +# ---------------------------------------------- +class DerivedSpectrum(bq.Spectrum): + pass + + +derived_spec = DerivedSpectrum(make_data()) + + [email protected]( + "spec", + [ + derived_spec + derived_spec, + derived_spec - derived_spec, + derived_spec * 2, + derived_spec / 2, + derived_spec.downsample(f=2), + derived_spec.combine_bins(f=2), + ], +) +def test_spectrum_inheritance(spec): + assert isinstance(spec, DerivedSpectrum)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-asyncio", "pytest-cov", "pytest-xdist", "pytest-mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt", "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asteval==1.0.6 beautifulsoup4==4.13.3 -e git+https://github.com/lbl-anp/becquerel.git@1580ab4bebbf6bccac8a7e16ef045f68a5d497c0#egg=becquerel black==25.1.0 bump2version==1.0.1 certifi==2025.1.31 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 dill==0.3.9 distlib==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 flake8==7.2.0 fonttools==4.56.0 future==1.0.0 h5py==3.13.0 html5lib==1.1 identify==2.6.9 idna==3.10 iminuit==2.30.1 importlib_resources==6.5.2 iniconfig==2.1.0 kiwisolver==1.4.7 llvmlite==0.43.0 lmfit==1.3.3 lxml==5.3.1 matplotlib==3.9.4 mccabe==0.7.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numba==0.60.0 numdifftools==0.9.41 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pathspec==0.12.1 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 pycodestyle==2.13.0 pyflakes==3.3.1 pyparsing==3.2.3 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-black==0.6.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-rerunfailures==15.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 requests==2.32.3 scipy==1.13.1 six==1.17.0 soupsieve==2.6 toml==0.10.2 tomli==2.2.1 typing_extensions==4.13.0 tzdata==2025.2 uncertainties==3.2.2 urllib3==2.3.0 virtualenv==20.29.3 webencodings==0.5.1 zipp==3.21.0
name: becquerel channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asteval==1.0.6 - beautifulsoup4==4.13.3 - becquerel==0.6.0 - black==25.1.0 - bump2version==1.0.1 - certifi==2025.1.31 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - dill==0.3.9 - distlib==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - flake8==7.2.0 - fonttools==4.56.0 - future==1.0.0 - h5py==3.13.0 - html5lib==1.1 - identify==2.6.9 - idna==3.10 - iminuit==2.30.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - kiwisolver==1.4.7 - llvmlite==0.43.0 - lmfit==1.3.3 - lxml==5.3.1 - matplotlib==3.9.4 - mccabe==0.7.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numba==0.60.0 - numdifftools==0.9.41 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pathspec==0.12.1 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-black==0.6.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-rerunfailures==15.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - requests==2.32.3 - scipy==1.13.1 - six==1.17.0 - soupsieve==2.6 - toml==0.10.2 - tomli==2.2.1 - typing-extensions==4.13.0 - tzdata==2025.2 - uncertainties==3.2.2 - urllib3==2.3.0 - virtualenv==20.29.3 - webencodings==0.5.1 - zipp==3.21.0 prefix: /opt/conda/envs/becquerel
[ "tests/spectrum_test.py::test_spectrum_inheritance[spec0]", "tests/spectrum_test.py::test_spectrum_inheritance[spec1]", "tests/spectrum_test.py::test_spectrum_inheritance[spec2]", "tests/spectrum_test.py::test_spectrum_inheritance[spec3]", "tests/spectrum_test.py::test_spectrum_inheritance[spec4]", "tests/spectrum_test.py::test_spectrum_inheritance[spec5]" ]
[]
[ "tests/spectrum_test.py::black", "tests/spectrum_test.py::test_uncal", "tests/spectrum_test.py::test_uncal_cps", "tests/spectrum_test.py::test_cal", "tests/spectrum_test.py::test_init_exceptions", "tests/spectrum_test.py::test_uncalibrated_exception", "tests/spectrum_test.py::test_negative_input", "tests/spectrum_test.py::test_init_with_lists[uncal]", "tests/spectrum_test.py::test_init_with_lists[cal0]", "tests/spectrum_test.py::test_init_with_lists[uncal_long]", "tests/spectrum_test.py::test_init_with_lists[cal1]", "tests/spectrum_test.py::test_listmode_uniform[None-False]", "tests/spectrum_test.py::test_listmode_uniform[None-True]", "tests/spectrum_test.py::test_listmode_uniform[False-False]", "tests/spectrum_test.py::test_listmode_uniform[False-True]", "tests/spectrum_test.py::test_listmode_uniform[True-False]", "tests/spectrum_test.py::test_listmode_uniform[True-True]", "tests/spectrum_test.py::test_listmode_non_uniform[None-False]", "tests/spectrum_test.py::test_listmode_non_uniform[None-True]", "tests/spectrum_test.py::test_listmode_non_uniform[False-False]", "tests/spectrum_test.py::test_listmode_non_uniform[False-True]", "tests/spectrum_test.py::test_listmode_non_uniform[True-False]", "tests/spectrum_test.py::test_listmode_non_uniform[True-True]", "tests/spectrum_test.py::test_listmode_no_args[None-False]", "tests/spectrum_test.py::test_listmode_no_args[None-True]", "tests/spectrum_test.py::test_listmode_no_args[False-False]", "tests/spectrum_test.py::test_listmode_no_args[False-True]", "tests/spectrum_test.py::test_listmode_no_args[True-False]", "tests/spectrum_test.py::test_listmode_no_args[True-True]", "tests/spectrum_test.py::test_listmode_is_cal", "tests/spectrum_test.py::test_find_bin_index[None-False-uniform]", "tests/spectrum_test.py::test_find_bin_index[None-False-log]", "tests/spectrum_test.py::test_find_bin_index[None-True-uniform]", "tests/spectrum_test.py::test_find_bin_index[None-True-log]", "tests/spectrum_test.py::test_find_bin_index[False-False-uniform]", "tests/spectrum_test.py::test_find_bin_index[False-False-log]", "tests/spectrum_test.py::test_find_bin_index[False-True-uniform]", "tests/spectrum_test.py::test_find_bin_index[False-True-log]", "tests/spectrum_test.py::test_find_bin_index[True-False-uniform]", "tests/spectrum_test.py::test_find_bin_index[True-False-log]", "tests/spectrum_test.py::test_find_bin_index[True-True-uniform]", "tests/spectrum_test.py::test_find_bin_index[True-True-log]", "tests/spectrum_test.py::test_index_out_of_bounds[None-False-uniform]", "tests/spectrum_test.py::test_index_out_of_bounds[None-False-default]", "tests/spectrum_test.py::test_index_out_of_bounds[None-False-log]", "tests/spectrum_test.py::test_index_out_of_bounds[None-True-uniform]", "tests/spectrum_test.py::test_index_out_of_bounds[None-True-default]", "tests/spectrum_test.py::test_index_out_of_bounds[None-True-log]", "tests/spectrum_test.py::test_index_out_of_bounds[False-False-uniform]", "tests/spectrum_test.py::test_index_out_of_bounds[False-False-default]", "tests/spectrum_test.py::test_index_out_of_bounds[False-False-log]", "tests/spectrum_test.py::test_index_out_of_bounds[False-True-uniform]", "tests/spectrum_test.py::test_index_out_of_bounds[False-True-default]", "tests/spectrum_test.py::test_index_out_of_bounds[False-True-log]", "tests/spectrum_test.py::test_index_out_of_bounds[True-False-uniform]", "tests/spectrum_test.py::test_index_out_of_bounds[True-False-default]", "tests/spectrum_test.py::test_index_out_of_bounds[True-False-log]", "tests/spectrum_test.py::test_index_out_of_bounds[True-True-uniform]", "tests/spectrum_test.py::test_index_out_of_bounds[True-True-default]", "tests/spectrum_test.py::test_index_out_of_bounds[True-True-log]", "tests/spectrum_test.py::test_bin_index_types[None-False]", "tests/spectrum_test.py::test_bin_index_types[None-True]", "tests/spectrum_test.py::test_bin_index_types[False-False]", "tests/spectrum_test.py::test_bin_index_types[False-True]", "tests/spectrum_test.py::test_bin_index_types[True-False]", "tests/spectrum_test.py::test_bin_index_types[True-True]", "tests/spectrum_test.py::test_repr", "tests/spectrum_test.py::test_str", "tests/spectrum_test.py::test_livetime_arg[86400]", "tests/spectrum_test.py::test_livetime_arg[300.6]", "tests/spectrum_test.py::test_livetime_arg[0.88]", "tests/spectrum_test.py::test_livetime_arg_cps[86400]", "tests/spectrum_test.py::test_livetime_arg_cps[300.6]", "tests/spectrum_test.py::test_livetime_arg_cps[0.88]", "tests/spectrum_test.py::test_no_livetime", "tests/spectrum_test.py::test_acqtime_construction[3600-start0-stop0]", "tests/spectrum_test.py::test_acqtime_construction[3600-2017-01-19", "tests/spectrum_test.py::test_acqtime_construction[3600-start2-2017-01-01", "tests/spectrum_test.py::test_acqtime_construction[2345.6-start0-stop0]", "tests/spectrum_test.py::test_acqtime_construction[2345.6-2017-01-19", "tests/spectrum_test.py::test_acqtime_construction[2345.6-start2-2017-01-01", "tests/spectrum_test.py::test_bad_acqtime_construction[2017-01-19", "tests/spectrum_test.py::test_bad_realtime_livetime", "tests/spectrum_test.py::test_deadtime[counts]", "tests/spectrum_test.py::test_deadtime[cps]", "tests/spectrum_test.py::test_deadtime_err[counts]", "tests/spectrum_test.py::test_deadtime_err[cps]", "tests/spectrum_test.py::test_construct_float_int", "tests/spectrum_test.py::test_construct_ufloat", "tests/spectrum_test.py::test_construct_float_int_uncs", "tests/spectrum_test.py::test_construct_errors", "tests/spectrum_test.py::test_properties", "tests/spectrum_test.py::test_bin_widths_kev", "tests/spectrum_test.py::test_bin_widths_uncal", "tests/spectrum_test.py::test_cps[construction_kwargs0]", "tests/spectrum_test.py::test_cps[construction_kwargs1]", "tests/spectrum_test.py::test_cpskev[86400]", "tests/spectrum_test.py::test_cpskev[300.6]", "tests/spectrum_test.py::test_cpskev[0.88]", "tests/spectrum_test.py::test_cps_cpsspec[86400]", "tests/spectrum_test.py::test_cps_cpsspec[300.6]", "tests/spectrum_test.py::test_cps_cpsspec[0.88]", "tests/spectrum_test.py::test_cps_errors", "tests/spectrum_test.py::test_cpskev_errors", "tests/spectrum_test.py::test_add[uncal-uncal-300-600]", "tests/spectrum_test.py::test_add[uncal-uncal-12.6-0.88]", "tests/spectrum_test.py::test_add[uncal-uncal-300-12.6]", "tests/spectrum_test.py::test_add[uncal-uncal-12.6-None]", "tests/spectrum_test.py::test_add[uncal-uncal-None-None]", "tests/spectrum_test.py::test_add[cal-cal-300-600]", "tests/spectrum_test.py::test_add[cal-cal-12.6-0.88]", "tests/spectrum_test.py::test_add[cal-cal-300-12.6]", "tests/spectrum_test.py::test_add[cal-cal-12.6-None]", "tests/spectrum_test.py::test_add[cal-cal-None-None]", "tests/spectrum_test.py::test_add_sub_errors[uncal-cal-SpectrumError]", "tests/spectrum_test.py::test_add_sub_errors[uncal-uncal_long-SpectrumError]", "tests/spectrum_test.py::test_add_sub_errors[uncal-data-TypeError0]", "tests/spectrum_test.py::test_add_sub_errors[data-uncal-TypeError]", "tests/spectrum_test.py::test_add_sub_errors[uncal-5-TypeError]", "tests/spectrum_test.py::test_add_sub_errors[5-cal-TypeError]", "tests/spectrum_test.py::test_add_sub_errors[cal-asdf-TypeError]", "tests/spectrum_test.py::test_add_sub_errors[asdf-uncal-TypeError]", "tests/spectrum_test.py::test_add_sub_errors[uncal-data-TypeError1]", "tests/spectrum_test.py::test_add_sub_errors[cal-cal_new-NotImplementedError]", "tests/spectrum_test.py::test_add_uncs[uncal-uncal]", "tests/spectrum_test.py::test_add_uncs[cal-cal]", "tests/spectrum_test.py::test_add_sub_cps[uncal_cps-uncal_cps-300-12.6]", "tests/spectrum_test.py::test_add_sub_cps[uncal_cps-uncal_cps-None-12.6]", "tests/spectrum_test.py::test_add_sub_cps[uncal_cps-uncal_cps-None-None]", "tests/spectrum_test.py::test_adddition_errors[uncal-uncal_cps-None-None]", "tests/spectrum_test.py::test_adddition_errors[uncal_cps-uncal-None-None]", "tests/spectrum_test.py::test_adddition_errors[uncal-uncal_cps-300-None]", "tests/spectrum_test.py::test_adddition_errors[uncal_cps-uncal-None-300]", "tests/spectrum_test.py::test_adddition_errors[uncal-uncal_cps-300-600]", "tests/spectrum_test.py::test_adddition_errors[uncal_cps-uncal-600-300]", "tests/spectrum_test.py::test_subtract_counts[uncal-uncal-300-600]", "tests/spectrum_test.py::test_subtract_counts[uncal-uncal-12.6-0.88]", "tests/spectrum_test.py::test_subtract_counts[uncal-uncal-300-12.6]", "tests/spectrum_test.py::test_subtract_counts[cal-cal-300-600]", "tests/spectrum_test.py::test_subtract_counts[cal-cal-12.6-0.88]", "tests/spectrum_test.py::test_subtract_counts[cal-cal-300-12.6]", "tests/spectrum_test.py::test_subtract_errors[uncal-uncal_cps-None-None]", "tests/spectrum_test.py::test_subtract_errors[uncal_cps-uncal-None-None]", "tests/spectrum_test.py::test_subtract_errors[uncal-uncal_cps-None-300]", "tests/spectrum_test.py::test_subtract_errors[uncal_cps-uncal-300-None]", "tests/spectrum_test.py::test_subtract_errors[uncal-uncal_cps-300-None]", "tests/spectrum_test.py::test_subtract_errors[uncal_cps-uncal-None-300]", "tests/spectrum_test.py::test_basic_mul_div[uncal-0.88]", "tests/spectrum_test.py::test_basic_mul_div[uncal-1]", "tests/spectrum_test.py::test_basic_mul_div[uncal-2]", "tests/spectrum_test.py::test_basic_mul_div[uncal-43.6]", "tests/spectrum_test.py::test_basic_mul_div[cal-0.88]", "tests/spectrum_test.py::test_basic_mul_div[cal-1]", "tests/spectrum_test.py::test_basic_mul_div[cal-2]", "tests/spectrum_test.py::test_basic_mul_div[cal-43.6]", "tests/spectrum_test.py::test_cps_mul_div[0.88]", "tests/spectrum_test.py::test_cps_mul_div[1]", "tests/spectrum_test.py::test_cps_mul_div[2]", "tests/spectrum_test.py::test_cps_mul_div[43.6]", "tests/spectrum_test.py::test_uncal_mul_div_uncertainties[uncal-factor0]", "tests/spectrum_test.py::test_uncal_mul_div_uncertainties[uncal-factor1]", "tests/spectrum_test.py::test_uncal_mul_div_uncertainties[uncal-factor2]", "tests/spectrum_test.py::test_uncal_mul_div_uncertainties[cal-factor0]", "tests/spectrum_test.py::test_uncal_mul_div_uncertainties[cal-factor1]", "tests/spectrum_test.py::test_uncal_mul_div_uncertainties[cal-factor2]", "tests/spectrum_test.py::test_mul_div_errors[uncal-uncal-TypeError]", "tests/spectrum_test.py::test_mul_div_errors[uncal-asdf-TypeError]", "tests/spectrum_test.py::test_mul_div_errors[uncal-data-TypeError]", "tests/spectrum_test.py::test_mul_div_errors[uncal-0-ValueError]", "tests/spectrum_test.py::test_mul_div_errors[uncal-inf-ValueError]", "tests/spectrum_test.py::test_mul_div_errors[uncal-nan-ValueError]", "tests/spectrum_test.py::test_mul_div_errors[uncal-type26-ValueError]", "tests/spectrum_test.py::test_mul_div_errors[uncal-type27-ValueError]", "tests/spectrum_test.py::test_attenuate[cal-10.0-Pb]", "tests/spectrum_test.py::test_attenuate[cal-10.0-H2O]", "tests/spectrum_test.py::test_attenuate[cal-10.0-material2]", "tests/spectrum_test.py::test_attenuate[cal--10.0-Pb]", "tests/spectrum_test.py::test_attenuate[cal--10.0-H2O]", "tests/spectrum_test.py::test_attenuate[cal--10.0-material2]", "tests/spectrum_test.py::test_attenuate[cal-0.0-Pb]", "tests/spectrum_test.py::test_attenuate[cal-0.0-H2O]", "tests/spectrum_test.py::test_attenuate[cal-0.0-material2]", "tests/spectrum_test.py::test_attenuate[cal_cps-10.0-Pb]", "tests/spectrum_test.py::test_attenuate[cal_cps-10.0-H2O]", "tests/spectrum_test.py::test_attenuate[cal_cps-10.0-material2]", "tests/spectrum_test.py::test_attenuate[cal_cps--10.0-Pb]", "tests/spectrum_test.py::test_attenuate[cal_cps--10.0-H2O]", "tests/spectrum_test.py::test_attenuate[cal_cps--10.0-material2]", "tests/spectrum_test.py::test_attenuate[cal_cps-0.0-Pb]", "tests/spectrum_test.py::test_attenuate[cal_cps-0.0-H2O]", "tests/spectrum_test.py::test_attenuate[cal_cps-0.0-material2]", "tests/spectrum_test.py::test_calibrate_like", "tests/spectrum_test.py::test_recalibrate_like", "tests/spectrum_test.py::test_calibrate_like_error", "tests/spectrum_test.py::test_calibrate_like_copy", "tests/spectrum_test.py::test_combine_bins[uncal]", "tests/spectrum_test.py::test_combine_bins[cal]", "tests/spectrum_test.py::test_combine_bins[uncal_cps]", "tests/spectrum_test.py::test_combine_bins_padding[uncal]", "tests/spectrum_test.py::test_combine_bins_padding[cal]", "tests/spectrum_test.py::test_combine_bins_padding[uncal_cps]", "tests/spectrum_test.py::test_downsample[2-uncal]", "tests/spectrum_test.py::test_downsample[2-cal]", "tests/spectrum_test.py::test_downsample[1.5-uncal]", "tests/spectrum_test.py::test_downsample[1.5-cal]", "tests/spectrum_test.py::test_downsample[999.99-uncal]", "tests/spectrum_test.py::test_downsample[999.99-cal]", "tests/spectrum_test.py::test_no_downsample", "tests/spectrum_test.py::test_zero_downsample", "tests/spectrum_test.py::test_downsample_handle_livetime", "tests/spectrum_test.py::test_downsample_error", "tests/spectrum_test.py::test_downsample_cps_error", "tests/spectrum_test.py::test_downsample_handle_livetime_error", "tests/spectrum_test.py::test_len[1]", "tests/spectrum_test.py::test_len[8]", "tests/spectrum_test.py::test_len[256]", "tests/spectrum_test.py::test_len[16384]", "tests/spectrum_test.py::test_len_cps[1-86400]", "tests/spectrum_test.py::test_len_cps[1-300.6]", "tests/spectrum_test.py::test_len_cps[1-0.88]", "tests/spectrum_test.py::test_len_cps[8-86400]", "tests/spectrum_test.py::test_len_cps[8-300.6]", "tests/spectrum_test.py::test_len_cps[8-0.88]", "tests/spectrum_test.py::test_len_cps[256-86400]", "tests/spectrum_test.py::test_len_cps[256-300.6]", "tests/spectrum_test.py::test_len_cps[256-0.88]", "tests/spectrum_test.py::test_len_cps[16384-86400]", "tests/spectrum_test.py::test_len_cps[16384-300.6]", "tests/spectrum_test.py::test_len_cps[16384-0.88]", "tests/spectrum_test.py::test_copy_uncal", "tests/spectrum_test.py::test_copy_cal", "tests/spectrum_test.py::test_spectrum_rebin_failure[uncalibrated", "tests/spectrum_test.py::test_spectrum_rebin_failure[calibrated", "tests/spectrum_test.py::test_spectrum_rebin_success[calibrated", "tests/spectrum_test.py::test_spectrum_rebin_like" ]
[]
BSD-3-Clause
18,336
747
[ "becquerel/core/spectrum.py" ]
modflowpy__flopy-2179
8e16aab76b6e4f892fcf7031488324c3d490b75b
2024-05-04 01:36:14
8e16aab76b6e4f892fcf7031488324c3d490b75b
diff --git a/flopy/utils/util_list.py b/flopy/utils/util_list.py index 62fdb5ef..66d2baf3 100644 --- a/flopy/utils/util_list.py +++ b/flopy/utils/util_list.py @@ -296,6 +296,16 @@ class MfList(DataInterface, DataListInterface): fmt_string = "".join(fmts) return fmt_string + def __cast_tabular(self, data): + data = pd.DataFrame(data) + if "kper" in data.dtypes: + groups = data.groupby("kper") + data = {kper: group.drop("kper", axis=1) for kper, group in groups} + for kper, d in data.items(): + self.__cast_dataframe(kper, d) + else: + self.__cast_dataframe(0, data) + # Private method to cast the data argument # Should only be called by the constructor def __cast_data(self, data): @@ -350,15 +360,18 @@ class MfList(DataInterface, DataListInterface): f"{type(d)} at kper {kper}" ) - # A single recarray - same MfList for all stress periods + # A single dataframe + elif isinstance(data, pd.DataFrame): + self.__cast_tabular(data) + + # A single recarray elif isinstance(data, np.recarray): - self.__cast_recarray(0, data) + self.__cast_tabular(data) + # A single ndarray elif isinstance(data, np.ndarray): self.__cast_ndarray(0, data) - # A single dataframe - elif isinstance(data, pd.DataFrame): - self.__cast_dataframe(0, data) + # A single filename elif isinstance(data, str): self.__cast_str(0, data)
feat: support kper column in stress period recarray/dataframe input data I like the idea of a kper column in the dataframe/recarray. We have been kicking that idea around for a while now and should see what it would take to support. _Originally posted by @langevin-usgs in https://github.com/modflowpy/flopy/discussions/2135#discussioncomment-9021953_
modflowpy/flopy
diff --git a/autotest/test_modflow.py b/autotest/test_modflow.py index b0127aaf..c421869d 100644 --- a/autotest/test_modflow.py +++ b/autotest/test_modflow.py @@ -917,17 +917,12 @@ def test_bcs_check(function_tmpdir): ghb = ModflowGhb(mf, stress_period_data={0: [0, 0, 0, 100, 1]}) riv_spd = pd.DataFrame( [[0, 0, 0, 0, 101.0, 10.0, 100.0], [0, 0, 0, 1, 80.0, 10.0, 90.0]], - columns=["per", "k", "i", "j", "stage", "cond", "rbot"], + columns=["kper", "k", "i", "j", "stage", "cond", "rbot"], ) - pers = riv_spd.groupby("per") - riv_spd = {i: pers.get_group(i).drop("per", axis=1) for i in [0]} riv = ModflowRiv( mf, - stress_period_data=riv_spd, - # stress_period_data={ - # 0: [[0, 0, 0, 101, 10, 100], [0, 0, 1, 80, 10, 90]] - # }, + stress_period_data=riv_spd.to_records(index=False), ) chk = ghb.check() assert chk.summary_array["desc"][0] == "BC in inactive cell"
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
3.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 alabaster==0.7.16 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 asttokens==3.0.0 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 black==25.1.0 bleach==6.2.0 bmipy==2.0.1 certifi==2025.1.31 cffconvert==2.0.0 cffi==1.17.1 cftime==1.6.4.post1 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 descartes==1.1.0 distlib==0.3.9 docopt==0.6.2 docutils==0.20.1 entrypoints==0.4 exceptiongroup==1.2.2 execnet==2.1.1 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fiona==1.10.1 flaky==3.8.1 -e git+https://github.com/modflowpy/flopy.git@8e16aab76b6e4f892fcf7031488324c3d490b75b#egg=flopy fonttools==4.56.0 geojson==3.2.0 geopandas==1.0.1 idna==3.10 imageio==2.37.0 imagesize==1.4.1 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipython-genutils==0.2.0 ipywidgets==8.1.5 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==3.2.0 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.6.3 jupyter_client==7.4.9 jupyter_core==5.7.2 jupyter_server==2.10.0 jupyter_server_terminals==0.5.3 jupyterlab==3.5.3 jupyterlab_pygments==0.3.0 jupyterlab_server==2.16.6 jupyterlab_widgets==3.0.13 jupytext==1.16.7 kiwisolver==1.4.7 markdown-it-py==3.0.0 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mdit-py-plugins==0.4.2 mdurl==0.1.2 mistune==3.1.3 modflow-devtools==1.6.0 mypy-extensions==1.0.0 myst-parser==3.0.1 nbclassic==1.2.0 nbclient==0.10.2 nbconvert==7.13.1 nbformat==5.10.4 nbsphinx==0.9.7 nest-asyncio==1.6.0 netCDF4==1.7.2 notebook==6.5.7 notebook_shim==0.2.4 numpy==1.26.4 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pathspec==0.12.1 pexpect==4.9.0 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 pooch==1.8.2 prometheus_client==0.21.1 prompt_toolkit==3.0.50 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 py-cpuinfo==9.0.0 pycparser==2.22 Pygments==2.19.1 pykwalify==1.8.0 PyMetis==2023.1.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pyrsistent==0.20.0 pyshp==2.3.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-benchmark==5.1.0 pytest-cov==6.0.0 pytest-dotenv==0.5.2 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 python-dotenv==1.1.0 python-json-logger==3.3.0 pytz==2025.2 pyvista==0.44.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 rasterstats==0.20.0 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rtds-action==1.1.0 ruamel.yaml==0.18.10 ruamel.yaml.clib==0.2.12 ruff==0.11.2 scipy==1.13.1 scooby==0.10.0 Send2Trash==1.8.3 setuptools-scm==8.2.0 shapely==2.0.7 simplejson==3.20.1 six==1.17.0 sniffio==1.3.1 snowballstemmer==2.2.0 soupsieve==2.6 Sphinx==7.1.2 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 stack-data==0.6.3 syrupy==4.9.1 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 virtualenv==20.29.3 vtk==9.3.1 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 xmipy==1.5.0 zipp==3.21.0
name: flopy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - alabaster==0.7.16 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - asttokens==3.0.0 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - black==25.1.0 - bleach==6.2.0 - bmipy==2.0.1 - certifi==2025.1.31 - cffconvert==2.0.0 - cffi==1.17.1 - cftime==1.6.4.post1 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - descartes==1.1.0 - distlib==0.3.9 - docopt==0.6.2 - docutils==0.20.1 - entrypoints==0.4 - exceptiongroup==1.2.2 - execnet==2.1.1 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fiona==1.10.1 - flaky==3.8.1 - flopy==3.7.0.dev0 - fonttools==4.56.0 - geojson==3.2.0 - geopandas==1.0.1 - idna==3.10 - imageio==2.37.0 - imagesize==1.4.1 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipython-genutils==0.2.0 - ipywidgets==8.1.5 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==3.2.0 - jupyter==1.1.1 - jupyter-client==7.4.9 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.6.3 - jupyter-server==2.10.0 - jupyter-server-terminals==0.5.3 - jupyterlab==3.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.16.6 - jupyterlab-widgets==3.0.13 - jupytext==1.16.7 - kiwisolver==1.4.7 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mdit-py-plugins==0.4.2 - mdurl==0.1.2 - mistune==3.1.3 - modflow-devtools==1.6.0 - mypy-extensions==1.0.0 - myst-parser==3.0.1 - nbclassic==1.2.0 - nbclient==0.10.2 - nbconvert==7.13.1 - nbformat==5.10.4 - nbsphinx==0.9.7 - nest-asyncio==1.6.0 - netcdf4==1.7.2 - notebook==6.5.7 - notebook-shim==0.2.4 - numpy==1.26.4 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pathspec==0.12.1 - pexpect==4.9.0 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pooch==1.8.2 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - py-cpuinfo==9.0.0 - pycparser==2.22 - pygments==2.19.1 - pykwalify==1.8.0 - pymetis==2023.1.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pyrsistent==0.20.0 - pyshp==2.3.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-benchmark==5.1.0 - pytest-cov==6.0.0 - pytest-dotenv==0.5.2 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - python-dotenv==1.1.0 - python-json-logger==3.3.0 - pytz==2025.2 - pyvista==0.44.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - rasterstats==0.20.0 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rtds-action==1.1.0 - ruamel-yaml==0.18.10 - ruamel-yaml-clib==0.2.12 - ruff==0.11.2 - scipy==1.13.1 - scooby==0.10.0 - send2trash==1.8.3 - setuptools-scm==8.2.0 - shapely==2.0.7 - simplejson==3.20.1 - six==1.17.0 - sniffio==1.3.1 - snowballstemmer==2.2.0 - soupsieve==2.6 - sphinx==7.1.2 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - stack-data==0.6.3 - syrupy==4.9.1 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - virtualenv==20.29.3 - vtk==9.3.1 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - xmipy==1.5.0 - zipp==3.21.0 prefix: /opt/conda/envs/flopy
[ "autotest/test_modflow.py::test_bcs_check" ]
[]
[ "autotest/test_modflow.py::test_modflow_load[namfile0]", "autotest/test_modflow.py::test_modflow_load[namfile1]", "autotest/test_modflow.py::test_modflow_load[namfile2]", "autotest/test_modflow.py::test_modflow_load[namfile3]", "autotest/test_modflow.py::test_modflow_load_modelgrid[freyberg]", "autotest/test_modflow.py::test_modflow_load_modelgrid[freyberg_multilayer_transient]", "autotest/test_modflow.py::test_modflow_load_modelgrid[CrnkNic]", "autotest/test_modflow.py::test_modflow_load_when_nam_dne", "autotest/test_modflow.py::test_mbase_modelgrid", "autotest/test_modflow.py::test_mt_modelgrid", "autotest/test_modflow.py::test_free_format_flag", "autotest/test_modflow.py::test_sr", "autotest/test_modflow.py::test_mf6_update_grid", "autotest/test_modflow.py::test_load_twri_grid", "autotest/test_modflow.py::test_mg", "autotest/test_modflow.py::test_dynamic_xll_yll", "autotest/test_modflow.py::test_namfile_readwrite", "autotest/test_modflow.py::test_read_usgs_model_reference", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/twrip.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/twrihfb.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/twri.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/tr2k_s3.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/testsfr2_tab.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/testsfr2.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/test1tr.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/test1ss.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/tc2hufv4.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/swtex4.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/swiex3.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/swiex2_strat.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/swiex1.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/swi2ex4sww.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/str.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/restest.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/mnw1.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/lakeex3.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/l2a_2k.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/l1b2k_bath.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/l1b2k.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/l1a2k.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/ibs2k.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/fhb.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/etsdrt.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/bcf2ss.nam]", "autotest/test_modflow.py::test_mf2005_test_models_loadonly[/flopy/examples/data/mf2005_test/UZFtest2.nam]", "autotest/test_modflow.py::test_write_irch", "autotest/test_modflow.py::test_mflist_external", "autotest/test_modflow.py::test_single_mflist_entry_load", "autotest/test_modflow.py::test_mflist_add_record", "autotest/test_modflow.py::test_checker_on_load[namfile0]", "autotest/test_modflow.py::test_checker_on_load[namfile1]", "autotest/test_modflow.py::test_checker_on_load[namfile2]", "autotest/test_modflow.py::test_checker_on_load[namfile3]", "autotest/test_modflow.py::test_checker_on_load[namfile4]", "autotest/test_modflow.py::test_checker_on_load[namfile5]", "autotest/test_modflow.py::test_checker_on_load[namfile6]", "autotest/test_modflow.py::test_checker_on_load[namfile7]", "autotest/test_modflow.py::test_checker_on_load[namfile8]", "autotest/test_modflow.py::test_checker_on_load[namfile9]", "autotest/test_modflow.py::test_checker_on_load[namfile10]", "autotest/test_modflow.py::test_checker_on_load[namfile11]", "autotest/test_modflow.py::test_checker_on_load[namfile12]", "autotest/test_modflow.py::test_checker_on_load[namfile13]", "autotest/test_modflow.py::test_checker_on_load[namfile14]", "autotest/test_modflow.py::test_checker_on_load[namfile15]", "autotest/test_modflow.py::test_checker_on_load[namfile16]", "autotest/test_modflow.py::test_checker_on_load[namfile17]", "autotest/test_modflow.py::test_checker_on_load[namfile18]", "autotest/test_modflow.py::test_checker_on_load[namfile19]", "autotest/test_modflow.py::test_checker_on_load[namfile20]", "autotest/test_modflow.py::test_checker_on_load[namfile21]", "autotest/test_modflow.py::test_checker_on_load[namfile22]", "autotest/test_modflow.py::test_checker_on_load[namfile23]", "autotest/test_modflow.py::test_checker_on_load[namfile24]", "autotest/test_modflow.py::test_checker_on_load[namfile25]", "autotest/test_modflow.py::test_checker_on_load[namfile26]", "autotest/test_modflow.py::test_manual_check[True]", "autotest/test_modflow.py::test_manual_check[False]", "autotest/test_modflow.py::test_path_params_and_props", "autotest/test_modflow.py::test_properties_check", "autotest/test_modflow.py::test_oc_check", "autotest/test_modflow.py::test_rchload", "autotest/test_modflow.py::test_default_oc_stress_period_data", "autotest/test_modflow.py::test_mfcbc", "autotest/test_modflow.py::test_load_with_list_reader", "autotest/test_modflow.py::test_model_init_time", "autotest/test_modflow.py::test_model_write_time", "autotest/test_modflow.py::test_model_load_time" ]
[]
CC0 1.0 Universal
18,339
438
[ "flopy/utils/util_list.py" ]
pyro-ppl__numpyro-1793
7c3ec50eff96f4bc56fa945fd73f1dee32395888
2024-05-04 14:54:10
7c3ec50eff96f4bc56fa945fd73f1dee32395888
diff --git a/numpyro/contrib/funsor/infer_util.py b/numpyro/contrib/funsor/infer_util.py index 5ee0af27..5e97f82d 100644 --- a/numpyro/contrib/funsor/infer_util.py +++ b/numpyro/contrib/funsor/infer_util.py @@ -1,7 +1,7 @@ # Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 -from collections import defaultdict +from collections import OrderedDict, defaultdict from contextlib import contextmanager import functools import re @@ -220,6 +220,10 @@ def _enum_log_density(model, model_args, model_kwargs, params, sum_op, prod_op): log_prob = scale * log_prob dim_to_name = site["infer"]["dim_to_name"] + + if all(dim == 1 for dim in log_prob.shape) and dim_to_name == OrderedDict(): + log_prob = log_prob.squeeze() + log_prob_factor = funsor.to_funsor( log_prob, output=funsor.Real, dim_to_name=dim_to_name ) diff --git a/numpyro/distributions/constraints.py b/numpyro/distributions/constraints.py index af29eb03..4d9445db 100644 --- a/numpyro/distributions/constraints.py +++ b/numpyro/distributions/constraints.py @@ -34,6 +34,7 @@ __all__ = [ "corr_matrix", "dependent", "greater_than", + "greater_than_eq", "integer_interval", "integer_greater_than", "interval", @@ -42,9 +43,11 @@ __all__ = [ "less_than", "lower_cholesky", "multinomial", + "nonnegative", "nonnegative_integer", "positive", "positive_definite", + "positive_semidefinite", "positive_integer", "real", "real_vector", @@ -291,11 +294,26 @@ class _GreaterThan(Constraint): return jnp.array_equal(self.lower_bound, other.lower_bound) +class _GreaterThanEq(_GreaterThan): + def __call__(self, x): + return x >= self.lower_bound + + def __eq__(self, other): + if not isinstance(other, _GreaterThanEq): + return False + return jnp.array_equal(self.lower_bound, other.lower_bound) + + class _Positive(_SingletonConstraint, _GreaterThan): def __init__(self): super().__init__(0.0) +class _Nonnegative(_SingletonConstraint, _GreaterThanEq): + def __init__(self): + super().__init__(0.0) + + class _IndependentConstraint(Constraint): """ Wraps a constraint by aggregating over ``reinterpreted_batch_ndims``-many @@ -614,6 +632,23 @@ class _PositiveDefinite(_SingletonConstraint): ) +class _PositiveSemiDefinite(_SingletonConstraint): + event_dim = 2 + + def __call__(self, x): + jnp = np if isinstance(x, (np.ndarray, np.generic)) else jax.numpy + # check for symmetric + symmetric = jnp.all(jnp.isclose(x, jnp.swapaxes(x, -2, -1)), axis=(-2, -1)) + # check for the smallest eigenvalue is nonnegative + nonnegative = jnp.linalg.eigh(x)[0][..., 0] >= 0 + return symmetric & nonnegative + + def feasible_like(self, prototype): + return jax.numpy.broadcast_to( + jax.numpy.eye(prototype.shape[-1]), prototype.shape + ) + + class _PositiveOrderedVector(_SingletonConstraint): """ Constrains to a positive real-valued tensor where the elements are monotonically @@ -731,6 +766,7 @@ corr_cholesky = _CorrCholesky() corr_matrix = _CorrMatrix() dependent = _Dependent() greater_than = _GreaterThan +greater_than_eq = _GreaterThanEq less_than = _LessThan independent = _IndependentConstraint integer_interval = _IntegerInterval @@ -740,10 +776,12 @@ l1_ball = _L1Ball() lower_cholesky = _LowerCholesky() scaled_unit_lower_cholesky = _ScaledUnitLowerCholesky() multinomial = _Multinomial +nonnegative = _Nonnegative() nonnegative_integer = _IntegerNonnegative() ordered_vector = _OrderedVector() positive = _Positive() positive_definite = _PositiveDefinite() +positive_semidefinite = _PositiveSemiDefinite() positive_integer = _IntegerPositive() positive_ordered_vector = _PositiveOrderedVector() real = _Real() diff --git a/numpyro/distributions/transforms.py b/numpyro/distributions/transforms.py index a057d86d..b7d984b5 100644 --- a/numpyro/distributions/transforms.py +++ b/numpyro/distributions/transforms.py @@ -1512,11 +1512,13 @@ def _transform_to_corr_matrix(constraint): @biject_to.register(type(constraints.positive)) +@biject_to.register(type(constraints.nonnegative)) def _transform_to_positive(constraint): return ExpTransform() @biject_to.register(constraints.greater_than) +@biject_to.register(constraints.greater_than_eq) def _transform_to_greater_than(constraint): return ComposeTransform( [ @@ -1586,6 +1588,7 @@ def _transform_to_ordered_vector(constraint): @biject_to.register(constraints.positive_definite) +@biject_to.register(constraints.positive_semidefinite) def _transform_to_positive_definite(constraint): return ComposeTransform([LowerCholeskyTransform(), CholeskyTransform().inv])
[FR] Add constraints.greater_than_eq Currently, `constraints.greater_than_eq` is supported in [torch](https://pytorch.org/docs/stable/distributions.html#torch.distributions.constraints.greater_than_eq), but we only have `constraints.greater_than` in numpyro. Can we add an alias for `greater_than_eq` with something like `constraints.interval(x, jnp.inf)` to the constraints namespace (and maybe something for positive semidefinite too)?
pyro-ppl/numpyro
diff --git a/test/contrib/test_funsor.py b/test/contrib/test_funsor.py index ad6037f1..0d403c59 100644 --- a/test/contrib/test_funsor.py +++ b/test/contrib/test_funsor.py @@ -575,3 +575,18 @@ def test_missing_plate(monkeypatch): with pytest.raises(Exception): mcmc.run(random.PRNGKey(2), data) assert len(_PYRO_STACK) == 0 + + [email protected]( + "i_size, j_size, k_size", [(1, 1, 1), (1, 2, 1), (2, 1, 1), (1, 1, 2)] +) +def test_singleton_plate_works(i_size, j_size, k_size): + def model(): + with numpyro.plate("i", i_size, dim=-3): + with numpyro.plate("j", j_size, dim=-2): + with numpyro.plate("k", k_size, dim=-1): + numpyro.sample("a", dist.Normal()) + + model = enum(numpyro.handlers.seed(model, rng_seed=0), first_available_dim=-4) + + log_density(model, (), {}, {}) diff --git a/test/test_constraints.py b/test/test_constraints.py index 67832c47..e413da21 100644 --- a/test/test_constraints.py +++ b/test/test_constraints.py @@ -20,10 +20,12 @@ SINGLETON_CONSTRAINTS = { "l1_ball": constraints.l1_ball, "lower_cholesky": constraints.lower_cholesky, "scaled_unit_lower_cholesky": constraints.scaled_unit_lower_cholesky, + "nonnegative": constraints.nonnegative, "nonnegative_integer": constraints.nonnegative_integer, "ordered_vector": constraints.ordered_vector, "positive": constraints.positive, "positive_definite": constraints.positive_definite, + "positive_semidefinite": constraints.positive_semidefinite, "positive_integer": constraints.positive_integer, "positive_ordered_vector": constraints.positive_ordered_vector, "real": constraints.real, @@ -48,6 +50,7 @@ PARAMETRIZED_CONSTRAINTS = { type(constraints.dependent), (), dict(is_discrete=True, event_dim=2) ), "greater_than": T(constraints.greater_than, (_a(0.0),), dict()), + "greater_than_eq": T(constraints.greater_than_eq, (_a(0.0),), dict()), "less_than": T(constraints.less_than, (_a(-1.0),), dict()), "independent": T( constraints.independent, diff --git a/test/test_transforms.py b/test/test_transforms.py index 4329d8b6..f3534519 100644 --- a/test/test_transforms.py +++ b/test/test_transforms.py @@ -362,6 +362,7 @@ def test_batched_recursive_linear_transform(): (constraints.corr_cholesky, (10, 10)), (constraints.corr_matrix, (21,)), (constraints.greater_than(3), ()), + (constraints.greater_than_eq(3), ()), (constraints.interval(8, 13), (17,)), (constraints.l1_ball, (4,)), (constraints.less_than(-1), ()), @@ -369,6 +370,7 @@ def test_batched_recursive_linear_transform(): (constraints.open_interval(3, 4), ()), (constraints.ordered_vector, (5,)), (constraints.positive_definite, (6,)), + (constraints.positive_semidefinite, (6,)), (constraints.positive_ordered_vector, (7,)), (constraints.positive, (7,)), (constraints.real_matrix, (17,)), @@ -379,6 +381,7 @@ def test_batched_recursive_linear_transform(): (constraints.softplus_lower_cholesky, (21,)), (constraints.softplus_positive, (2,)), (constraints.unit_interval, (4,)), + (constraints.nonnegative, (7,)), ], ids=str, )
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 3 }
0.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev,test,doc,examples]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-xdist" ], "pre_install": [ "apt-get update", "apt-get install -y pandoc graphviz gsfonts" ], "python": "3.9", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
absl-py==2.2.1 alabaster==0.7.16 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 arviz==0.17.1 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 bleach==6.2.0 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 chex==0.1.89 cloudpickle==3.1.1 comm==0.2.2 contourpy==1.3.0 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 dm-haiku==0.0.13 dm-tree==0.1.8 docutils==0.21.2 etils==1.5.2 exceptiongroup==1.2.2 execnet==2.1.1 executing==2.2.0 fastjsonschema==2.21.1 flax==0.8.5 fonttools==4.56.0 fqdn==1.5.1 fsspec==2025.3.1 funsor==0.4.5 gast==0.6.0 graphviz==0.20.3 h11==0.14.0 h5netcdf==1.6.1 h5py==3.13.0 httpcore==1.0.7 httpx==0.28.1 humanize==4.12.2 idna==3.10 imagesize==1.4.1 importlib-metadata==4.13.0 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 isoduration==20.11.0 jax==0.4.30 jaxlib==0.4.30 jaxns==2.4.8 jaxopt==0.8.3 jedi==0.19.2 Jinja2==3.1.6 jmp==0.0.4 joblib==1.4.2 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 makefun==1.15.6 markdown-it-py==3.0.0 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mdurl==0.1.2 mistune==3.1.3 ml_dtypes==0.5.1 msgpack==1.1.0 multipledispatch==1.0.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbsphinx==0.9.7 nest-asyncio==1.6.0 notebook==7.3.3 notebook_shim==0.2.4 numpy==1.26.4 -e git+https://github.com/pyro-ppl/numpyro.git@7c3ec50eff96f4bc56fa945fd73f1dee32395888#egg=numpyro opt_einsum==3.4.0 optax==0.2.4 orbax-checkpoint==0.6.4 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pycparser==2.22 Pygments==2.19.1 pylab-sdk==1.7.2 pyparsing==3.2.3 pyro-api==0.1.2 pytest==8.3.5 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 readthedocs-sphinx-search==0.3.2 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rich==14.0.0 rpds-py==0.24.0 ruff==0.11.2 scikit-learn==1.6.1 scipy==1.13.1 seaborn==0.13.2 Send2Trash==1.8.3 six==1.17.0 sniffio==1.3.1 snowballstemmer==2.2.0 soupsieve==2.6 Sphinx==7.3.7 sphinx-gallery==0.19.0 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 stack-data==0.6.3 tabulate==0.9.0 tensorflow-probability==0.25.0 tensorstore==0.1.69 terminado==0.18.1 threadpoolctl==3.6.0 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 wordcloud==1.9.4 xarray==2024.7.0 xarray-einstats==0.7.0 zipp==3.21.0
name: numpyro channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - absl-py==2.2.1 - alabaster==0.7.16 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - arviz==0.17.1 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - chex==0.1.89 - cloudpickle==3.1.1 - comm==0.2.2 - contourpy==1.3.0 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - dm-haiku==0.0.13 - dm-tree==0.1.8 - docutils==0.21.2 - etils==1.5.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - executing==2.2.0 - fastjsonschema==2.21.1 - flax==0.8.5 - fonttools==4.56.0 - fqdn==1.5.1 - fsspec==2025.3.1 - funsor==0.4.5 - gast==0.6.0 - graphviz==0.20.3 - h11==0.14.0 - h5netcdf==1.6.1 - h5py==3.13.0 - httpcore==1.0.7 - httpx==0.28.1 - humanize==4.12.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.13.0 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jax==0.4.30 - jaxlib==0.4.30 - jaxns==2.4.8 - jaxopt==0.8.3 - jedi==0.19.2 - jinja2==3.1.6 - jmp==0.0.4 - joblib==1.4.2 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - makefun==1.15.6 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mdurl==0.1.2 - mistune==3.1.3 - ml-dtypes==0.5.1 - msgpack==1.1.0 - multipledispatch==1.0.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbsphinx==0.9.7 - nest-asyncio==1.6.0 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==1.26.4 - numpyro==0.14.0 - opt-einsum==3.4.0 - optax==0.2.4 - orbax-checkpoint==0.6.4 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pycparser==2.22 - pygments==2.19.1 - pylab-sdk==1.7.2 - pyparsing==3.2.3 - pyro-api==0.1.2 - pytest==8.3.5 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - readthedocs-sphinx-search==0.3.2 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rich==14.0.0 - rpds-py==0.24.0 - ruff==0.11.2 - scikit-learn==1.6.1 - scipy==1.13.1 - seaborn==0.13.2 - send2trash==1.8.3 - six==1.17.0 - sniffio==1.3.1 - snowballstemmer==2.2.0 - soupsieve==2.6 - sphinx==7.3.7 - sphinx-gallery==0.19.0 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - stack-data==0.6.3 - tabulate==0.9.0 - tensorflow-probability==0.25.0 - tensorstore==0.1.69 - terminado==0.18.1 - threadpoolctl==3.6.0 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - wordcloud==1.9.4 - xarray==2024.7.0 - xarray-einstats==0.7.0 - zipp==3.21.0 prefix: /opt/conda/envs/numpyro
[ "test/contrib/test_funsor.py::test_iteration", "test/contrib/test_funsor.py::test_nesting", "test/contrib/test_funsor.py::test_staggered", "test/contrib/test_funsor.py::test_nested_plate", "test/contrib/test_funsor.py::test_scan_enum_one_latent[1]", "test/contrib/test_funsor.py::test_scan_history[1-2]", "test/contrib/test_funsor.py::test_scan_history[1-3]", "test/contrib/test_funsor.py::test_scan_history[2-2]", "test/contrib/test_funsor.py::test_scan_history[2-3]", "test/contrib/test_funsor.py::test_scan_history[3-2]", "test/contrib/test_funsor.py::test_scan_history[3-3]", "test/contrib/test_funsor.py::test_scan_history[4-3]", "test/contrib/test_funsor.py::test_scan_enum_history_0", "test/contrib/test_funsor.py::test_missing_plate", "test/contrib/test_funsor.py::test_singleton_plate_works[1-1-1]", "test/contrib/test_funsor.py::test_singleton_plate_works[1-2-1]", "test/contrib/test_funsor.py::test_singleton_plate_works[2-1-1]", "test/contrib/test_funsor.py::test_singleton_plate_works[1-1-2]", "test/test_constraints.py::test_singleton_constraint_pytree[boolean]", "test/test_constraints.py::test_singleton_constraint_pytree[circular]", "test/test_constraints.py::test_singleton_constraint_pytree[complex]", "test/test_constraints.py::test_singleton_constraint_pytree[corr_cholesky]", "test/test_constraints.py::test_singleton_constraint_pytree[corr_matrix]", "test/test_constraints.py::test_singleton_constraint_pytree[l1_ball]", "test/test_constraints.py::test_singleton_constraint_pytree[lower_cholesky]", "test/test_constraints.py::test_singleton_constraint_pytree[scaled_unit_lower_cholesky]", "test/test_constraints.py::test_singleton_constraint_pytree[nonnegative]", "test/test_constraints.py::test_singleton_constraint_pytree[nonnegative_integer]", "test/test_constraints.py::test_singleton_constraint_pytree[ordered_vector]", "test/test_constraints.py::test_singleton_constraint_pytree[positive]", "test/test_constraints.py::test_singleton_constraint_pytree[positive_definite]", "test/test_constraints.py::test_singleton_constraint_pytree[positive_semidefinite]", "test/test_constraints.py::test_singleton_constraint_pytree[positive_integer]", "test/test_constraints.py::test_singleton_constraint_pytree[positive_ordered_vector]", "test/test_constraints.py::test_singleton_constraint_pytree[real]", "test/test_constraints.py::test_singleton_constraint_pytree[real_vector]", "test/test_constraints.py::test_singleton_constraint_pytree[real_matrix]", "test/test_constraints.py::test_singleton_constraint_pytree[simplex]", "test/test_constraints.py::test_singleton_constraint_pytree[softplus_lower_cholesky]", "test/test_constraints.py::test_singleton_constraint_pytree[softplus_positive]", "test/test_constraints.py::test_singleton_constraint_pytree[sphere]", "test/test_constraints.py::test_singleton_constraint_pytree[unit_interval]", "test/test_constraints.py::test_parametrized_constraint_pytree[dependent]", "test/test_constraints.py::test_parametrized_constraint_pytree[greater_than]", "test/test_constraints.py::test_parametrized_constraint_pytree[greater_than_eq]", "test/test_constraints.py::test_parametrized_constraint_pytree[less_than]", "test/test_constraints.py::test_parametrized_constraint_pytree[independent]", "test/test_constraints.py::test_parametrized_constraint_pytree[integer_interval]", "test/test_constraints.py::test_parametrized_constraint_pytree[integer_greater_than]", "test/test_constraints.py::test_parametrized_constraint_pytree[interval]", "test/test_constraints.py::test_parametrized_constraint_pytree[multinomial]", "test/test_constraints.py::test_parametrized_constraint_pytree[open_interval]", "test/test_constraints.py::test_parametrized_constraint_pytree[zero_sum]", "test/test_constraints.py::test_parametrized_constraint_eq[dependent]", "test/test_constraints.py::test_parametrized_constraint_eq[greater_than]", "test/test_constraints.py::test_parametrized_constraint_eq[greater_than_eq]", "test/test_constraints.py::test_parametrized_constraint_eq[less_than]", "test/test_constraints.py::test_parametrized_constraint_eq[independent]", "test/test_constraints.py::test_parametrized_constraint_eq[integer_interval]", "test/test_constraints.py::test_parametrized_constraint_eq[integer_greater_than]", "test/test_constraints.py::test_parametrized_constraint_eq[interval]", "test/test_constraints.py::test_parametrized_constraint_eq[multinomial]", "test/test_constraints.py::test_parametrized_constraint_eq[open_interval]", "test/test_constraints.py::test_parametrized_constraint_eq[zero_sum]", "test/test_constraints.py::test_singleton_constraint_eq[boolean]", "test/test_constraints.py::test_singleton_constraint_eq[circular]", "test/test_constraints.py::test_singleton_constraint_eq[complex]", "test/test_constraints.py::test_singleton_constraint_eq[corr_cholesky]", "test/test_constraints.py::test_singleton_constraint_eq[corr_matrix]", "test/test_constraints.py::test_singleton_constraint_eq[l1_ball]", "test/test_constraints.py::test_singleton_constraint_eq[lower_cholesky]", "test/test_constraints.py::test_singleton_constraint_eq[scaled_unit_lower_cholesky]", "test/test_constraints.py::test_singleton_constraint_eq[nonnegative]", "test/test_constraints.py::test_singleton_constraint_eq[nonnegative_integer]", "test/test_constraints.py::test_singleton_constraint_eq[ordered_vector]", "test/test_constraints.py::test_singleton_constraint_eq[positive]", "test/test_constraints.py::test_singleton_constraint_eq[positive_definite]", "test/test_constraints.py::test_singleton_constraint_eq[positive_semidefinite]", "test/test_constraints.py::test_singleton_constraint_eq[positive_integer]", "test/test_constraints.py::test_singleton_constraint_eq[positive_ordered_vector]", "test/test_constraints.py::test_singleton_constraint_eq[real]", "test/test_constraints.py::test_singleton_constraint_eq[real_vector]", "test/test_constraints.py::test_singleton_constraint_eq[real_matrix]", "test/test_constraints.py::test_singleton_constraint_eq[simplex]", "test/test_constraints.py::test_singleton_constraint_eq[softplus_lower_cholesky]", "test/test_constraints.py::test_singleton_constraint_eq[softplus_positive]", "test/test_constraints.py::test_singleton_constraint_eq[sphere]", "test/test_constraints.py::test_singleton_constraint_eq[unit_interval]", "test/test_transforms.py::test_parametrized_transform_pytree[affine]", "test/test_transforms.py::test_parametrized_transform_pytree[compose]", "test/test_transforms.py::test_parametrized_transform_pytree[independent]", "test/test_transforms.py::test_parametrized_transform_pytree[lower_cholesky_affine]", "test/test_transforms.py::test_parametrized_transform_pytree[permute]", "test/test_transforms.py::test_parametrized_transform_pytree[power]", "test/test_transforms.py::test_parametrized_transform_pytree[rfft]", "test/test_transforms.py::test_parametrized_transform_pytree[recursive_linear]", "test/test_transforms.py::test_parametrized_transform_pytree[simplex_to_ordered]", "test/test_transforms.py::test_parametrized_transform_pytree[unpack]", "test/test_transforms.py::test_parametrized_transform_pytree[abs]", "test/test_transforms.py::test_parametrized_transform_pytree[cholesky]", "test/test_transforms.py::test_parametrized_transform_pytree[corr_chol]", "test/test_transforms.py::test_parametrized_transform_pytree[corr_matrix_chol]", "test/test_transforms.py::test_parametrized_transform_pytree[exp]", "test/test_transforms.py::test_parametrized_transform_pytree[identity]", "test/test_transforms.py::test_parametrized_transform_pytree[l1_ball]", "test/test_transforms.py::test_parametrized_transform_pytree[lower_cholesky]", "test/test_transforms.py::test_parametrized_transform_pytree[ordered]", "test/test_transforms.py::test_parametrized_transform_pytree[scaled_unit_lower_cholesky]", "test/test_transforms.py::test_parametrized_transform_pytree[sigmoid]", "test/test_transforms.py::test_parametrized_transform_pytree[softplus]", "test/test_transforms.py::test_parametrized_transform_pytree[softplus_lower_cholesky]", "test/test_transforms.py::test_parametrized_transform_pytree[stick_breaking]", "test/test_transforms.py::test_parametrized_transform_pytree[iaf]", "test/test_transforms.py::test_parametrized_transform_pytree[bna]", "test/test_transforms.py::test_parametrized_transform_pytree[reshape]", "test/test_transforms.py::test_parametrized_transform_pytree[zero_sum]", "test/test_transforms.py::test_parametrized_transform_eq[affine]", "test/test_transforms.py::test_parametrized_transform_eq[compose]", "test/test_transforms.py::test_parametrized_transform_eq[independent]", "test/test_transforms.py::test_parametrized_transform_eq[lower_cholesky_affine]", "test/test_transforms.py::test_parametrized_transform_eq[permute]", "test/test_transforms.py::test_parametrized_transform_eq[power]", "test/test_transforms.py::test_parametrized_transform_eq[rfft]", "test/test_transforms.py::test_parametrized_transform_eq[recursive_linear]", "test/test_transforms.py::test_parametrized_transform_eq[simplex_to_ordered]", "test/test_transforms.py::test_parametrized_transform_eq[unpack]", "test/test_transforms.py::test_parametrized_transform_eq[abs]", "test/test_transforms.py::test_parametrized_transform_eq[cholesky]", "test/test_transforms.py::test_parametrized_transform_eq[corr_chol]", "test/test_transforms.py::test_parametrized_transform_eq[corr_matrix_chol]", "test/test_transforms.py::test_parametrized_transform_eq[exp]", "test/test_transforms.py::test_parametrized_transform_eq[identity]", "test/test_transforms.py::test_parametrized_transform_eq[l1_ball]", "test/test_transforms.py::test_parametrized_transform_eq[lower_cholesky]", "test/test_transforms.py::test_parametrized_transform_eq[ordered]", "test/test_transforms.py::test_parametrized_transform_eq[scaled_unit_lower_cholesky]", "test/test_transforms.py::test_parametrized_transform_eq[sigmoid]", "test/test_transforms.py::test_parametrized_transform_eq[softplus]", "test/test_transforms.py::test_parametrized_transform_eq[softplus_lower_cholesky]", "test/test_transforms.py::test_parametrized_transform_eq[stick_breaking]", "test/test_transforms.py::test_parametrized_transform_eq[iaf]", "test/test_transforms.py::test_parametrized_transform_eq[bna]", "test/test_transforms.py::test_parametrized_transform_eq[reshape]", "test/test_transforms.py::test_parametrized_transform_eq[zero_sum]", "test/test_transforms.py::test_reshape_transform[forward_shape0-inverse_shape0-batch_shape0]", "test/test_transforms.py::test_reshape_transform[forward_shape1-inverse_shape1-batch_shape1]", "test/test_transforms.py::test_reshape_transform[forward_shape2-inverse_shape2-batch_shape2]", "test/test_transforms.py::test_reshape_transform[forward_shape3-inverse_shape3-batch_shape3]", "test/test_transforms.py::test_reshape_transform_invalid", "test/test_transforms.py::test_real_fast_fourier_transform[input_shape0-None-1]", "test/test_transforms.py::test_real_fast_fourier_transform[input_shape1-11-1]", "test/test_transforms.py::test_real_fast_fourier_transform[input_shape2-None-2]", "test/test_transforms.py::test_real_fast_fourier_transform[input_shape3-shape3-2]", "test/test_transforms.py::test_bijective_transforms[transform0-shape0]", "test/test_transforms.py::test_bijective_transforms[transform1-shape1]", "test/test_transforms.py::test_bijective_transforms[transform2-shape2]", "test/test_transforms.py::test_bijective_transforms[transform3-shape3]", "test/test_transforms.py::test_bijective_transforms[transform4-shape4]", "test/test_transforms.py::test_bijective_transforms[transform5-shape5]", "test/test_transforms.py::test_bijective_transforms[transform6-shape6]", "test/test_transforms.py::test_bijective_transforms[transform7-shape7]", "test/test_transforms.py::test_bijective_transforms[transform8-shape8]", "test/test_transforms.py::test_bijective_transforms[transform9-shape9]", "test/test_transforms.py::test_bijective_transforms[transform10-shape10]", "test/test_transforms.py::test_bijective_transforms[transform11-shape11]", "test/test_transforms.py::test_bijective_transforms[transform12-shape12]", "test/test_transforms.py::test_bijective_transforms[transform13-shape13]", "test/test_transforms.py::test_bijective_transforms[transform14-shape14]", "test/test_transforms.py::test_bijective_transforms[transform15-shape15]", "test/test_transforms.py::test_bijective_transforms[transform16-shape16]", "test/test_transforms.py::test_bijective_transforms[transform17-shape17]", "test/test_transforms.py::test_bijective_transforms[transform18-shape18]", "test/test_transforms.py::test_bijective_transforms[transform19-shape19]", "test/test_transforms.py::test_bijective_transforms[transform20-shape20]", "test/test_transforms.py::test_bijective_transforms[transform21-shape21]", "test/test_transforms.py::test_bijective_transforms[transform22-shape22]", "test/test_transforms.py::test_bijective_transforms[transform23-shape23]", "test/test_transforms.py::test_bijective_transforms[transform24-shape24]", "test/test_transforms.py::test_bijective_transforms[transform25-shape25]", "test/test_transforms.py::test_batched_recursive_linear_transform", "test/test_transforms.py::test_biject_to[Circular(lower_bound=-3.141592653589793,", "test/test_transforms.py::test_biject_to[Complex()-(3,)]", "test/test_transforms.py::test_biject_to[CorrCholesky()-(10,", "test/test_transforms.py::test_biject_to[CorrMatrix()-(21,)]", "test/test_transforms.py::test_biject_to[GreaterThan(lower_bound=3)-()]", "test/test_transforms.py::test_biject_to[GreaterThanEq(lower_bound=3)-()]", "test/test_transforms.py::test_biject_to[Interval(lower_bound=8,", "test/test_transforms.py::test_biject_to[L1Ball()-(4,)]", "test/test_transforms.py::test_biject_to[LessThan(upper_bound=-1)-()]", "test/test_transforms.py::test_biject_to[LowerCholesky()-(21,)]", "test/test_transforms.py::test_biject_to[OpenInterval(lower_bound=3,", "test/test_transforms.py::test_biject_to[OrderedVector()-(5,)]", "test/test_transforms.py::test_biject_to[PositiveDefinite()-(6,)]", "test/test_transforms.py::test_biject_to[PositiveSemiDefinite()-(6,)]", "test/test_transforms.py::test_biject_to[PositiveOrderedVector()-(7,)]", "test/test_transforms.py::test_biject_to[Positive(lower_bound=0.0)-(7,)]", "test/test_transforms.py::test_biject_to[RealMatrix(Real(),", "test/test_transforms.py::test_biject_to[RealVector(Real(),", "test/test_transforms.py::test_biject_to[Real()-(3,)]", "test/test_transforms.py::test_biject_to[ScaledUnitLowerCholesky()-(21,)]", "test/test_transforms.py::test_biject_to[Simplex()-(3,)]", "test/test_transforms.py::test_biject_to[SoftplusLowerCholesky()-(21,)]", "test/test_transforms.py::test_biject_to[SoftplusPositive(lower_bound=0.0)-(2,)]", "test/test_transforms.py::test_biject_to[UnitInterval(lower_bound=0.0,", "test/test_transforms.py::test_biject_to[Nonnegative(lower_bound=0.0)-(7,)]" ]
[ "test/contrib/test_funsor.py::test_gaussian_mixture_model", "test/contrib/test_funsor.py::test_bernoulli_latent_model", "test/contrib/test_funsor.py::test_change_point", "test/contrib/test_funsor.py::test_gaussian_hmm", "test/contrib/test_funsor.py::test_scan_enum_one_latent[10]", "test/contrib/test_funsor.py::test_scan_enum_one_latent[11]", "test/contrib/test_funsor.py::test_scan_enum_plate", "test/contrib/test_funsor.py::test_scan_enum_separated_plates_same_dim", "test/contrib/test_funsor.py::test_scan_enum_separated_plate_discrete", "test/contrib/test_funsor.py::test_scan_enum_discrete_outside", "test/contrib/test_funsor.py::test_scan_enum_two_latents", "test/contrib/test_funsor.py::test_scan_enum_scan_enum", "test/contrib/test_funsor.py::test_scan_history[4-2]", "test/contrib/test_funsor.py::test_scan_history[10-2]", "test/contrib/test_funsor.py::test_scan_history[10-3]", "test/contrib/test_funsor.py::test_scan_history[11-2]", "test/contrib/test_funsor.py::test_scan_history[11-3]", "test/contrib/test_funsor.py::test_scan_history[12-2]", "test/contrib/test_funsor.py::test_scan_history[12-3]", "test/contrib/test_funsor.py::test_scan_history[13-2]", "test/contrib/test_funsor.py::test_scan_history[13-3]" ]
[]
[]
Apache License 2.0
18,342
1,360
[ "numpyro/contrib/funsor/infer_util.py", "numpyro/distributions/constraints.py", "numpyro/distributions/transforms.py" ]
lightkurve__lightkurve-1426
143bf0a319195f6c756df753a23c1e146a777608
2024-05-06 23:56:39
a8f26dfa8196e99d9bf93f71d51ad02cbcd826ea
diff --git a/src/lightkurve/periodogram.py b/src/lightkurve/periodogram.py index 2c7c9932..bb3a4211 100644 --- a/src/lightkurve/periodogram.py +++ b/src/lightkurve/periodogram.py @@ -650,7 +650,8 @@ class LombScarglePeriodogram(Periodogram): ls_method="fast", **kwargs ): - """Creates a `Periodogram` from a LightCurve using the Lomb-Scargle method. + """Creates a `Periodogram` from a LightCurve using the Lomb-Scargle method in + `astropy`'s `~astropy.timeseries.LombScargle`. By default, the periodogram will be created for a regular grid of frequencies from one frequency separation to the Nyquist frequency, @@ -768,9 +769,11 @@ class LombScarglePeriodogram(Periodogram): (`'amplitude'`). ls_method : str Default: `'fast'`. Passed to the `method` keyword of - `astropy.stats.LombScargle()`. + `astropy.timeseries.LombScargle()`. kwargs : dict - Keyword arguments passed to `astropy.stats.LombScargle()` + Keyword arguments passed to + `LombScargle() <astropy.timeseries.LombScargle>` + Returns ------- @@ -1019,7 +1022,8 @@ class BoxLeastSquaresPeriodogram(Periodogram): @staticmethod def from_lightcurve(lc, **kwargs): - """Creates a `Periodogram` from a LightCurve using the Box Least Squares (BLS) method. + """Creates a `Periodogram` from a LightCurve using the Box Least Squares (BLS) method + in `astropy`'s `~astropy.timeseries.BoxLeastSquares`. Parameters ---------- diff --git a/src/lightkurve/utils.py b/src/lightkurve/utils.py index f63897ba..fe965d3f 100644 --- a/src/lightkurve/utils.py +++ b/src/lightkurve/utils.py @@ -627,10 +627,20 @@ def centroid_quadratic(data, mask=None): """ if isinstance(data, u.Quantity): data = data.value + + if np.issubdtype(data.dtype, int): + # multiple code paths below require data be of float type + # proactively convert int to float once and for all. + data = data.astype(float) + # Step 1: identify the patch of 3x3 pixels (z_) # that is centered on the brightest pixel (xx, yy) if mask is not None: - data = data * mask + # mask handling. + # Issue 1401 demonstrates that using 'data' to find the max will break when all flux is negative + # set masked pixels NaN (instead of 0) to resolve it. + data = data.copy() + data[~mask] = np.nan arg_data_max = np.nanargmax(data) yy, xx = np.unravel_index(arg_data_max, data.shape) # Make sure the 3x3 patch does not leave the TPF bounds @@ -644,6 +654,13 @@ def centroid_quadratic(data, mask=None): xx = data.shape[1] - 2 z_ = data[yy - 1 : yy + 2, xx - 1 : xx + 2] + if np.any(np.isnan(z_)): + # handle edge case the 3X3 patch has NaN + # Need some finite value for NaN pixels for the + # quadratic fit below: use the mean of the 3x3 patch + # to reduce the skew + z_ = z_.copy() + z_[np.isnan(z_)] = np.nanmean(z_) # Next, we will fit the coefficients of the bivariate quadratic with the # help of a design matrix (A) as defined by Eqn 20 in Vakili & Hogg
`centroid_quadratic()` incorrectly failed in a boundary case, when `mask` is specified and fluxes are all negative <!-- Fill in the information below before opening an issue. --> #### Problem description <!-- Provide a clear and concise description of the issue. --> `lk.utils.centroid_quadratic()` would fail and return `(nan, nan)` in a specific boundary case: - `mask` argument is specified, and - the flux in `data` is all negative. While all negative flux should not happen in normal flux data, they could possibly arise when the data is from a difference flux. #### Example See: https://gist.github.com/orionlee/fb9a855c3f4fe935ef653d72910768ac #### Expected behavior <!-- Describe the behavior you expected and how it differs from the behavior observed in the example. --> It should still return a reasonable centroid. #### Environment - lightkurve version (e.g. 1.0b6): 2.4.2
lightkurve/lightkurve
diff --git a/tests/test_utils.py b/tests/test_utils.py index d58da191..601b36e5 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -165,25 +165,66 @@ def test_centroid_quadratic(): assert np.isclose(row, 5) & np.isclose(col, 1.5) -def test_centroid_quadratic_robustness(): - """Test quadratic centroids in edge cases; regression test for #610.""" +# create a mask that'd mask out first 2 rows +a_mask = np.full((5, 5), True, dtype=bool) +a_mask[0:2, :] = False + [email protected]("data_dtype, mask", [ + (float, None), + (float, a_mask), + (int, None), + (int, a_mask), + ]) +def test_centroid_quadratic_robustness(data_dtype, mask): + """Test quadratic centroids in edge cases; regression test for #610, etc.""" # Brightest pixel in upper left - data = np.zeros((5, 5)) + data = np.zeros((5, 5), dtype=data_dtype) data[0, 0] = 1 - centroid_quadratic(data) + centroid_quadratic(data, mask=mask) + col, row = centroid_quadratic(data, mask=mask) + if mask is None: + assert np.isfinite(col) & np.isfinite(row) + else: + # the mask (of top 2 rows) would make the eligible pixels to be uniformly at 0 + # no centroid can be calculated in such case. + assert np.isnan(col) & np.isnan(row) # Brightest pixel in bottom right - data = np.zeros((5, 5)) + data = np.zeros((5, 5), dtype=data_dtype) data[-1, -1] = 1 - centroid_quadratic(data) + col, row = centroid_quadratic(data, mask=mask) + assert np.isfinite(col) & np.isfinite(row) # Data contains a NaN - data = np.zeros((5, 5)) - data[0, 0] = np.nan - data[-1, -1] = 10 - col, row = centroid_quadratic(data) + if data_dtype is float: # NaN only applicable to float + data = np.zeros((5, 5), dtype=data_dtype) + data[0, 0] = np.nan + data[-1, -1] = 10 + col, row = centroid_quadratic(data, mask=mask) + assert np.isfinite(col) & np.isfinite(row) + + # has NaN in the identified 3x3 patch + if data_dtype is float: # NaN only applicable to float + data = np.zeros((5, 5), dtype=data_dtype) + data[3, 2] = 10 + data[3, 3] = np.nan + col, row = centroid_quadratic(data, mask=mask) + assert np.isfinite(col) & np.isfinite(row) + + # Data contains are all negative (#1401 case `mask` is specified) + # e.g., in a difference image + data = np.full((5, 5), -9, dtype=data_dtype) + data[3, 2] = -5 + col, row = centroid_quadratic(data, mask=mask) assert np.isfinite(col) & np.isfinite(row) + # case the 3x3 patch contains masked pixels + if mask is not None: + data = np.zeros((5, 5), dtype=data_dtype) + data[2, 1] = 10 # the row above is masked + col, row = centroid_quadratic(data, mask=mask) + assert np.isfinite(col) & np.isfinite(row) + def test_show_citation_instructions(): show_citation_instructions()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
2.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astropy==6.0.1 astropy-iers-data==0.2025.3.31.0.36.18 astroquery==0.4.10 autograd==1.7.0 backports.tarfile==1.2.0 beautifulsoup4==4.13.3 bokeh==3.4.3 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work fbpca==1.0 fonttools==4.56.0 html5lib==1.1 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jeepney==0.9.0 Jinja2==3.1.6 joblib==1.4.2 keyring==25.6.0 kiwisolver==1.4.7 -e git+https://github.com/lightkurve/lightkurve.git@143bf0a319195f6c756df753a23c1e146a777608#egg=lightkurve MarkupSafe==3.0.2 matplotlib==3.9.4 memoization==0.4.0 more-itertools==10.6.0 numpy==1.26.4 oktopus==0.1.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 patsy==1.0.1 pillow==11.1.0 pluggy @ file:///croot/pluggy_1733169602837/work pycparser==2.22 pyerfa==2.0.1.5 pyparsing==3.2.3 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 pyvo==1.6.1 PyYAML==6.0.2 requests==2.32.3 scikit-learn==1.6.1 scipy==1.13.1 SecretStorage==3.3.3 six==1.17.0 soupsieve==2.6 threadpoolctl==3.6.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tornado==6.4.2 tqdm==4.67.1 typing_extensions==4.13.0 tzdata==2025.2 uncertainties==3.2.2 urllib3==2.3.0 webencodings==0.5.1 xyzservices==2025.1.0 zipp==3.21.0
name: lightkurve channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astropy==6.0.1 - astropy-iers-data==0.2025.3.31.0.36.18 - astroquery==0.4.10 - autograd==1.7.0 - backports-tarfile==1.2.0 - beautifulsoup4==4.13.3 - bokeh==3.4.3 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - fbpca==1.0 - fonttools==4.56.0 - html5lib==1.1 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jeepney==0.9.0 - jinja2==3.1.6 - joblib==1.4.2 - keyring==25.6.0 - kiwisolver==1.4.7 - lightkurve==2.5.0.dev0 - markupsafe==3.0.2 - matplotlib==3.9.4 - memoization==0.4.0 - more-itertools==10.6.0 - numpy==1.26.4 - oktopus==0.1.2 - pandas==2.2.3 - patsy==1.0.1 - pillow==11.1.0 - pycparser==2.22 - pyerfa==2.0.1.5 - pyparsing==3.2.3 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyvo==1.6.1 - pyyaml==6.0.2 - requests==2.32.3 - scikit-learn==1.6.1 - scipy==1.13.1 - secretstorage==3.3.3 - six==1.17.0 - soupsieve==2.6 - threadpoolctl==3.6.0 - tornado==6.4.2 - tqdm==4.67.1 - typing-extensions==4.13.0 - tzdata==2025.2 - uncertainties==3.2.2 - urllib3==2.3.0 - webencodings==0.5.1 - xyzservices==2025.1.0 - zipp==3.21.0 prefix: /opt/conda/envs/lightkurve
[ "tests/test_utils.py::test_centroid_quadratic_robustness[float-None]", "tests/test_utils.py::test_centroid_quadratic_robustness[float-mask1]", "tests/test_utils.py::test_centroid_quadratic_robustness[int-mask3]" ]
[]
[ "tests/test_utils.py::test_channel_to_module_output", "tests/test_utils.py::test_module_output_to_channel", "tests/test_utils.py::test_running_mean", "tests/test_utils.py::test_quality_flag_decoding_kepler", "tests/test_utils.py::test_quality_flag_decoding_tess", "tests/test_utils.py::test_quality_flag_decoding_quantity_object", "tests/test_utils.py::test_quality_mask", "tests/test_utils.py::test_validate_method", "tests/test_utils.py::test_import", "tests/test_utils.py::test_btjd_bkjd_input", "tests/test_utils.py::test_centroid_quadratic", "tests/test_utils.py::test_centroid_quadratic_robustness[int-None]", "tests/test_utils.py::test_show_citation_instructions" ]
[]
MIT License
18,356
966
[ "src/lightkurve/periodogram.py", "src/lightkurve/utils.py" ]
vyperlang__vyper-4007
4c66c8c10a9164e464a3cf786bc199f854a9beac
2024-05-07 10:51:15
f444c8fa3b02f34181cfa8768bcf572aedc29659
Leminkay: LGTM! charles-cooper: @DanielSchiavini update the commit message please with a description of how the change was arrived at, and i'll merge codecov-commenter: ## [Codecov](https://app.codecov.io/gh/vyperlang/vyper/pull/4007?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=vyperlang) Report Attention: Patch coverage is `0%` with `4 lines` in your changes are missing coverage. Please review. > Project coverage is 47.96%. Comparing base [(`fb55f4c`)](https://app.codecov.io/gh/vyperlang/vyper/commit/fb55f4c79654074e1abe9d202539366684c77b00?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=vyperlang) to head [(`93d1bb7`)](https://app.codecov.io/gh/vyperlang/vyper/pull/4007?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=vyperlang). > Report is 1 commits behind head on master. | [Files](https://app.codecov.io/gh/vyperlang/vyper/pull/4007?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=vyperlang) | Patch % | Lines | |---|---|---| | [vyper/semantics/analysis/local.py](https://app.codecov.io/gh/vyperlang/vyper/pull/4007?src=pr&el=tree&filepath=vyper%2Fsemantics%2Fanalysis%2Flocal.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=vyperlang#diff-dnlwZXIvc2VtYW50aWNzL2FuYWx5c2lzL2xvY2FsLnB5) | 0.00% | [4 Missing :warning: ](https://app.codecov.io/gh/vyperlang/vyper/pull/4007?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=vyperlang) | :exclamation: Your organization needs to install the [Codecov GitHub app](https://github.com/apps/codecov/installations/select_target) to enable full functionality. <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## master #4007 +/- ## =========================================== - Coverage 90.92% 47.96% -42.96% =========================================== Files 105 105 Lines 15246 15247 +1 Branches 3357 3358 +1 =========================================== - Hits 13862 7313 -6549 - Misses 947 7326 +6379 - Partials 437 608 +171 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/vyperlang/vyper/pull/4007?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=vyperlang). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=vyperlang).
diff --git a/vyper/semantics/analysis/local.py b/vyper/semantics/analysis/local.py index 5b20ef77..26c6a4ef 100644 --- a/vyper/semantics/analysis/local.py +++ b/vyper/semantics/analysis/local.py @@ -914,14 +914,14 @@ class ExprVisitor(VyperNodeVisitorBase): else: base_type = get_exact_type_from_node(node.value) - # get the correct type for the index, it might - # not be exactly base_type.key_type - # note: index_type is validated in types_from_Subscript - index_types = get_possible_types_from_node(node.slice) - index_type = index_types.pop() + if isinstance(base_type, HashMapT): + index_type = base_type.key_type + else: + # Arrays allow most int types as index: Take the least specific + index_type = get_possible_types_from_node(node.slice).pop() - self.visit(node.slice, index_type) self.visit(node.value, base_type) + self.visit(node.slice, index_type) def visit_Tuple(self, node: vy_ast.Tuple, typ: VyperType) -> None: if isinstance(typ, TYPE_T):
HashMap index checks when the subscript is folded per @Leminkay ### Version Information vyper Version (output of vyper --version): 6f09e2966b8096d8d36a85ad8745d56691dd25c4 ### Issue description and/or POC ```vyper m: HashMap[uint256, uint256] @external def foo(): self.m[0-1] = 2 ``` Successfully compiles introduced in https://github.com/vyperlang/vyper/pull/3669, _related_ bug was fixed in https://github.com/vyperlang/vyper/pull/3924 (but this bug was not fixed)
vyperlang/vyper
diff --git a/tests/functional/codegen/storage_variables/test_getters.py b/tests/functional/codegen/storage_variables/test_getters.py index 5169bd30..e581d712 100644 --- a/tests/functional/codegen/storage_variables/test_getters.py +++ b/tests/functional/codegen/storage_variables/test_getters.py @@ -1,3 +1,9 @@ +import pytest + +from vyper import compile_code +from vyper.exceptions import OverflowException, TypeMismatch + + def test_state_accessor(get_contract): state_accessor = """ y: HashMap[int128, int128] @@ -98,3 +104,32 @@ def __init__(): if item["type"] == "constructor": continue assert item["stateMutability"] == "view" + + [email protected]( + "typ,index,expected_error", + [ + ("uint256", "-1", TypeMismatch), + ("uint256", "0-1", TypeMismatch), + ("uint256", "0-1+1", TypeMismatch), + ("uint256", "2**256", OverflowException), + ("uint256", "2**256 // 2", OverflowException), + ("uint256", "2 * 2**255", OverflowException), + ("int256", "-2**255", TypeMismatch), + ("int256", "-2**256", OverflowException), + ("int256", "2**255", TypeMismatch), + ("int256", "2**256 - 5", OverflowException), + ("int256", "2 * 2**254", TypeMismatch), + ("int8", "*".join(["2"] * 7), TypeMismatch), + ], +) +def test_hashmap_index_checks(typ, index, expected_error): + code = f""" +m: HashMap[{typ}, uint256] + +@external +def foo(): + self.m[{index}] = 2 + """ + with pytest.raises(expected_error): + compile_code(code)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_git_commit_hash", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-split pytest-instafail", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc git libgmp-dev" ], "python": "3.11", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 altgraph==0.17.4 annotated-types==0.7.0 asttokens==2.4.1 attrs==25.3.0 backports.tarfile==1.2.0 bitarray==3.3.0 black==23.12.0 cached-property==2.0.1 cbor2==5.6.5 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 ckzg==2.1.0 click==8.1.8 coverage==7.8.0 cryptography==44.0.2 cytoolz==1.0.1 decorator==5.2.1 distlib==0.3.9 docutils==0.21.2 eth-account==0.12.2 eth-bloom==3.1.0 eth-hash==0.7.1 eth-keyfile==0.9.1 eth-keys==0.6.1 eth-rlp==2.2.0 eth-stdlib==0.2.7 eth-typing==5.2.0 eth-utils==5.2.0 eth_abi==5.2.0 execnet==2.1.1 executing==2.2.0 filelock==3.18.0 flake8==6.1.0 flake8-bugbear==23.12.2 flake8-use-fstring==1.4 frozenlist==1.5.0 hexbytes==1.3.0 hypothesis==6.130.5 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipython==9.0.2 ipython_pygments_lexers==1.1.1 isort==5.13.2 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jedi==0.19.2 jeepney==0.9.0 keyring==25.6.0 lark==1.1.9 lru-dict==1.3.0 markdown-it-py==3.0.0 matplotlib-inline==0.1.7 mccabe==0.7.0 mdurl==0.1.2 more-itertools==10.6.0 multidict==6.2.0 mypy==1.5.0 mypy-extensions==1.0.0 nh3==0.2.21 nodeenv==1.9.1 packaging==23.2 parsimonious==0.10.0 parso==0.8.4 pathspec==0.12.1 pexpect==4.9.0 pkginfo==1.12.1.2 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prompt_toolkit==3.0.50 propcache==0.3.1 ptyprocess==0.7.0 pure_eval==0.2.3 py-ecc==7.0.1 py-evm==0.10.1b2 pycodestyle==2.11.1 pycparser==2.22 pycryptodome==3.22.0 pydantic==2.11.1 pydantic_core==2.33.0 pyflakes==3.1.0 Pygments==2.19.1 pyinstaller==6.12.0 pyinstaller-hooks-contrib==2025.2 pyrevm==0.3.3 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==4.1.0 pytest-instafail==0.5.0 pytest-split==0.10.0 pytest-xdist==3.3.1 PyYAML==6.0.2 readme_renderer==44.0 regex==2024.11.6 requests==2.32.3 requests-toolbelt==1.0.0 rfc3986==2.0.0 rich==14.0.0 rlp==4.1.0 SecretStorage==3.3.3 six==1.17.0 sortedcontainers==2.4.0 stack-data==0.6.3 toolz==1.0.0 traitlets==5.14.3 trie==3.1.0 twine==6.0.1 typing-inspection==0.4.0 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3 -e git+https://github.com/vyperlang/vyper.git@4c66c8c10a9164e464a3cf786bc199f854a9beac#egg=vyper wcwidth==0.2.13 yarl==1.18.3 zipp==3.21.0
name: vyper channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py311h06a4308_0 - pluggy=1.5.0=py311h06a4308_0 - pytest=8.3.4=py311h06a4308_0 - python=3.11.11=he870216_0 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py311h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py311h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - altgraph==0.17.4 - annotated-types==0.7.0 - asttokens==2.4.1 - attrs==25.3.0 - backports-tarfile==1.2.0 - bitarray==3.3.0 - black==23.12.0 - cached-property==2.0.1 - cbor2==5.6.5 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - ckzg==2.1.0 - click==8.1.8 - coverage==7.8.0 - cryptography==44.0.2 - cytoolz==1.0.1 - decorator==5.2.1 - distlib==0.3.9 - docutils==0.21.2 - eth-abi==5.2.0 - eth-account==0.12.2 - eth-bloom==3.1.0 - eth-hash==0.7.1 - eth-keyfile==0.9.1 - eth-keys==0.6.1 - eth-rlp==2.2.0 - eth-stdlib==0.2.7 - eth-typing==5.2.0 - eth-utils==5.2.0 - execnet==2.1.1 - executing==2.2.0 - filelock==3.18.0 - flake8==6.1.0 - flake8-bugbear==23.12.2 - flake8-use-fstring==1.4 - frozenlist==1.5.0 - hexbytes==1.3.0 - hypothesis==6.130.5 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - ipython==9.0.2 - ipython-pygments-lexers==1.1.1 - isort==5.13.2 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jedi==0.19.2 - jeepney==0.9.0 - keyring==25.6.0 - lark==1.1.9 - lru-dict==1.3.0 - markdown-it-py==3.0.0 - matplotlib-inline==0.1.7 - mccabe==0.7.0 - mdurl==0.1.2 - more-itertools==10.6.0 - multidict==6.2.0 - mypy==1.5.0 - mypy-extensions==1.0.0 - nh3==0.2.21 - nodeenv==1.9.1 - packaging==23.2 - parsimonious==0.10.0 - parso==0.8.4 - pathspec==0.12.1 - pexpect==4.9.0 - pkginfo==1.12.1.2 - platformdirs==4.3.7 - pre-commit==4.2.0 - prompt-toolkit==3.0.50 - propcache==0.3.1 - ptyprocess==0.7.0 - pure-eval==0.2.3 - py-ecc==7.0.1 - py-evm==0.10.1b2 - pycodestyle==2.11.1 - pycparser==2.22 - pycryptodome==3.22.0 - pydantic==2.11.1 - pydantic-core==2.33.0 - pyflakes==3.1.0 - pygments==2.19.1 - pyinstaller==6.12.0 - pyinstaller-hooks-contrib==2025.2 - pyrevm==0.3.3 - pytest-cov==4.1.0 - pytest-instafail==0.5.0 - pytest-split==0.10.0 - pytest-xdist==3.3.1 - pyyaml==6.0.2 - readme-renderer==44.0 - regex==2024.11.6 - requests==2.32.3 - requests-toolbelt==1.0.0 - rfc3986==2.0.0 - rich==14.0.0 - rlp==4.1.0 - secretstorage==3.3.3 - six==1.17.0 - sortedcontainers==2.4.0 - stack-data==0.6.3 - toolz==1.0.0 - traitlets==5.14.3 - trie==3.1.0 - twine==6.0.1 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - urllib3==2.3.0 - virtualenv==20.29.3 - vyper==0.4.0rc4 - wcwidth==0.2.13 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/vyper
[ "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[uint256-0-1-TypeMismatch]", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[uint256-0-1+1-TypeMismatch]", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[uint256-2" ]
[]
[ "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[uint256--1-TypeMismatch]", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[int256--2**256-OverflowException]", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[int256--2**255-TypeMismatch]", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[int256-2", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[uint256-2**256", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[int256-2**255-TypeMismatch]", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[int8-2*2*2*2*2*2*2-TypeMismatch]", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[int256-2**256", "tests/functional/codegen/storage_variables/test_getters.py::test_hashmap_index_checks[uint256-2**256-OverflowException]", "tests/functional/codegen/storage_variables/test_getters.py::test_state_accessor", "tests/functional/codegen/storage_variables/test_getters.py::test_getter_mutability", "tests/functional/codegen/storage_variables/test_getters.py::test_getter_code" ]
[]
Apache License 2.0
18,359
293
[ "vyper/semantics/analysis/local.py" ]
tobymao__sqlglot-3417
e1b6483d5e26d556f6a3dd82c6d35f475c189c2b
2024-05-07 12:21:37
e1b6483d5e26d556f6a3dd82c6d35f475c189c2b
diff --git a/sqlglot/parser.py b/sqlglot/parser.py index b0a25167..51022bbe 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -5974,7 +5974,7 @@ class Parser(metaclass=_Parser): if kind in ("GLOBAL", "SESSION") and self._match_text_seq("TRANSACTION"): return self._parse_set_transaction(global_=kind == "GLOBAL") - left = self._parse_primary() or self._parse_id_var() + left = self._parse_primary() or self._parse_column() assignment_delimiter = self._match_texts(("=", "TO")) if not left or (self.SET_REQUIRES_ASSIGNMENT_DELIMITER and not assignment_delimiter):
SET TAG identifier containing dots is parsed as Command Would love for an identifier containing dots to be parsed as a `SetItem` ie: like an identifier without dots. Without dots, is parsed as SetItem: ``` ❯ sqlglot.parse_one("ALTER TABLE table1 SET TAG foo='baz'", read="snowflake") AlterTable( this=Table( this=Identifier(this=table1, quoted=False)), actions=[ Set( expressions=[ SetItem( this=EQ( this=Identifier(this=foo, quoted=False), expression=Literal(this=baz, is_string=True)))], unset=False, tag=True)]) ``` vs with dots: ``` ❯ sqlglot.parse_one("ALTER TABLE table1 SET TAG foo.bar='baz'", read="snowflake") AlterTable( this=Table( this=Identifier(this=table1, quoted=False)), actions=[ Command(this=TAG, expression=foo.bar='baz')]) ``` In sqlglot 15 this was parsed as SetTag: ``` ❯ python -c 'import sqlglot; print(repr(sqlglot.parse_one("ALTER TABLE table1 SET TAG foo.bar=''baz''", read="snowflake")));' (ALTERTABLE this: (TABLE this: (IDENTIFIER this: table1, quoted: False)), actions: (SETTAG expressions: (EQ this: (COLUMN this: (IDENTIFIER this: bar, quoted: False), table: (IDENTIFIER this: foo, quoted: False)), expression: (LITERAL this: baz, is_string: True)), unset: False)) ```
tobymao/sqlglot
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py index dae83557..97b83ab9 100644 --- a/tests/dialects/test_snowflake.py +++ b/tests/dialects/test_snowflake.py @@ -10,14 +10,6 @@ class TestSnowflake(Validator): dialect = "snowflake" def test_snowflake(self): - self.validate_identity( - "MERGE INTO my_db AS ids USING (SELECT new_id FROM my_model WHERE NOT col IS NULL) AS new_ids ON ids.type = new_ids.type AND ids.source = new_ids.source WHEN NOT MATCHED THEN INSERT VALUES (new_ids.new_id)" - ) - self.validate_identity("ALTER TABLE table1 CLUSTER BY (name DESC)") - self.validate_identity( - "INSERT OVERWRITE TABLE t SELECT 1", "INSERT OVERWRITE INTO t SELECT 1" - ) - self.validate_identity("SELECT rename, replace") expr = parse_one("SELECT APPROX_TOP_K(C4, 3, 5) FROM t") expr.selects[0].assert_is(exp.AggFunc) self.assertEqual(expr.sql(dialect="snowflake"), "SELECT APPROX_TOP_K(C4, 3, 5) FROM t") @@ -43,6 +35,9 @@ WHERE )""", ) + self.validate_identity("ALTER TABLE table1 CLUSTER BY (name DESC)") + self.validate_identity("SELECT rename, replace") + self.validate_identity("ALTER TABLE table1 SET TAG foo.bar = 'baz'") self.validate_identity("SELECT TIMEADD(HOUR, 2, CAST('09:05:03' AS TIME))") self.validate_identity("SELECT CAST(OBJECT_CONSTRUCT('a', 1) AS MAP(VARCHAR, INT))") self.validate_identity("SELECT CAST(OBJECT_CONSTRUCT('a', 1) AS OBJECT(a CHAR NOT NULL))") @@ -95,6 +90,12 @@ WHERE self.validate_identity("SELECT CONVERT_TIMEZONE('UTC', 'America/Los_Angeles', col)") self.validate_identity("ALTER TABLE a SWAP WITH b") self.validate_identity("SELECT MATCH_CONDITION") + self.validate_identity( + "MERGE INTO my_db AS ids USING (SELECT new_id FROM my_model WHERE NOT col IS NULL) AS new_ids ON ids.type = new_ids.type AND ids.source = new_ids.source WHEN NOT MATCHED THEN INSERT VALUES (new_ids.new_id)" + ) + self.validate_identity( + "INSERT OVERWRITE TABLE t SELECT 1", "INSERT OVERWRITE INTO t SELECT 1" + ) self.validate_identity( 'DESCRIBE TABLE "SNOWFLAKE_SAMPLE_DATA"."TPCDS_SF100TCL"."WEB_SITE" type=stage' ) diff --git a/tests/test_parser.py b/tests/test_parser.py index 6bcdb643..1b9639a7 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -503,7 +503,7 @@ class TestParser(unittest.TestCase): self.assertIsInstance(set_item, exp.SetItem) self.assertIsInstance(set_item.this, exp.EQ) - self.assertIsInstance(set_item.this.this, exp.Identifier) + self.assertIsInstance(set_item.this.this, exp.Column) self.assertIsInstance(set_item.this.expression, exp.Literal) self.assertEqual(set_item.args.get("kind"), "SESSION")
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
23.13
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio", "pre-commit" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 coverage==7.8.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.3.2 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@e1b6483d5e26d556f6a3dd82c6d35f475c189c2b#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - coverage==7.8.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.3.2 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/test_parser.py::TestParser::test_set_expression" ]
[]
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_copy", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_describe_table", "tests/dialects/test_snowflake.py::TestSnowflake::test_flatten", "tests/dialects/test_snowflake.py::TestSnowflake::test_historical_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_snowflake.py::TestSnowflake::test_minus", "tests/dialects/test_snowflake.py::TestSnowflake::test_null_treatment", "tests/dialects/test_snowflake.py::TestSnowflake::test_parse_like_any", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_replace", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_substr", "tests/dialects/test_snowflake.py::TestSnowflake::test_sample", "tests/dialects/test_snowflake.py::TestSnowflake::test_semi_structured_types", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_columns", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_imported_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_objects", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_primary_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_schemas", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_sequences", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_tables", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_unique_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_users", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_views", "tests/dialects/test_snowflake.py::TestSnowflake::test_staged_files", "tests/dialects/test_snowflake.py::TestSnowflake::test_storage_integration", "tests/dialects/test_snowflake.py::TestSnowflake::test_stored_procedures", "tests/dialects/test_snowflake.py::TestSnowflake::test_swap", "tests/dialects/test_snowflake.py::TestSnowflake::test_table_literal", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/dialects/test_snowflake.py::TestSnowflake::test_try_cast", "tests/dialects/test_snowflake.py::TestSnowflake::test_user_defined_functions", "tests/dialects/test_snowflake.py::TestSnowflake::test_values", "tests/test_parser.py::TestParser::test_column", "tests/test_parser.py::TestParser::test_command", "tests/test_parser.py::TestParser::test_comment_error_n", "tests/test_parser.py::TestParser::test_comment_error_r", "tests/test_parser.py::TestParser::test_comments_delete", "tests/test_parser.py::TestParser::test_comments_delete_cte", "tests/test_parser.py::TestParser::test_comments_insert", "tests/test_parser.py::TestParser::test_comments_insert_cte", "tests/test_parser.py::TestParser::test_comments_select", "tests/test_parser.py::TestParser::test_comments_select_cte", "tests/test_parser.py::TestParser::test_comments_update", "tests/test_parser.py::TestParser::test_comments_update_cte", "tests/test_parser.py::TestParser::test_create_table_error", "tests/test_parser.py::TestParser::test_distinct_from", "tests/test_parser.py::TestParser::test_expression", "tests/test_parser.py::TestParser::test_float", "tests/test_parser.py::TestParser::test_identify", "tests/test_parser.py::TestParser::test_lambda_struct", "tests/test_parser.py::TestParser::test_missing_by", "tests/test_parser.py::TestParser::test_multi", "tests/test_parser.py::TestParser::test_parameter", "tests/test_parser.py::TestParser::test_parse_concat_ws", "tests/test_parser.py::TestParser::test_parse_create_schema", "tests/test_parser.py::TestParser::test_parse_drop_schema", "tests/test_parser.py::TestParser::test_parse_empty", "tests/test_parser.py::TestParser::test_parse_errors", "tests/test_parser.py::TestParser::test_parse_floats", "tests/test_parser.py::TestParser::test_parse_intervals", "tests/test_parser.py::TestParser::test_parse_into", "tests/test_parser.py::TestParser::test_parse_into_error", "tests/test_parser.py::TestParser::test_parse_into_errors", "tests/test_parser.py::TestParser::test_parse_nested", "tests/test_parser.py::TestParser::test_parse_properties", "tests/test_parser.py::TestParser::test_parse_terse_coalesce", "tests/test_parser.py::TestParser::test_pivot_columns", "tests/test_parser.py::TestParser::test_pretty_config_override", "tests/test_parser.py::TestParser::test_rename_table", "tests/test_parser.py::TestParser::test_select", "tests/test_parser.py::TestParser::test_space", "tests/test_parser.py::TestParser::test_structs", "tests/test_parser.py::TestParser::test_table", "tests/test_parser.py::TestParser::test_transactions", "tests/test_parser.py::TestParser::test_tuple", "tests/test_parser.py::TestParser::test_type_literals", "tests/test_parser.py::TestParser::test_unary_plus", "tests/test_parser.py::TestParser::test_union", "tests/test_parser.py::TestParser::test_unnest_projection", "tests/test_parser.py::TestParser::test_values_as_identifier", "tests/test_parser.py::TestParser::test_var" ]
[]
MIT License
18,361
181
[ "sqlglot/parser.py" ]
pyvista__pyvista-6046
50bceb3e796f4973a31f3cf7f7e039753a2bf016
2024-05-07 12:35:54
b5d7a8114b128b5890c0e116fcf985d800fca950
tkoyama010: @pyvista-bot preview pyvista-bot: <!-- NETLIFY DEPLOY COMMENT GENERATED BY ACTIONS_NETLIFY - APP ID SHA256: a13cb84fb117b1fbb38c5e9d3853a95b804288edd848742e6f4a409c37f2648c --> 🚀 Deployed on https://663a3ffb7b66d20e2a353b9d--meek-duckanoo-d2f5ec.netlify.app
diff --git a/pyvista/core/composite.py b/pyvista/core/composite.py index bb75aeb3..f6018f2e 100644 --- a/pyvista/core/composite.py +++ b/pyvista/core/composite.py @@ -1308,3 +1308,27 @@ class MultiBlock( point_name = point_names.pop() if len(point_names) == 1 else None cell_name = cell_names.pop() if len(cell_names) == 1 else None return point_name, cell_name + + def clear_all_data(self): + """Clear all data from all blocks.""" + for block in self: + if isinstance(block, MultiBlock): + block.clear_all_data() + elif block is not None: + block.clear_data() + + def clear_all_point_data(self): + """Clear all point data from all blocks.""" + for block in self: + if isinstance(block, MultiBlock): + block.clear_all_point_data() + elif block is not None: + block.clear_point_data() + + def clear_all_cell_data(self): + """Clear all cell data from all blocks.""" + for block in self: + if isinstance(block, MultiBlock): + block.clear_all_cell_data() + elif block is not None: + block.clear_cell_data()
Allow clearing cell and point data for all blocks in `MultiBlock` objects ### Describe the feature you would like to be added. PyVista `DataSet` objects have `clear_data`, `clear_point_data`, and `clear_cell_data` [methods](https://docs.pyvista.org/version/stable/api/core/_autosummary/pyvista.dataset#pyvista.DataSet). It would be nice to be able to recursively call these methods on all blocks of a MultiBlock using something like `MultiBlock.clear_all_data()`, `MultiBlock.clear_all_point_data()` and `MultiBlock.clear_all_cell_data()`. ### Links to VTK Documentation, Examples, or Class Definitions. _No response_ ### Pseudocode or Screenshots _No response_
pyvista/pyvista
diff --git a/tests/core/test_composite.py b/tests/core/test_composite.py index 53268f85..99a37bbd 100644 --- a/tests/core/test_composite.py +++ b/tests/core/test_composite.py @@ -785,3 +785,51 @@ def test_activate_scalars(multiblock_poly): for block in multiblock_poly: data = np.array(['a'] * block.n_points) block.point_data.set_array(data, 'data') + + +def test_clear_all_data(multiblock_all): + for block in multiblock_all: + block.point_data['data'] = range(block.n_points) + block.cell_data['data'] = range(block.n_cells) + multiblock_all.append(multiblock_all.copy()) + multiblock_all.clear_all_data() + for block in multiblock_all: + if isinstance(block, MultiBlock): + for subblock in block: + assert subblock.point_data.keys() == [] + assert subblock.cell_data.keys() == [] + else: + assert block.point_data.keys() == [] + assert block.cell_data.keys() == [] + + +def test_clear_all_point_data(multiblock_all): + for block in multiblock_all: + block.point_data['data'] = range(block.n_points) + block.cell_data['data'] = range(block.n_cells) + multiblock_all.append(multiblock_all.copy()) + multiblock_all.clear_all_point_data() + for block in multiblock_all: + if isinstance(block, MultiBlock): + for subblock in block: + assert subblock.point_data.keys() == [] + assert subblock.cell_data.keys() != [] + else: + assert block.point_data.keys() == [] + assert block.cell_data.keys() != [] + + +def test_clear_all_cell_data(multiblock_all): + for block in multiblock_all: + block.point_data['data'] = range(block.n_points) + block.cell_data['data'] = range(block.n_cells) + multiblock_all.append(multiblock_all.copy()) + multiblock_all.clear_all_cell_data() + for block in multiblock_all: + if isinstance(block, MultiBlock): + for subblock in block: + assert subblock.point_data.keys() != [] + assert subblock.cell_data.keys() == [] + else: + assert block.point_data.keys() != [] + assert block.cell_data.keys() == []
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
0.43
{ "env_vars": null, "env_yml_path": [ "environment.yml" ], "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "environment.yml", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y libgl1-mesa-glx xvfb" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiohappyeyeballs @ file:///home/conda/feedstock_root/build_artifacts/aiohappyeyeballs_1741775197943/work aiohttp @ file:///home/conda/feedstock_root/build_artifacts/aiohttp_1742268596946/work aiosignal @ file:///home/conda/feedstock_root/build_artifacts/aiosignal_1734342155601/work anyio @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_anyio_1742243108/work argon2-cffi @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi_1733311059102/work argon2-cffi-bindings @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi-bindings_1725356560642/work arrow @ file:///home/conda/feedstock_root/build_artifacts/arrow_1733584251875/work asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1733250440834/work async-lru @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_async-lru_1742153708/work async-timeout @ file:///home/conda/feedstock_root/build_artifacts/async-timeout_1733235340728/work attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1741918516150/work babel @ file:///home/conda/feedstock_root/build_artifacts/babel_1738490167835/work beautifulsoup4 @ file:///home/conda/feedstock_root/build_artifacts/beautifulsoup4_1738740337718/work bleach @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_bleach_1737382993/work Brotli @ file:///home/conda/feedstock_root/build_artifacts/brotli-split_1725267488082/work cached-property @ file:///home/conda/feedstock_root/build_artifacts/cached_property_1615209429212/work certifi @ file:///home/conda/feedstock_root/build_artifacts/certifi_1739515848642/work/certifi cffi @ file:///home/conda/feedstock_root/build_artifacts/cffi_1725571112467/work cftime @ file:///home/conda/feedstock_root/build_artifacts/cftime_1725400455427/work charset-normalizer @ file:///home/conda/feedstock_root/build_artifacts/charset-normalizer_1735929714516/work click @ file:///home/conda/feedstock_root/build_artifacts/click_1734858813237/work cmocean @ file:///home/conda/feedstock_root/build_artifacts/cmocean_1734343940570/work codecov @ file:///home/conda/feedstock_root/build_artifacts/codecov_1734975286850/work colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1733218098505/work colorcet @ file:///home/conda/feedstock_root/build_artifacts/colorcet_1734007314889/work colorspacious @ file:///home/conda/feedstock_root/build_artifacts/colorspacious_1734341944815/work comm @ file:///home/conda/feedstock_root/build_artifacts/comm_1733502965406/work contourpy @ file:///home/conda/feedstock_root/build_artifacts/contourpy_1727293517607/work coverage @ file:///home/conda/feedstock_root/build_artifacts/coverage_1743381224823/work cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1733332471406/work debugpy @ file:///home/conda/feedstock_root/build_artifacts/debugpy_1741148409996/work decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1740384970518/work defusedxml @ file:///home/conda/feedstock_root/build_artifacts/defusedxml_1615232257335/work exceptiongroup @ file:///home/conda/feedstock_root/build_artifacts/exceptiongroup_1733208806608/work execnet @ file:///home/conda/feedstock_root/build_artifacts/execnet_1733230988954/work executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1733569351617/work fastjsonschema @ file:///home/conda/feedstock_root/build_artifacts/python-fastjsonschema_1733235979760/work/dist fonttools @ file:///home/conda/feedstock_root/build_artifacts/fonttools_1738940303262/work fqdn @ file:///home/conda/feedstock_root/build_artifacts/fqdn_1733327382592/work/dist frozenlist @ file:///home/conda/feedstock_root/build_artifacts/frozenlist_1737645236190/work h11 @ file:///home/conda/feedstock_root/build_artifacts/h11_1733327467879/work h2 @ file:///home/conda/feedstock_root/build_artifacts/h2_1738578511449/work h5py @ file:///home/conda/feedstock_root/build_artifacts/h5py_1739952287730/work hpack @ file:///home/conda/feedstock_root/build_artifacts/hpack_1737618293087/work httpcore @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_httpcore_1731707562/work httpx @ file:///home/conda/feedstock_root/build_artifacts/httpx_1733663348460/work hyperframe @ file:///home/conda/feedstock_root/build_artifacts/hyperframe_1737618333194/work hypothesis @ file:///home/conda/feedstock_root/build_artifacts/hypothesis_1742900877539/work idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1733211830134/work imageio @ file:///home/conda/feedstock_root/build_artifacts/imageio_1738273805233/work imageio-ffmpeg @ file:///home/conda/feedstock_root/build_artifacts/imageio-ffmpeg_1737102630951/work importlib_metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1737420181517/work importlib_resources @ file:///home/conda/feedstock_root/build_artifacts/importlib_resources_1736252299705/work iniconfig @ file:///home/conda/feedstock_root/build_artifacts/iniconfig_1733223141826/work ipykernel @ file:///home/conda/feedstock_root/build_artifacts/ipykernel_1719845459717/work ipython @ file:///home/conda/feedstock_root/build_artifacts/ipython_1701831663892/work ipywidgets==8.1.5 isoduration @ file:///home/conda/feedstock_root/build_artifacts/isoduration_1733493628631/work/dist jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1733300866624/work Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1741263328855/work json5 @ file:///home/conda/feedstock_root/build_artifacts/json5_1733272076743/work jsonpointer @ file:///home/conda/feedstock_root/build_artifacts/jsonpointer_1725302957584/work jsonschema @ file:///home/conda/feedstock_root/build_artifacts/jsonschema_1733472696581/work jsonschema-specifications @ file:///tmp/tmpk0f344m9/src jupyter-events @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_jupyter_events_1738765986/work jupyter-lsp @ file:///home/conda/feedstock_root/build_artifacts/jupyter-lsp-meta_1733492907176/work/jupyter-lsp jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1733440914442/work jupyter_core @ file:///home/conda/feedstock_root/build_artifacts/jupyter_core_1727163409502/work jupyter_server @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_1734702637701/work jupyter_server_proxy==4.4.0 jupyter_server_terminals @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_terminals_1733427956852/work jupyterlab @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_1741964057182/work jupyterlab_pygments @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_pygments_1733328101776/work jupyterlab_server @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_server_1733599573484/work jupyterlab_widgets==3.0.13 kiwisolver @ file:///home/conda/feedstock_root/build_artifacts/kiwisolver_1725459266648/work loguru @ file:///home/conda/feedstock_root/build_artifacts/loguru_1725349754278/work markdown-it-py @ file:///home/conda/feedstock_root/build_artifacts/markdown-it-py_1733250460757/work MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1733219680183/work matplotlib==3.9.4 matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1733416936468/work mdurl @ file:///home/conda/feedstock_root/build_artifacts/mdurl_1733255585584/work meshio @ file:///home/conda/feedstock_root/build_artifacts/meshio_1706720595231/work mistune @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_mistune_1742402716/work more-itertools @ file:///home/conda/feedstock_root/build_artifacts/more-itertools_1736883817510/work msgpack @ file:///home/conda/feedstock_root/build_artifacts/msgpack-python_1725975012026/work multidict @ file:///home/conda/feedstock_root/build_artifacts/multidict_1742308123521/work munkres==1.1.4 nbclient @ file:///home/conda/feedstock_root/build_artifacts/nbclient_1734628800805/work nbconvert @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_nbconvert-core_1738067871/work nbformat @ file:///home/conda/feedstock_root/build_artifacts/nbformat_1733402752141/work nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1733325553580/work netCDF4 @ file:///home/conda/feedstock_root/build_artifacts/netcdf4_1733253338730/work notebook_shim @ file:///home/conda/feedstock_root/build_artifacts/notebook-shim_1733408315203/work numpy @ file:///home/conda/feedstock_root/build_artifacts/numpy_1707225342954/work/dist/numpy-1.26.4-cp39-cp39-linux_x86_64.whl#sha256=c799942b5898f6e6c60264d1663a6469a475290e758c654aeeb78e2596463abd overrides @ file:///home/conda/feedstock_root/build_artifacts/overrides_1734587627321/work packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1733203243479/work pandocfilters @ file:///home/conda/feedstock_root/build_artifacts/pandocfilters_1631603243851/work parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1733271261340/work pexpect @ file:///home/conda/feedstock_root/build_artifacts/pexpect_1733301927746/work pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1733327343728/work pillow @ file:///home/conda/feedstock_root/build_artifacts/pillow_1735929703139/work pkgutil_resolve_name @ file:///home/conda/feedstock_root/build_artifacts/pkgutil-resolve-name_1733344503739/work platformdirs @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_platformdirs_1742485085/work pluggy @ file:///home/conda/feedstock_root/build_artifacts/pluggy_1733222765875/work pooch @ file:///home/conda/feedstock_root/build_artifacts/pooch_1733421311631/work prometheus_client @ file:///home/conda/feedstock_root/build_artifacts/prometheus_client_1733327310477/work prompt_toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1737453357274/work propcache @ file:///home/conda/feedstock_root/build_artifacts/propcache_1737635528546/work psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1740663125313/work ptyprocess @ file:///home/conda/feedstock_root/build_artifacts/ptyprocess_1733302279685/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl#sha256=92c32ff62b5fd8cf325bec5ab90d7be3d2a8ca8c8a3813ff487a8d2002630d1f pure_eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1733569405015/work pycparser @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_pycparser_1733195786/work pyembree @ file:///home/conda/feedstock_root/build_artifacts/pyembree_1718702851992/work Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1736243443484/work pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1743089729650/work PySide6==6.8.3 PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1733217236728/work pytest @ file:///home/conda/feedstock_root/build_artifacts/pytest_1740946542080/work pytest-cov @ file:///home/conda/feedstock_root/build_artifacts/pytest-cov_1733223023082/work pytest-memprof==0.2.0 pytest-xdist @ file:///home/conda/feedstock_root/build_artifacts/pytest-xdist_1733240780199/work python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1733215673016/work python-json-logger @ file:///home/conda/feedstock_root/build_artifacts/python-json-logger_1677079630776/work pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1742920838005/work -e git+https://github.com/pyvista/pyvista.git@50bceb3e796f4973a31f3cf7f7e039753a2bf016#egg=pyvista PyYAML @ file:///home/conda/feedstock_root/build_artifacts/pyyaml_1737454647378/work pyzmq @ file:///home/conda/feedstock_root/build_artifacts/pyzmq_1741805177758/work referencing @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_referencing_1737836872/work requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1733217035951/work rfc3339_validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3339-validator_1733599910982/work rfc3986-validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3986-validator_1598024191506/work rich @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rich_1743371105/work/dist rpds-py @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rpds-py_1743037693/work rtree @ file:///home/conda/feedstock_root/build_artifacts/rtree_1741378561624/work scooby @ file:///home/conda/feedstock_root/build_artifacts/scooby_1734299019922/work Send2Trash @ file:///home/conda/feedstock_root/build_artifacts/send2trash_1733322040660/work shiboken6==6.8.3 simpervisor==1.0.0 six @ file:///home/conda/feedstock_root/build_artifacts/six_1733380938961/work sniffio @ file:///home/conda/feedstock_root/build_artifacts/sniffio_1733244044561/work sortedcontainers @ file:///home/conda/feedstock_root/build_artifacts/sortedcontainers_1738440353519/work soupsieve @ file:///home/conda/feedstock_root/build_artifacts/soupsieve_1693929250441/work stack_data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1733569443808/work terminado @ file:///home/conda/feedstock_root/build_artifacts/terminado_1710262609923/work tinycss2 @ file:///home/conda/feedstock_root/build_artifacts/tinycss2_1729802851396/work toml @ file:///home/conda/feedstock_root/build_artifacts/toml_1734091811753/work tomli @ file:///home/conda/feedstock_root/build_artifacts/tomli_1733256695513/work tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1732615921868/work tqdm @ file:///home/conda/feedstock_root/build_artifacts/tqdm_1735661334605/work traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1733367359838/work trame @ file:///home/conda/feedstock_root/build_artifacts/trame_1741413642518/work trame-client @ file:///home/conda/feedstock_root/build_artifacts/trame-client_1742874331306/work trame-server @ file:///home/conda/feedstock_root/build_artifacts/trame-server_1741638011360/work trame-vtk @ file:///home/conda/feedstock_root/build_artifacts/trame-vtk_1739145199105/work trame-vuetify @ file:///home/conda/feedstock_root/build_artifacts/trame-vuetify_1743263303319/work trimesh @ file:///home/conda/feedstock_root/build_artifacts/trimesh_1743289679380/work types-python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/types-python-dateutil_1733612335562/work typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_typing_extensions_1743201626/work typing_utils @ file:///home/conda/feedstock_root/build_artifacts/typing_utils_1733331286120/work unicodedata2 @ file:///home/conda/feedstock_root/build_artifacts/unicodedata2_1736692503055/work uri-template @ file:///home/conda/feedstock_root/build_artifacts/uri-template_1733323593477/work/dist urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1734859416348/work vtk==9.3.1 wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1733231326287/work webcolors @ file:///home/conda/feedstock_root/build_artifacts/webcolors_1733359735138/work webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1733236011802/work websocket-client @ file:///home/conda/feedstock_root/build_artifacts/websocket-client_1733157342724/work widgetsnbextension==4.0.13 wslink @ file:///home/conda/feedstock_root/build_artifacts/wslink_1742768409749/work yarl @ file:///home/conda/feedstock_root/build_artifacts/yarl_1737575777699/work zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1732827521216/work zstandard==0.23.0
name: pyvista channels: - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=conda_forge - _openmp_mutex=4.5=2_gnu - aiohappyeyeballs=2.6.1=pyhd8ed1ab_0 - aiohttp=3.11.14=py39h9399b63_0 - aiosignal=1.3.2=pyhd8ed1ab_0 - alsa-lib=1.2.13=hb9d3cd8_0 - anyio=4.9.0=pyh29332c3_0 - aom=3.9.1=hac33072_0 - argon2-cffi=23.1.0=pyhd8ed1ab_1 - argon2-cffi-bindings=21.2.0=py39h8cd3c5a_5 - arrow=1.3.0=pyhd8ed1ab_1 - asttokens=3.0.0=pyhd8ed1ab_1 - async-lru=2.0.5=pyh29332c3_0 - async-timeout=5.0.1=pyhd8ed1ab_1 - attr=2.5.1=h166bdaf_1 - attrs=25.3.0=pyh71513ae_0 - babel=2.17.0=pyhd8ed1ab_0 - beautifulsoup4=4.13.3=pyha770c72_0 - bleach=6.2.0=pyh29332c3_4 - bleach-with-css=6.2.0=h82add2a_4 - blosc=1.21.6=he440d0b_1 - brotli=1.1.0=hb9d3cd8_2 - brotli-bin=1.1.0=hb9d3cd8_2 - brotli-python=1.1.0=py39hf88036b_2 - bzip2=1.0.8=h4bc722e_7 - c-ares=1.34.4=hb9d3cd8_0 - ca-certificates=2025.1.31=hbcca054_0 - cached-property=1.5.2=hd8ed1ab_1 - cached_property=1.5.2=pyha770c72_1 - cairo=1.18.4=h3394656_0 - certifi=2025.1.31=pyhd8ed1ab_0 - cffi=1.17.1=py39h15c3d72_0 - cftime=1.6.4=py39hf3d9206_1 - charset-normalizer=3.4.1=pyhd8ed1ab_0 - click=8.1.8=pyh707e725_0 - cmocean=4.0.3=pyhd8ed1ab_1 - codecov=2.1.13=pyhd8ed1ab_1 - colorama=0.4.6=pyhd8ed1ab_1 - colorcet=3.1.0=pyhd8ed1ab_1 - colorspacious=1.1.2=pyhecae5ae_1 - comm=0.2.2=pyhd8ed1ab_1 - contourpy=1.3.0=py39h74842e3_2 - coverage=7.8.0=py39h9399b63_0 - cycler=0.12.1=pyhd8ed1ab_1 - cyrus-sasl=2.1.27=h54b06d7_7 - dav1d=1.2.1=hd590300_0 - dbus=1.13.6=h5008d03_3 - debugpy=1.8.13=py39hf88036b_0 - decorator=5.2.1=pyhd8ed1ab_0 - defusedxml=0.7.1=pyhd8ed1ab_0 - double-conversion=3.3.1=h5888daf_0 - embree=2.17.7=ha770c72_3 - exceptiongroup=1.2.2=pyhd8ed1ab_1 - execnet=2.1.1=pyhd8ed1ab_1 - executing=2.1.0=pyhd8ed1ab_1 - expat=2.6.4=h5888daf_0 - ffmpeg=7.1.1=gpl_h0b79d52_704 - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 - font-ttf-inconsolata=3.000=h77eed37_0 - font-ttf-source-code-pro=2.038=h77eed37_0 - font-ttf-ubuntu=0.83=h77eed37_3 - fontconfig=2.15.0=h7e30c49_1 - fonts-conda-ecosystem=1=0 - fonts-conda-forge=1=0 - fonttools=4.56.0=py39h9399b63_0 - fqdn=1.5.1=pyhd8ed1ab_1 - freetype=2.13.3=h48d6fc4_0 - fribidi=1.0.10=h36c2ea0_0 - frozenlist=1.5.0=py39h9399b63_1 - gdk-pixbuf=2.42.12=hb9ae30d_0 - gettext=0.23.1=h5888daf_0 - gettext-tools=0.23.1=h5888daf_0 - gl2ps=1.4.2=hae5d5c5_1 - glew=2.1.0=h9c3ff4c_2 - gmp=6.3.0=hac33072_2 - graphite2=1.3.13=h59595ed_1003 - h11=0.14.0=pyhd8ed1ab_1 - h2=4.2.0=pyhd8ed1ab_0 - h5py=3.13.0=nompi_py39h30a5a8d_100 - harfbuzz=11.0.0=h76408a6_0 - hdf4=4.2.15=h2a13503_7 - hdf5=1.14.3=nompi_h2d575fe_109 - hpack=4.1.0=pyhd8ed1ab_0 - httpcore=1.0.7=pyh29332c3_1 - httpx=0.28.1=pyhd8ed1ab_0 - hyperframe=6.1.0=pyhd8ed1ab_0 - hypothesis=6.130.4=pyha770c72_0 - icu=75.1=he02047a_0 - idna=3.10=pyhd8ed1ab_1 - imageio=2.37.0=pyhfb79c49_0 - imageio-ffmpeg=0.6.0=pyhd8ed1ab_0 - importlib-metadata=8.6.1=pyha770c72_0 - importlib-resources=6.5.2=pyhd8ed1ab_0 - importlib_metadata=8.6.1=hd8ed1ab_0 - importlib_resources=6.5.2=pyhd8ed1ab_0 - iniconfig=2.0.0=pyhd8ed1ab_1 - ipykernel=6.29.5=pyh3099207_0 - ipython=8.18.1=pyh707e725_3 - isoduration=20.11.0=pyhd8ed1ab_1 - jack=1.9.22=h7c63dc7_2 - jedi=0.19.2=pyhd8ed1ab_1 - jinja2=3.1.6=pyhd8ed1ab_0 - json5=0.10.0=pyhd8ed1ab_1 - jsoncpp=1.9.6=hf42df4d_1 - jsonpointer=3.0.0=py39hf3d152e_1 - jsonschema=4.23.0=pyhd8ed1ab_1 - jsonschema-specifications=2024.10.1=pyhd8ed1ab_1 - jsonschema-with-format-nongpl=4.23.0=hd8ed1ab_1 - jupyter-lsp=2.2.5=pyhd8ed1ab_1 - jupyter_client=8.6.3=pyhd8ed1ab_1 - jupyter_core=5.7.2=pyh31011fe_1 - jupyter_events=0.12.0=pyh29332c3_0 - jupyter_server=2.15.0=pyhd8ed1ab_0 - jupyter_server_terminals=0.5.3=pyhd8ed1ab_1 - jupyterlab=4.3.6=pyhd8ed1ab_0 - jupyterlab_pygments=0.3.0=pyhd8ed1ab_2 - jupyterlab_server=2.27.3=pyhd8ed1ab_1 - keyutils=1.6.1=h166bdaf_0 - kiwisolver=1.4.7=py39h74842e3_0 - krb5=1.21.3=h659f571_0 - lame=3.100=h166bdaf_1003 - lcms2=2.17=h717163a_0 - ld_impl_linux-64=2.43=h712a8e2_4 - lerc=4.0.0=h27087fc_0 - level-zero=1.21.6=h84d6215_0 - libabseil=20250127.1=cxx17_hbbce691_0 - libaec=1.1.3=h59595ed_0 - libasprintf=0.23.1=h8e693c7_0 - libasprintf-devel=0.23.1=h8e693c7_0 - libass=0.17.3=h52826cd_2 - libblas=3.9.0=31_h59b9bed_openblas - libbrotlicommon=1.1.0=hb9d3cd8_2 - libbrotlidec=1.1.0=hb9d3cd8_2 - libbrotlienc=1.1.0=hb9d3cd8_2 - libcap=2.75=h39aace5_0 - libcblas=3.9.0=31_he106b2a_openblas - libclang-cpp20.1=20.1.1=default_hb5137d0_0 - libclang13=20.1.1=default_h9c6a7e4_0 - libcups=2.3.3=h4637d8d_4 - libcurl=8.12.1=h332b0f4_0 - libdb=6.2.32=h9c3ff4c_0 - libdeflate=1.23=h4ddbbb0_0 - libdrm=2.4.124=hb9d3cd8_0 - libedit=3.1.20250104=pl5321h7949ede_0 - libegl=1.7.0=ha4b6fd6_2 - libev=4.33=hd590300_2 - libexpat=2.6.4=h5888daf_0 - libffi=3.4.6=h2dba641_0 - libflac=1.4.3=h59595ed_0 - libgcc=14.2.0=h767d61c_2 - libgcc-ng=14.2.0=h69a702a_2 - libgcrypt-lib=1.11.0=hb9d3cd8_2 - libgettextpo=0.23.1=h5888daf_0 - libgettextpo-devel=0.23.1=h5888daf_0 - libgfortran=14.2.0=h69a702a_2 - libgfortran5=14.2.0=hf1ad2bd_2 - libgl=1.7.0=ha4b6fd6_2 - libglib=2.84.0=h2ff4ddf_0 - libglu=9.0.3=h03adeef_0 - libglvnd=1.7.0=ha4b6fd6_2 - libglx=1.7.0=ha4b6fd6_2 - libgomp=14.2.0=h767d61c_2 - libgpg-error=1.51=hbd13f7d_1 - libhwloc=2.11.2=default_h0d58e46_1001 - libiconv=1.18=h4ce23a2_1 - libjpeg-turbo=3.0.0=hd590300_1 - liblapack=3.9.0=31_h7ac8fdf_openblas - libllvm20=20.1.1=ha7bfdaf_0 - liblzma=5.6.4=hb9d3cd8_0 - libnetcdf=4.9.2=nompi_h00e09a9_116 - libnghttp2=1.64.0=h161d5f1_0 - libnsl=2.0.1=hd590300_0 - libntlm=1.8=hb9d3cd8_0 - libogg=1.3.5=h4ab18f5_0 - libopenblas=0.3.29=pthreads_h94d23a6_0 - libopengl=1.7.0=ha4b6fd6_2 - libopenvino=2025.0.0=hdc3f47d_3 - libopenvino-auto-batch-plugin=2025.0.0=h4d9b6c2_3 - libopenvino-auto-plugin=2025.0.0=h4d9b6c2_3 - libopenvino-hetero-plugin=2025.0.0=h981d57b_3 - libopenvino-intel-cpu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-intel-gpu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-intel-npu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-ir-frontend=2025.0.0=h981d57b_3 - libopenvino-onnx-frontend=2025.0.0=h0e684df_3 - libopenvino-paddle-frontend=2025.0.0=h0e684df_3 - libopenvino-pytorch-frontend=2025.0.0=h5888daf_3 - libopenvino-tensorflow-frontend=2025.0.0=h684f15b_3 - libopenvino-tensorflow-lite-frontend=2025.0.0=h5888daf_3 - libopus=1.3.1=h7f98852_1 - libpciaccess=0.18=hd590300_0 - libpng=1.6.47=h943b412_0 - libpq=17.4=h27ae623_0 - libprotobuf=5.29.3=h501fc15_0 - librsvg=2.58.4=he92a37e_3 - libsndfile=1.2.2=hc60ed4a_1 - libsodium=1.0.20=h4ab18f5_0 - libspatialindex=2.1.0=he57a185_0 - libsqlite=3.49.1=hee588c1_2 - libssh2=1.11.1=hf672d98_0 - libstdcxx=14.2.0=h8f9b012_2 - libstdcxx-ng=14.2.0=h4852527_2 - libsystemd0=257.4=h4e0b6ca_1 - libtheora=1.1.1=h4ab18f5_1006 - libtiff=4.7.0=hd9ff511_3 - libudev1=257.4=hbe16f8c_1 - libunwind=1.6.2=h9c3ff4c_0 - liburing=2.9=h84d6215_0 - libusb=1.0.28=hb9d3cd8_0 - libuuid=2.38.1=h0b41bf4_0 - libva=2.22.0=h4f16b4b_2 - libvorbis=1.3.7=h9c3ff4c_0 - libvpx=1.14.1=hac33072_0 - libwebp-base=1.5.0=h851e524_0 - libxcb=1.17.0=h8a09558_0 - libxcrypt=4.4.36=hd590300_1 - libxkbcommon=1.8.1=hc4a0caf_0 - libxml2=2.13.7=h8d12d68_0 - libxslt=1.1.39=h76b75d6_0 - libzip=1.11.2=h6991a6a_0 - libzlib=1.3.1=hb9d3cd8_2 - loguru=0.7.2=py39hf3d152e_2 - lz4-c=1.10.0=h5888daf_1 - markdown-it-py=3.0.0=pyhd8ed1ab_1 - markupsafe=3.0.2=py39h9399b63_1 - matplotlib=3.9.4=py39hf3d152e_0 - matplotlib-base=3.9.4=py39h16632d1_0 - matplotlib-inline=0.1.7=pyhd8ed1ab_1 - mdurl=0.1.2=pyhd8ed1ab_1 - meshio=5.3.5=pyhd8ed1ab_0 - mistune=3.1.3=pyh29332c3_0 - more-itertools=10.6.0=pyhd8ed1ab_0 - mpg123=1.32.9=hc50e24c_0 - msgpack-python=1.1.0=py39h74842e3_0 - multidict=6.2.0=py39h9399b63_0 - munkres=1.1.4=pyh9f0ad1d_0 - mysql-common=9.0.1=h266115a_5 - mysql-libs=9.0.1=he0572af_5 - nbclient=0.10.2=pyhd8ed1ab_0 - nbconvert-core=7.16.6=pyh29332c3_0 - nbformat=5.10.4=pyhd8ed1ab_1 - ncurses=6.5=h2d0b736_3 - nest-asyncio=1.6.0=pyhd8ed1ab_1 - netcdf4=1.7.2=nompi_py39h9d02bfe_101 - nlohmann_json=3.11.3=he02047a_1 - notebook-shim=0.2.4=pyhd8ed1ab_1 - numpy=1.26.4=py39h474f0d3_0 - ocl-icd=2.3.2=hb9d3cd8_2 - opencl-headers=2024.10.24=h5888daf_0 - openh264=2.6.0=hc22cd8d_0 - openjpeg=2.5.3=h5fbd93e_0 - openldap=2.6.9=he970967_0 - openssl=3.4.1=h7b32b05_0 - overrides=7.7.0=pyhd8ed1ab_1 - packaging=24.2=pyhd8ed1ab_2 - pandocfilters=1.5.0=pyhd8ed1ab_0 - pango=1.56.3=h9ac818e_1 - parso=0.8.4=pyhd8ed1ab_1 - pcre2=10.44=hba22ea6_2 - pexpect=4.9.0=pyhd8ed1ab_1 - pickleshare=0.7.5=pyhd8ed1ab_1004 - pillow=11.1.0=py39h15c0740_0 - pip=25.0.1=pyh8b19718_0 - pixman=0.44.2=h29eaf8c_0 - pkgutil-resolve-name=1.3.10=pyhd8ed1ab_2 - platformdirs=4.3.7=pyh29332c3_0 - pluggy=1.5.0=pyhd8ed1ab_1 - pooch=1.8.2=pyhd8ed1ab_1 - proj=9.5.1=h0054346_0 - prometheus_client=0.21.1=pyhd8ed1ab_0 - prompt-toolkit=3.0.50=pyha770c72_0 - propcache=0.2.1=py39h9399b63_1 - psutil=7.0.0=py39h8cd3c5a_0 - pthread-stubs=0.4=hb9d3cd8_1002 - ptyprocess=0.7.0=pyhd8ed1ab_1 - pugixml=1.15=h3f63f65_0 - pulseaudio-client=17.0=hac146a9_1 - pure_eval=0.2.3=pyhd8ed1ab_1 - pycparser=2.22=pyh29332c3_1 - pyembree=0.1.6=py39hddac248_4 - pygments=2.19.1=pyhd8ed1ab_0 - pyparsing=3.2.3=pyhd8ed1ab_1 - pyside6=6.8.3=py39h0383914_0 - pysocks=1.7.1=pyha55dd90_7 - pytest=8.3.5=pyhd8ed1ab_0 - pytest-cov=6.0.0=pyhd8ed1ab_1 - pytest-xdist=3.6.1=pyhd8ed1ab_1 - python=3.9.21=h9c0c6dc_1_cpython - python-dateutil=2.9.0.post0=pyhff2d567_1 - python-fastjsonschema=2.21.1=pyhd8ed1ab_0 - python-json-logger=2.0.7=pyhd8ed1ab_0 - python_abi=3.9=5_cp39 - pytz=2025.2=pyhd8ed1ab_0 - pyyaml=6.0.2=py39h9399b63_2 - pyzmq=26.3.0=py39h4e4fb57_0 - qhull=2020.2=h434a139_5 - qt6-main=6.8.3=h6441bc3_1 - readline=8.2=h8c095d6_2 - referencing=0.36.2=pyh29332c3_0 - requests=2.32.3=pyhd8ed1ab_1 - rfc3339-validator=0.1.4=pyhd8ed1ab_1 - rfc3986-validator=0.1.1=pyh9f0ad1d_0 - rich=14.0.0=pyh29332c3_0 - rpds-py=0.24.0=py39h3506688_0 - rtree=1.4.0=pyh11ca60a_1 - scooby=0.10.0=pyhd8ed1ab_1 - sdl2=2.32.50=h9b8e6db_1 - sdl3=3.2.8=h3083f51_0 - send2trash=1.8.3=pyh0d859eb_1 - setuptools=75.8.2=pyhff2d567_0 - six=1.17.0=pyhd8ed1ab_0 - snappy=1.2.1=h8bd8927_1 - sniffio=1.3.1=pyhd8ed1ab_1 - sortedcontainers=2.4.0=pyhd8ed1ab_1 - soupsieve=2.5=pyhd8ed1ab_1 - sqlite=3.49.1=h9eae976_2 - stack_data=0.6.3=pyhd8ed1ab_1 - svt-av1=3.0.2=h5888daf_0 - tbb=2022.0.0=hceb3a55_0 - terminado=0.18.1=pyh0d859eb_0 - tinycss2=1.4.0=pyhd8ed1ab_0 - tk=8.6.13=noxft_h4845f30_101 - toml=0.10.2=pyhd8ed1ab_1 - tomli=2.2.1=pyhd8ed1ab_1 - tornado=6.4.2=py39h8cd3c5a_0 - tqdm=4.67.1=pyhd8ed1ab_1 - traitlets=5.14.3=pyhd8ed1ab_1 - trame=3.8.1=pyhd8ed1ab_0 - trame-client=3.6.1=pyhd8ed1ab_0 - trame-server=3.4.0=pyhd8ed1ab_0 - trame-vtk=2.8.15=pyhb419c8b_0 - trame-vuetify=2.9.0=pyhd8ed1ab_0 - trimesh=4.6.6=pyh7b2049a_0 - types-python-dateutil=2.9.0.20241206=pyhd8ed1ab_0 - typing-extensions=4.13.0=h9fa5a19_1 - typing_extensions=4.13.0=pyh29332c3_1 - typing_utils=0.1.0=pyhd8ed1ab_1 - tzdata=2025b=h78e105d_0 - unicodedata2=16.0.0=py39h8cd3c5a_0 - uri-template=1.3.0=pyhd8ed1ab_1 - urllib3=2.3.0=pyhd8ed1ab_0 - utfcpp=4.0.6=h005c6e1_0 - vtk=9.3.1=qt_py39h71fb23e_216 - vtk-base=9.3.1=qt_py39habd23de_216 - vtk-io-ffmpeg=9.3.1=qt_py39h71fb23e_216 - wayland=1.23.1=h3e06ad9_0 - wayland-protocols=1.42=hd8ed1ab_0 - wcwidth=0.2.13=pyhd8ed1ab_1 - webcolors=24.11.1=pyhd8ed1ab_0 - webencodings=0.5.1=pyhd8ed1ab_3 - websocket-client=1.8.0=pyhd8ed1ab_1 - wheel=0.45.1=pyhd8ed1ab_1 - wslink=2.3.3=pyhd8ed1ab_0 - x264=1!164.3095=h166bdaf_2 - x265=3.5=h924138e_3 - xcb-util=0.4.1=hb711507_2 - xcb-util-cursor=0.1.5=hb9d3cd8_0 - xcb-util-image=0.4.0=hb711507_2 - xcb-util-keysyms=0.4.1=hb711507_0 - xcb-util-renderutil=0.3.10=hb711507_0 - xcb-util-wm=0.4.2=hb711507_0 - xkeyboard-config=2.43=hb9d3cd8_0 - xorg-libice=1.1.2=hb9d3cd8_0 - xorg-libsm=1.2.6=he73a12e_0 - xorg-libx11=1.8.12=h4f16b4b_0 - xorg-libxau=1.0.12=hb9d3cd8_0 - xorg-libxcomposite=0.4.6=hb9d3cd8_2 - xorg-libxcursor=1.2.3=hb9d3cd8_0 - xorg-libxdamage=1.1.6=hb9d3cd8_0 - xorg-libxdmcp=1.1.5=hb9d3cd8_0 - xorg-libxext=1.3.6=hb9d3cd8_0 - xorg-libxfixes=6.0.1=hb9d3cd8_0 - xorg-libxi=1.8.2=hb9d3cd8_0 - xorg-libxrandr=1.5.4=hb9d3cd8_0 - xorg-libxrender=0.9.12=hb9d3cd8_0 - xorg-libxscrnsaver=1.2.4=hb9d3cd8_0 - xorg-libxt=1.3.1=hb9d3cd8_0 - xorg-libxtst=1.2.5=hb9d3cd8_3 - xorg-libxxf86vm=1.1.6=hb9d3cd8_0 - yaml=0.2.5=h7f98852_2 - yarl=1.18.3=py39h9399b63_1 - zeromq=4.3.5=h3b0a872_7 - zipp=3.21.0=pyhd8ed1ab_1 - zlib=1.3.1=hb9d3cd8_2 - zstandard=0.23.0=py39h8cd3c5a_1 - zstd=1.5.7=hb8e6e7a_2 - pip: - ipywidgets==8.1.5 - jupyter-server-proxy==4.4.0 - jupyterlab-widgets==3.0.13 - pytest-memprof==0.2.0 - pyvista==0.44.dev0 - simpervisor==1.0.0 - widgetsnbextension==4.0.13 prefix: /opt/conda/envs/pyvista
[ "tests/core/test_composite.py::test_clear_all_data", "tests/core/test_composite.py::test_clear_all_point_data", "tests/core/test_composite.py::test_clear_all_cell_data" ]
[]
[ "tests/core/test_composite.py::test_multi_block_init_vtk", "tests/core/test_composite.py::test_multi_block_init_dict", "tests/core/test_composite.py::test_multi_block_keys", "tests/core/test_composite.py::test_multi_block_init_list", "tests/core/test_composite.py::test_multi_block_append", "tests/core/test_composite.py::test_multi_block_set_get_ers", "tests/core/test_composite.py::test_replace", "tests/core/test_composite.py::test_pop", "tests/core/test_composite.py::test_del_slice", "tests/core/test_composite.py::test_slicing_multiple_in_setitem", "tests/core/test_composite.py::test_reverse", "tests/core/test_composite.py::test_insert", "tests/core/test_composite.py::test_extend", "tests/core/test_composite.py::test_multi_block_clean", "tests/core/test_composite.py::test_multi_block_repr", "tests/core/test_composite.py::test_multi_block_eq", "tests/core/test_composite.py::test_multi_block_io[True-.vtm-True]", "tests/core/test_composite.py::test_multi_block_io[True-.vtm-False]", "tests/core/test_composite.py::test_multi_block_io[True-.vtmb-True]", "tests/core/test_composite.py::test_multi_block_io[True-.vtmb-False]", "tests/core/test_composite.py::test_multi_block_io[False-.vtm-True]", "tests/core/test_composite.py::test_multi_block_io[False-.vtm-False]", "tests/core/test_composite.py::test_multi_block_io[False-.vtmb-True]", "tests/core/test_composite.py::test_multi_block_io[False-.vtmb-False]", "tests/core/test_composite.py::test_ensight_multi_block_io[vtm-True]", "tests/core/test_composite.py::test_ensight_multi_block_io[vtm-False]", "tests/core/test_composite.py::test_ensight_multi_block_io[vtmb-True]", "tests/core/test_composite.py::test_ensight_multi_block_io[vtmb-False]", "tests/core/test_composite.py::test_invalid_arg", "tests/core/test_composite.py::test_multi_io_erros", "tests/core/test_composite.py::test_extract_geometry", "tests/core/test_composite.py::test_combine_filter", "tests/core/test_composite.py::test_multi_block_copy", "tests/core/test_composite.py::test_multi_block_negative_index", "tests/core/test_composite.py::test_multi_slice_index", "tests/core/test_composite.py::test_slice_defaults", "tests/core/test_composite.py::test_slice_negatives", "tests/core/test_composite.py::test_multi_block_volume", "tests/core/test_composite.py::test_multi_block_length", "tests/core/test_composite.py::test_multi_block_save_lines", "tests/core/test_composite.py::test_multi_block_data_range", "tests/core/test_composite.py::test_multiblock_ref", "tests/core/test_composite.py::test_set_active_scalars", "tests/core/test_composite.py::test_set_active_scalars_multi", "tests/core/test_composite.py::test_set_active_scalars_components", "tests/core/test_composite.py::test_set_active_multi_multi", "tests/core/test_composite.py::test_set_active_scalars_mixed", "tests/core/test_composite.py::test_to_polydata", "tests/core/test_composite.py::test_compute_normals", "tests/core/test_composite.py::test_activate_scalars" ]
[]
MIT License
18,362
307
[ "pyvista/core/composite.py" ]
Informasjonsforvaltning__fdk-rdf-parser-297
969a0bdc1110685f4c2bea4ca4ceba4106488e33
2024-05-08 11:00:46
0a72edaddfd8858b4fe4830a24875fc1cc1be7fb
github-actions[bot]: ``` Warning: poetry-plugin-export will not be installed by default in a future version of Poetry. In order to avoid a breaking change and make your automation forward-compatible, please install poetry-plugin-export explicitly. See https://python-poetry.org/docs/plugins/#using-plugins for details on how to install a plugin. To disable this warning run 'poetry config warnings.export false'. The `--dev` option is deprecated, use the `--with dev` notation instead. +==============================================================================+ /$$$$$$ /$$ /$$__ $$ | $$ /$$$$$$$ /$$$$$$ | $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$_____/ |____ $$| $$$$ /$$__ $$|_ $$_/ | $$ | $$ | $$$$$$ /$$$$$$$| $$_/ | $$$$$$$$ | $$ | $$ | $$ \____ $$ /$$__ $$| $$ | $$_____/ | $$ /$$| $$ | $$ /$$$$$$$/| $$$$$$$| $$ | $$$$$$$ | $$$$/| $$$$$$$ |_______/ \_______/|__/ \_______/ \___/ \____ $$ /$$ | $$ | $$$$$$/ by safetycli.com \______/ +==============================================================================+ REPORT Safety is using PyUp's free open-source vulnerability database. This data is 30 days old and limited. For real-time enhanced vulnerability data, fix recommendations, severity reporting, cybersecurity support, team and project policy management and more sign up at https://pyup.io or email [email protected] Safety v3.1.0 is scanning for Vulnerabilities... Scanning dependencies in your files: -> /tmp/tmpeg_9z2g2 Using open-source vulnerability database Found and scanned 72 packages Timestamp 2024-05-08 11:01:27 0 vulnerabilities reported 0 vulnerabilities ignored +==============================================================================+ No known security vulnerabilities found. +==============================================================================+ Safety is using PyUp's free open-source vulnerability database. This data is 30 days old and limited. For real-time enhanced vulnerability data, fix recommendations, severity reporting, cybersecurity support, team and project policy management and more sign up at https://pyup.io or email [email protected] +==============================================================================+ ``` <!-- Sticky Pull Request CommentSafety result --> codecov[bot]: ## [Codecov](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/297?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning) Report Attention: Patch coverage is `91.66667%` with `1 lines` in your changes are missing coverage. Please review. > Project coverage is 99.78%. Comparing base [(`969a0bd`)](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/commit/969a0bdc1110685f4c2bea4ca4ceba4106488e33?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning) to head [(`d22516d`)](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/297?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning). | [Files](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/297?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning) | Patch % | Lines | |---|---|---| | [src/fdk\_rdf\_parser/parse\_functions/concept.py](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/297?src=pr&el=tree&filepath=src%2Ffdk_rdf_parser%2Fparse_functions%2Fconcept.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning#diff-c3JjL2Zka19yZGZfcGFyc2VyL3BhcnNlX2Z1bmN0aW9ucy9jb25jZXB0LnB5) | 91.66% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/297?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning) | <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #297 +/- ## =========================================== - Coverage 100.00% 99.78% -0.22% =========================================== Files 89 89 Lines 2366 2377 +11 Branches 263 268 +5 =========================================== + Hits 2366 2372 +6 - Misses 0 3 +3 - Partials 0 2 +2 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/297?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning).
diff --git a/src/fdk_rdf_parser/parse_functions/concept.py b/src/fdk_rdf_parser/parse_functions/concept.py index 75c9731..e891d18 100644 --- a/src/fdk_rdf_parser/parse_functions/concept.py +++ b/src/fdk_rdf_parser/parse_functions/concept.py @@ -35,6 +35,7 @@ from fdk_rdf_parser.rdf_utils import ( date_value, dcat_uri, euvoc_uri, + has_literal_value_on_predicate, has_value_on_predicate, is_type, object_value, @@ -356,15 +357,24 @@ def parse_collection(graph: Graph, concept_record_uri: URIRef) -> Optional[Colle return None -def parse_label_set( - graph: Graph, concept_uri: URIRef, predicate: URIRef +def extract_labels( + graph: Graph, concept_uri: URIRef, predicate: URIRef, predicate_deprecated: URIRef ) -> Optional[List[Dict[str, str]]]: - values = [] - for label in graph.objects(concept_uri, predicate): - literal_form = value_translations(graph, label, skosxl_uri("literalForm")) - if literal_form: - values.append(literal_form) - return values if len(values) > 0 else None + labels = list() + if has_literal_value_on_predicate(graph, concept_uri, predicate): + main_labels = value_translations(graph, concept_uri, predicate) + labels.append(main_labels) if main_labels is not None else None + + else: + deprecated_labels = [ + value_translations(graph, label, skosxl_uri("literalForm")) + for label in graph.objects(concept_uri, predicate_deprecated) + ] + + for label in deprecated_labels: + labels.append(label) if label is not None else None + + return labels if len(labels) > 0 else None def _parse_concept( @@ -374,7 +384,9 @@ def _parse_concept( concept_temporal = concept_temporal_list[0] if concept_temporal_list else Temporal() contact_points = extract_contact_points(graph, concept_uri) - pref_label_list = parse_label_set(graph, concept_uri, skosxl_uri("prefLabel")) + pref_label_list = extract_labels( + graph, concept_uri, SKOS.prefLabel, skosxl_uri("prefLabel") + ) definition_list = extract_definitions(graph, concept_uri) return Concept( @@ -390,8 +402,12 @@ def _parse_concept( prefLabel=( pref_label_list[0] if pref_label_list and len(pref_label_list) > 0 else None ), - hiddenLabel=parse_label_set(graph, concept_uri, skosxl_uri("hiddenLabel")), - altLabel=parse_label_set(graph, concept_uri, skosxl_uri("altLabel")), + hiddenLabel=extract_labels( + graph, concept_uri, SKOS.hiddenLabel, skosxl_uri("hiddenLabel") + ), + altLabel=extract_labels( + graph, concept_uri, SKOS.altLabel, skosxl_uri("altLabel") + ), contactPoint=contact_points[0] if contact_points else None, definition=get_first_definition_with_no_target_group(definition_list), definitions=definition_list, @@ -407,6 +423,6 @@ def _parse_concept( exactMatch=value_set(graph, concept_uri, SKOS.exactMatch), closeMatch=value_set(graph, concept_uri, SKOS.closeMatch), memberOf=value_set(graph, concept_uri, uneskos_uri("memberOf")), - remark=parse_label_set(graph, concept_uri, SKOS.scopeNote), + remark=extract_labels(graph, concept_uri, SKOS.scopeNote, SKOS.scopeNote), range=extract_range(graph, concept_uri), ) diff --git a/src/fdk_rdf_parser/rdf_utils/__init__.py b/src/fdk_rdf_parser/rdf_utils/__init__.py index 6d4607f..4148f87 100644 --- a/src/fdk_rdf_parser/rdf_utils/__init__.py +++ b/src/fdk_rdf_parser/rdf_utils/__init__.py @@ -32,6 +32,7 @@ from .ns import ( from .utils import ( date_value, duration_string_value, + has_literal_value_on_predicate, has_value_on_predicate, is_type, linguistic_system_keywords, diff --git a/src/fdk_rdf_parser/rdf_utils/utils.py b/src/fdk_rdf_parser/rdf_utils/utils.py index b69d91b..ee0fd48 100644 --- a/src/fdk_rdf_parser/rdf_utils/utils.py +++ b/src/fdk_rdf_parser/rdf_utils/utils.py @@ -19,6 +19,7 @@ from isodate import ( from rdflib import ( BNode, Graph, + Literal, URIRef, ) from rdflib.namespace import ( @@ -39,6 +40,13 @@ def has_value_on_predicate(graph: Graph, subject: URIRef, predicate: URIRef) -> return graph.value(subject, predicate) is not None +def has_literal_value_on_predicate( + graph: Graph, subject: URIRef, predicate: URIRef +) -> bool: + value = graph.value(subject, predicate) + return isinstance(value, Literal) + + def object_value(graph: Graph, subject: URIRef, predicate: URIRef) -> Optional[Any]: value = graph.value(subject, predicate) return value.toPython() if value and not isinstance(value, BNode) else None
Legg til støtte for labels fra skos-ap-no v.2.0.3 prefLabel, altLabel og hiddenLabel får alle tre nye predikater og går over til å være direkte angivelse - `skosxl:prefLabel` -> direkte angivelse på `skos:prefLabel`[ref](https://data.norge.no/specification/skos-ap-no-begrep#Begrep-anbefalt-term) - `skosxl:altLabel` -> direkte angivelse på `skos:altLabel` [ref](https://data.norge.no/specification/skos-ap-no-begrep#Begrep-tillatt-term) - `skosxl:hiddenLabel` -> direkte angivelse på `skos:hiddenLabel` [ref](https://data.norge.no/specification/skos-ap-no-begrep#Begrep-frar%C3%A5dd-term) i.e. ````` skosxl:prefLabel [ a skosxl:Label ; skosxl:literalForm "språkkode"@nb ] ; ````` 👇 ````` skos:prefLabel "språkkode"@nb ; `````
Informasjonsforvaltning/fdk-rdf-parser
diff --git a/tests/test_concept.py b/tests/test_concept.py index 2e0aecd..7b4dc47 100644 --- a/tests/test_concept.py +++ b/tests/test_concept.py @@ -77,6 +77,7 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: skosxl:literalForm "w"@nb ] ; skosxl:hiddenLabel [ ] ; + skos:hiddenLabel "hidden"@nb ; skosxl:prefLabel [ a skosxl:Label ; skosxl:literalForm "to"@nb ] ; @@ -289,6 +290,7 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: "nn": "gjeldande", "nb": "gjeldende", }, + hiddenLabel=[{"nb": "hidden"}], altLabel=[{"nb": "w"}], definition=Definition( text={"nb": "def-1"}, @@ -622,9 +624,7 @@ def test_parse_concept(mock_reference_data_client: Mock) -> None: skos:exactMatch <http://begrepskatalogen/begrep/20b2e2ab-9fe1-11e5-a9f8-e4115b280940> ; skos:closeMatch <http://begrepskatalogen/begrep/20b2e2aa-9fe1-11e5-a9f8-e4115b280940> ; uneskos:memberOf <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028> ; - skosxl:altLabel [ a skosxl:Label ; - skosxl:literalForm "w"@nb - ] ; + skos:altLabel "altLabel"@nb, "altLabel2"@en ; skosxl:hiddenLabel [ ] ; skosxl:prefLabel [ a skosxl:Label ; skosxl:literalForm "to"@nb @@ -695,7 +695,7 @@ def test_parse_concept(mock_reference_data_client: Mock) -> None: "nn": "gjeldande", "nb": "gjeldende", }, - altLabel=[{"nb": "w"}], + altLabel=[{"nb": "altLabel", "en": "altLabel2"}], definition=Definition( text={"nb": "skos_definition"}, ),
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
2.7
{ "env_vars": null, "env_yml_path": null, "install": "poetry install", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "poetry", "pip_packages": [ "pytest", "pytest-cov", "pytest-mock" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.6.0 argcomplete==3.3.0 attrs==23.2.0 Authlib==1.3.0 bandit==1.7.8 black==24.4.2 Brotli @ file:///croot/brotli-split_1736182456865/work build @ file:///croot/python-build_1679596508056/work CacheControl @ file:///croot/cachecontrol-split_1676365553644/work certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 cleo @ file:///croot/cleo_1705431334181/work click==8.1.7 codecov==2.1.13 colorlog==6.8.2 coverage==7.5.0 crashtest @ file:///croot/crashtest_1679422372509/work cryptography==42.0.5 distlib==0.3.8 dparse==0.6.4b0 dulwich @ file:///croot/dulwich_1679420040193/work exceptiongroup==1.2.1 -e git+https://github.com/Informasjonsforvaltning/fdk-rdf-parser.git@969a0bdc1110685f4c2bea4ca4ceba4106488e33#egg=fdk_rdf_parser filelock==3.13.4 flake8==7.0.0 flake8-annotations==3.0.1 flake8-bandit==4.1.1 flake8-black==0.3.6 flake8-bugbear==24.4.26 flake8-import-order==0.18.2 html5lib @ file:///Users/ktietz/demo/mc3/conda-bld/html5lib_1629144453894/work idna==3.7 importlib_metadata @ file:///croot/importlib_metadata-suite_1732633488278/work iniconfig==2.0.0 installer @ file:///croot/python-installer_1679432998036/work isodate==0.6.1 jaraco.classes @ file:///tmp/build/80754af9/jaraco.classes_1620983179379/work jeepney @ file:///tmp/build/80754af9/jeepney_1627537048313/work Jinja2==3.1.3 jsonschema @ file:///croot/jsonschema_1728486696720/work jsonschema-specifications @ file:///croot/jsonschema-specifications_1699032386549/work keyring @ file:///croot/keyring_1678999217139/work lockfile==0.12.2 markdown-it-py==3.0.0 MarkupSafe==2.1.5 marshmallow==3.21.1 mccabe==0.7.0 mdurl==0.1.2 more-itertools @ file:///croot/more-itertools_1727185441804/work msgpack @ file:///opt/conda/conda-bld/msgpack-python_1652362659880/work mypy==1.10.0 mypy-extensions==1.0.0 nox==2024.4.15 nox-poetry==1.0.3 numpy @ file:///croot/numpy_and_numpy_base_1725470312869/work/dist/numpy-2.0.1-cp39-cp39-linux_x86_64.whl#sha256=b8c18bbfe185fbdff23024458e4b8ffbe2040e705abd5fb6cda1ef9d20b5974d packaging==24.0 pathspec==0.12.1 pbr==6.0.0 pep8-naming==0.13.3 pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pkginfo @ file:///croot/pkginfo_1743184746806/work platformdirs==4.2.1 pluggy==1.5.0 poetry @ file:///croot/poetry_1680193142998/work poetry-core @ file:///croot/poetry-core_1680018645313/work poetry-plugin-export @ file:///croot/poetry-plugin-export_1680122784541/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl pycodestyle==2.11.1 pycparser==2.22 pydantic==2.7.1 pydantic_core==2.18.2 pyflakes==3.2.0 Pygments==2.17.2 pyOpenSSL @ file:///croot/pyopenssl_1741343803032/work pyparsing==3.1.2 pyproject_hooks @ file:///croot/pyproject_hooks_1679584411881/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305812635/work pytest==8.2.0 pytest-cov==5.0.0 pytest-mock==3.14.0 PyYAML==6.0.1 RapidFuzz @ file:///croot/rapidfuzz_1738592335633/work rdflib==7.0.0 referencing @ file:///croot/referencing_1699012038513/work requests==2.31.0 requests-toolbelt @ file:///Users/ktietz/demo/mc3/conda-bld/requests-toolbelt_1629456163440/work rich==13.7.1 rpds-py @ file:///croot/rpds-py_1736541261634/work ruamel.yaml==0.18.6 ruamel.yaml.clib==0.2.8 safety==3.1.0 safety-schemas==0.0.2 SecretStorage @ file:///croot/secretstorage_1678709481048/work shellingham==1.5.4 six==1.16.0 stevedore==5.2.0 tomli==2.0.1 tomlkit==0.12.4 trove-classifiers @ file:///croot/trove-classifiers_1729277230900/work typer==0.12.3 typing_extensions==4.11.0 urllib3==2.2.1 virtualenv==20.26.0 webencodings==0.5.1 zipp @ file:///croot/zipp_1732630741423/work
name: fdk-rdf-parser channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - blas=1.0=openblas - brotli-python=1.0.9=py39h6a678d5_9 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - cachecontrol=0.12.11=py39h06a4308_1 - charset-normalizer=3.3.2=pyhd3eb1b0_0 - cleo=2.1.0=py39h06a4308_0 - crashtest=0.4.1=py39h06a4308_0 - dbus=1.13.18=hb2f20db_0 - distlib=0.3.8=py39h06a4308_0 - dulwich=0.21.3=py39h5eee18b_0 - expat=2.6.4=h6a678d5_0 - glib=2.78.4=h6a678d5_0 - glib-tools=2.78.4=h6a678d5_0 - html5lib=1.1=pyhd3eb1b0_0 - idna=3.7=py39h06a4308_0 - importlib-metadata=8.5.0=py39h06a4308_0 - importlib_metadata=8.5.0=hd3eb1b0_0 - jaraco.classes=3.2.1=pyhd3eb1b0_0 - jeepney=0.7.1=pyhd3eb1b0_0 - jsonschema=4.23.0=py39h06a4308_0 - jsonschema-specifications=2023.7.1=py39h06a4308_0 - keyring=23.13.1=py39h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=11.2.0=h00389a5_1 - libgfortran5=11.2.0=h1234567_1 - libglib=2.78.4=hdc74915_0 - libgomp=11.2.0=h1234567_1 - libiconv=1.16=h5eee18b_3 - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - lockfile=0.12.2=py39h06a4308_0 - more-itertools=10.3.0=py39h06a4308_0 - msgpack-python=1.0.3=py39hd09550d_0 - ncurses=6.4=h6a678d5_0 - numpy=2.0.1=py39heeff2f4_1 - numpy-base=2.0.1=py39h8a23956_1 - openssl=3.0.16=h5eee18b_0 - pcre2=10.42=hebb0a14_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pip=25.0=py39h06a4308_0 - pkginfo=1.12.0=py39h06a4308_0 - poetry=1.4.0=py39h06a4308_0 - poetry-core=1.5.1=py39h06a4308_0 - poetry-plugin-export=1.3.0=py39h4849bfd_0 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pyopenssl=25.0.0=py39h06a4308_0 - pyproject_hooks=1.0.0=py39h06a4308_0 - pysocks=1.7.1=py39h06a4308_0 - python=3.9.21=he870216_1 - python-build=0.10.0=py39h06a4308_0 - python-installer=0.6.0=py39h06a4308_0 - rapidfuzz=3.12.1=py39h6a678d5_0 - readline=8.2=h5eee18b_0 - referencing=0.30.2=py39h06a4308_0 - requests-toolbelt=0.9.1=pyhd3eb1b0_0 - rpds-py=0.22.3=py39h4aa5aa6_0 - secretstorage=3.3.1=py39h06a4308_1 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - trove-classifiers=2024.10.14=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - webencodings=0.5.1=py39h06a4308_1 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.21.0=py39h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.6.0 - argcomplete==3.3.0 - attrs==23.2.0 - authlib==1.3.0 - bandit==1.7.8 - black==24.4.2 - certifi==2024.2.2 - cffi==1.16.0 - click==8.1.7 - codecov==2.1.13 - colorlog==6.8.2 - coverage==7.5.0 - cryptography==42.0.5 - dparse==0.6.4b0 - exceptiongroup==1.2.1 - fdk-rdf-parser==2.7.1 - filelock==3.13.4 - flake8==7.0.0 - flake8-annotations==3.0.1 - flake8-bandit==4.1.1 - flake8-black==0.3.6 - flake8-bugbear==24.4.26 - flake8-import-order==0.18.2 - iniconfig==2.0.0 - isodate==0.6.1 - jinja2==3.1.3 - markdown-it-py==3.0.0 - markupsafe==2.1.5 - marshmallow==3.21.1 - mccabe==0.7.0 - mdurl==0.1.2 - mypy==1.10.0 - mypy-extensions==1.0.0 - nox==2024.4.15 - nox-poetry==1.0.3 - packaging==24.0 - pathspec==0.12.1 - pbr==6.0.0 - pep8-naming==0.13.3 - platformdirs==4.2.1 - pluggy==1.5.0 - pycodestyle==2.11.1 - pycparser==2.22 - pydantic==2.7.1 - pydantic-core==2.18.2 - pyflakes==3.2.0 - pygments==2.17.2 - pyparsing==3.1.2 - pytest==8.2.0 - pytest-cov==5.0.0 - pytest-mock==3.14.0 - pyyaml==6.0.1 - rdflib==7.0.0 - requests==2.31.0 - rich==13.7.1 - ruamel-yaml==0.18.6 - ruamel-yaml-clib==0.2.8 - safety==3.1.0 - safety-schemas==0.0.2 - setuptools==69.5.1 - shellingham==1.5.4 - stevedore==5.2.0 - tomlkit==0.12.4 - typer==0.12.3 - typing-extensions==4.11.0 - urllib3==2.2.1 - virtualenv==20.26.0 prefix: /opt/conda/envs/fdk-rdf-parser
[ "tests/test_concept.py::test_parse_concepts", "tests/test_concept.py::test_parse_concept" ]
[]
[ "tests/test_concept.py::test_parse_concept_handles_wrong_collection_type" ]
[]
Apache License 2.0
18,372
1,296
[ "src/fdk_rdf_parser/parse_functions/concept.py", "src/fdk_rdf_parser/rdf_utils/__init__.py", "src/fdk_rdf_parser/rdf_utils/utils.py" ]
tobymao__sqlglot-3426
e8014e2a479c37ef75510e7d5ca90ed30522ce60
2024-05-08 11:46:07
761ba6fb507158d4e5ea51ca396809be91c11ebf
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py index 5a45215b..538cb9cb 100644 --- a/sqlglot/dialects/snowflake.py +++ b/sqlglot/dialects/snowflake.py @@ -345,6 +345,7 @@ class Snowflake(Dialect): FUNCTIONS = { **parser.Parser.FUNCTIONS, + "APPROX_PERCENTILE": exp.ApproxQuantile.from_arg_list, "ARRAYAGG": exp.ArrayAgg.from_arg_list, "ARRAY_CONSTRUCT": exp.Array.from_arg_list, "ARRAY_CONTAINS": lambda args: exp.ArrayContains( @@ -1051,3 +1052,11 @@ class Snowflake(Dialect): return f"{option} = ({values})" return super().copyparameter_sql(expression) + + def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: + if expression.args.get("weight") or expression.args.get("accuracy"): + self.unsupported( + "APPROX_PERCENTILE with weight and/or accuracy arguments are not supported in Snowflake" + ) + + return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile"))
APPROX_PERCENTILE is translated from Trino to APPROX_QUANTILE in Snowflake, which does not exist in Snowflake **Fully reproducible code snippet** ``` >>> sql = "SELECT APPROX_PERCENTILE(a,1, 0.5, 0.001) from t" >>> select = sqlglot.parse_one(sql, "trino") >>> select.sql("snowflake") 'SELECT APPROX_QUANTILE(a, 0.5, 0.001, 1) FROM t' ``` It should be translated to `APPROX_PERCENTILE` **Official Documentation** https://docs.snowflake.com/en/sql-reference/functions/approx_percentile
tobymao/sqlglot
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py index 62fa5974..d03412ca 100644 --- a/tests/dialects/test_snowflake.py +++ b/tests/dialects/test_snowflake.py @@ -832,6 +832,18 @@ WHERE "snowflake": "SELECT LISTAGG(col1, ', ') WITHIN GROUP (ORDER BY col2) FROM t", }, ) + self.validate_all( + "SELECT APPROX_PERCENTILE(a, 0.5) FROM t", + read={ + "trino": "SELECT APPROX_PERCENTILE(a, 1, 0.5, 0.001) FROM t", + "presto": "SELECT APPROX_PERCENTILE(a, 1, 0.5, 0.001) FROM t", + }, + write={ + "trino": "SELECT APPROX_PERCENTILE(a, 0.5) FROM t", + "presto": "SELECT APPROX_PERCENTILE(a, 0.5) FROM t", + "snowflake": "SELECT APPROX_PERCENTILE(a, 0.5) FROM t", + }, + ) def test_null_treatment(self): self.validate_all(
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
23.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.3.2 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@e8014e2a479c37ef75510e7d5ca90ed30522ce60#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.3.2 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake" ]
[]
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_copy", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_describe_table", "tests/dialects/test_snowflake.py::TestSnowflake::test_flatten", "tests/dialects/test_snowflake.py::TestSnowflake::test_historical_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_snowflake.py::TestSnowflake::test_minus", "tests/dialects/test_snowflake.py::TestSnowflake::test_null_treatment", "tests/dialects/test_snowflake.py::TestSnowflake::test_parse_like_any", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_replace", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_substr", "tests/dialects/test_snowflake.py::TestSnowflake::test_sample", "tests/dialects/test_snowflake.py::TestSnowflake::test_semi_structured_types", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_columns", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_imported_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_objects", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_primary_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_schemas", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_sequences", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_tables", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_unique_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_users", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_views", "tests/dialects/test_snowflake.py::TestSnowflake::test_staged_files", "tests/dialects/test_snowflake.py::TestSnowflake::test_storage_integration", "tests/dialects/test_snowflake.py::TestSnowflake::test_stored_procedures", "tests/dialects/test_snowflake.py::TestSnowflake::test_swap", "tests/dialects/test_snowflake.py::TestSnowflake::test_table_literal", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/dialects/test_snowflake.py::TestSnowflake::test_try_cast", "tests/dialects/test_snowflake.py::TestSnowflake::test_user_defined_functions", "tests/dialects/test_snowflake.py::TestSnowflake::test_values" ]
[]
MIT License
18,374
300
[ "sqlglot/dialects/snowflake.py" ]
tobymao__sqlglot-3440
761ba6fb507158d4e5ea51ca396809be91c11ebf
2024-05-09 09:12:27
761ba6fb507158d4e5ea51ca396809be91c11ebf
diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py index 3d2fb3d9..cba74403 100644 --- a/sqlglot/dialects/bigquery.py +++ b/sqlglot/dialects/bigquery.py @@ -609,7 +609,7 @@ class BigQuery(Dialect): exp.IntDiv: rename_func("DIV"), exp.JSONFormat: rename_func("TO_JSON_STRING"), exp.Max: max_or_greatest, - exp.Mod: rename_func("MOD"), + exp.Mod: lambda self, e: self.func("MOD", e.this.unnest(), e.expression.unnest()), exp.MD5: lambda self, e: self.func("TO_HEX", self.func("MD5", e.this)), exp.MD5Digest: rename_func("MD5"), exp.Min: min_or_least, diff --git a/sqlglot/generator.py b/sqlglot/generator.py index 6c56d1c2..37c04409 100644 --- a/sqlglot/generator.py +++ b/sqlglot/generator.py @@ -2845,7 +2845,8 @@ class Generator(metaclass=_Generator): stack.append(expression.right) if expression.comments and self.comments: for comment in expression.comments: - op += f" /*{self.pad_comment(comment)}*/" + if comment: + op += f" /*{self.pad_comment(comment)}*/" stack.extend((op, expression.left)) return op diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 8f5050ee..2f995f61 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -74,6 +74,17 @@ def build_extract_json_with_path(expr_type: t.Type[E]) -> t.Callable[[t.List, Di return _builder +def build_mod(args: t.List) -> exp.Mod: + this = seq_get(args, 0) + expression = seq_get(args, 1) + + # Wrap the operands if they are binary nodes, e.g. MOD(a + 1, 7) -> (a + 1) % 7 + this = exp.Paren(this=this) if isinstance(this, exp.Binary) else this + expression = exp.Paren(this=expression) if isinstance(expression, exp.Binary) else expression + + return exp.Mod(this=this, expression=expression) + + class _Parser(type): def __new__(cls, clsname, bases, attrs): klass = super().__new__(cls, clsname, bases, attrs) @@ -123,7 +134,7 @@ class Parser(metaclass=_Parser): "LOG": build_logarithm, "LOG2": lambda args: exp.Log(this=exp.Literal.number(2), expression=seq_get(args, 0)), "LOG10": lambda args: exp.Log(this=exp.Literal.number(10), expression=seq_get(args, 0)), - "MOD": lambda args: exp.Mod(this=seq_get(args, 0), expression=seq_get(args, 1)), + "MOD": build_mod, "TIME_TO_TIME_STR": lambda args: exp.Cast( this=seq_get(args, 0), to=exp.DataType(this=exp.DataType.Type.TEXT),
Incorrect transpiling of MOD function from trino to snowflake Appears in 3.14 The following expression in Trino `(MOD((DAY_OF_YEAR(world."orders.date") % 7) - 1 + 7, 7))` is transpiled in Snowflake as `((DAYOFYEAR(orders.date) % 7) - 1 + 7 % 7)` The transpiled expression returns incorrect result, as values could be negative (-1). Missing a parenthesis before the modulo operator, to make it correct. Expected result: `(MOD((DAYOFYEAR(orders.date) % 7) - 1 + 7, 7))` or `(((DAYOFYEAR(orders.date) % 7) - 1 + 7 ) % 7)` **Fully reproducible code snippet** ``` from sqlglot import Dialects, parse_one trino_sql = 'SELECT (MOD((DAY_OF_YEAR(orders.date) % 7) - 1 + 7, 7)) FROM orders' parsed = parse_one(sql, dialect=Dialects.TRINO) snowflake_sql = parsed.sql(dialect=Dialects.SNOWFLAKE) ``` **Official Documentation** https://trino.io/docs/current/functions/datetime.html#day_of_year https://trino.io/docs/current/functions/math.html#mod https://docs.snowflake.com/en/sql-reference/functions/year https://docs.snowflake.com/en/sql-reference/functions/mod
tobymao/sqlglot
diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py index 301cd572..338a979b 100644 --- a/tests/dialects/test_bigquery.py +++ b/tests/dialects/test_bigquery.py @@ -1464,3 +1464,13 @@ OPTIONS ( with self.assertRaises(ParseError): transpile("SELECT JSON_OBJECT('a', 1, 'b') AS json_data", read="bigquery") + + def test_mod(self): + for sql in ("MOD(a, b)", "MOD('a', b)", "MOD(5, 2)", "MOD((a + 1) * 8, 5 - 1)"): + with self.subTest(f"Testing BigQuery roundtrip of modulo operation: {sql}"): + self.validate_identity(sql) + + self.validate_identity( + "MOD((a + 1), b)", + "MOD(a + 1, b)", + ) diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py index dda0eb2a..809cb6da 100644 --- a/tests/dialects/test_dialect.py +++ b/tests/dialects/test_dialect.py @@ -1681,6 +1681,26 @@ class TestDialect(Validator): "tsql": "CAST(a AS FLOAT) / b", }, ) + self.validate_all( + "MOD(8 - 1 + 7, 7)", + write={ + "": "(8 - 1 + 7) % 7", + "hive": "(8 - 1 + 7) % 7", + "presto": "(8 - 1 + 7) % 7", + "snowflake": "(8 - 1 + 7) % 7", + "bigquery": "MOD(8 - 1 + 7, 7)", + }, + ) + self.validate_all( + "MOD(a, b + 1)", + write={ + "": "a % (b + 1)", + "hive": "a % (b + 1)", + "presto": "a % (b + 1)", + "snowflake": "a % (b + 1)", + "bigquery": "MOD(a, b + 1)", + }, + ) def test_typeddiv(self): typed_div = exp.Div(this=exp.column("a"), expression=exp.column("b"), typed=True) diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py index 2d0af135..f736264c 100644 --- a/tests/dialects/test_duckdb.py +++ b/tests/dialects/test_duckdb.py @@ -803,7 +803,7 @@ class TestDuckDB(Validator): write={"duckdb": "SELECT (90 * INTERVAL '1' DAY)"}, ) self.validate_all( - "SELECT ((DATE_TRUNC('DAY', CAST(CAST(DATE_TRUNC('DAY', CURRENT_TIMESTAMP) AS DATE) AS TIMESTAMP) + INTERVAL (0 - (DAYOFWEEK(CAST(CAST(DATE_TRUNC('DAY', CURRENT_TIMESTAMP) AS DATE) AS TIMESTAMP)) % 7) - 1 + 7 % 7) DAY) + (7 * INTERVAL (-5) DAY))) AS t1", + "SELECT ((DATE_TRUNC('DAY', CAST(CAST(DATE_TRUNC('DAY', CURRENT_TIMESTAMP) AS DATE) AS TIMESTAMP) + INTERVAL (0 - ((DAYOFWEEK(CAST(CAST(DATE_TRUNC('DAY', CURRENT_TIMESTAMP) AS DATE) AS TIMESTAMP)) % 7) - 1 + 7) % 7) DAY) + (7 * INTERVAL (-5) DAY))) AS t1", read={ "presto": "SELECT ((DATE_ADD('week', -5, DATE_TRUNC('DAY', DATE_ADD('day', (0 - MOD((DAY_OF_WEEK(CAST(CAST(DATE_TRUNC('DAY', NOW()) AS DATE) AS TIMESTAMP)) % 7) - 1 + 7, 7)), CAST(CAST(DATE_TRUNC('DAY', NOW()) AS DATE) AS TIMESTAMP)))))) AS t1", }, diff --git a/tests/test_transpile.py b/tests/test_transpile.py index 22085b32..dea9985b 100644 --- a/tests/test_transpile.py +++ b/tests/test_transpile.py @@ -551,6 +551,13 @@ FROM x""", pretty=True, ) + self.validate( + """SELECT X FROM catalog.db.table WHERE Y + -- + AND Z""", + """SELECT X FROM catalog.db.table WHERE Y AND Z""", + ) + def test_types(self): self.validate("INT 1", "CAST(1 AS INT)") self.validate("VARCHAR 'x' y", "CAST('x' AS VARCHAR) AS y")
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 3 }
23.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@761ba6fb507158d4e5ea51ca396809be91c11ebf#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_mod", "tests/dialects/test_dialect.py::TestDialect::test_operators", "tests/dialects/test_duckdb.py::TestDuckDB::test_time", "tests/test_transpile.py::TestTranspile::test_comments" ]
[]
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery", "tests/dialects/test_bigquery.py::TestBigQuery::test_errors", "tests/dialects/test_bigquery.py::TestBigQuery::test_group_concat", "tests/dialects/test_bigquery.py::TestBigQuery::test_json_object", "tests/dialects/test_bigquery.py::TestBigQuery::test_merge", "tests/dialects/test_bigquery.py::TestBigQuery::test_models", "tests/dialects/test_bigquery.py::TestBigQuery::test_pushdown_cte_column_names", "tests/dialects/test_bigquery.py::TestBigQuery::test_remove_precision_parameterized_types", "tests/dialects/test_bigquery.py::TestBigQuery::test_rename_table", "tests/dialects/test_bigquery.py::TestBigQuery::test_user_defined_functions", "tests/dialects/test_bigquery.py::TestBigQuery::test_warnings", "tests/dialects/test_dialect.py::TestDialect::test_alias", "tests/dialects/test_dialect.py::TestDialect::test_array", "tests/dialects/test_dialect.py::TestDialect::test_array_any", "tests/dialects/test_dialect.py::TestDialect::test_cast", "tests/dialects/test_dialect.py::TestDialect::test_cast_to_user_defined_type", "tests/dialects/test_dialect.py::TestDialect::test_compare_dialects", "tests/dialects/test_dialect.py::TestDialect::test_count_if", "tests/dialects/test_dialect.py::TestDialect::test_create_sequence", "tests/dialects/test_dialect.py::TestDialect::test_cross_join", "tests/dialects/test_dialect.py::TestDialect::test_ddl", "tests/dialects/test_dialect.py::TestDialect::test_decode", "tests/dialects/test_dialect.py::TestDialect::test_enum", "tests/dialects/test_dialect.py::TestDialect::test_get_or_raise", "tests/dialects/test_dialect.py::TestDialect::test_hash_comments", "tests/dialects/test_dialect.py::TestDialect::test_heredoc_strings", "tests/dialects/test_dialect.py::TestDialect::test_if_null", "tests/dialects/test_dialect.py::TestDialect::test_json", "tests/dialects/test_dialect.py::TestDialect::test_lateral_subquery", "tests/dialects/test_dialect.py::TestDialect::test_limit", "tests/dialects/test_dialect.py::TestDialect::test_logarithm", "tests/dialects/test_dialect.py::TestDialect::test_merge", "tests/dialects/test_dialect.py::TestDialect::test_nested_ctes", "tests/dialects/test_dialect.py::TestDialect::test_nullsafe_eq", "tests/dialects/test_dialect.py::TestDialect::test_nullsafe_neq", "tests/dialects/test_dialect.py::TestDialect::test_nvl2", "tests/dialects/test_dialect.py::TestDialect::test_order_by", "tests/dialects/test_dialect.py::TestDialect::test_qualify", "tests/dialects/test_dialect.py::TestDialect::test_random", "tests/dialects/test_dialect.py::TestDialect::test_reserved_keywords", "tests/dialects/test_dialect.py::TestDialect::test_safediv", "tests/dialects/test_dialect.py::TestDialect::test_set_operators", "tests/dialects/test_dialect.py::TestDialect::test_substring", "tests/dialects/test_dialect.py::TestDialect::test_time", "tests/dialects/test_dialect.py::TestDialect::test_transactions", "tests/dialects/test_dialect.py::TestDialect::test_truncate", "tests/dialects/test_dialect.py::TestDialect::test_typeddiv", "tests/dialects/test_dialect.py::TestDialect::test_unsupported_null_ordering", "tests/dialects/test_duckdb.py::TestDuckDB::test_array", "tests/dialects/test_duckdb.py::TestDuckDB::test_array_index", "tests/dialects/test_duckdb.py::TestDuckDB::test_bool_or", "tests/dialects/test_duckdb.py::TestDuckDB::test_cast", "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_duckdb.py::TestDuckDB::test_encode_decode", "tests/dialects/test_duckdb.py::TestDuckDB::test_isinf", "tests/dialects/test_duckdb.py::TestDuckDB::test_isnan", "tests/dialects/test_duckdb.py::TestDuckDB::test_parameter_token", "tests/dialects/test_duckdb.py::TestDuckDB::test_rename_table", "tests/dialects/test_duckdb.py::TestDuckDB::test_sample", "tests/dialects/test_duckdb.py::TestDuckDB::test_timestamps_with_units", "tests/test_transpile.py::TestTranspile::test_alias", "tests/test_transpile.py::TestTranspile::test_alter", "tests/test_transpile.py::TestTranspile::test_command_identity", "tests/test_transpile.py::TestTranspile::test_error_level", "tests/test_transpile.py::TestTranspile::test_extract", "tests/test_transpile.py::TestTranspile::test_identify_lambda", "tests/test_transpile.py::TestTranspile::test_identity", "tests/test_transpile.py::TestTranspile::test_if", "tests/test_transpile.py::TestTranspile::test_index_offset", "tests/test_transpile.py::TestTranspile::test_leading_comma", "tests/test_transpile.py::TestTranspile::test_normalize_name", "tests/test_transpile.py::TestTranspile::test_not_range", "tests/test_transpile.py::TestTranspile::test_paren", "tests/test_transpile.py::TestTranspile::test_partial", "tests/test_transpile.py::TestTranspile::test_pretty", "tests/test_transpile.py::TestTranspile::test_pretty_line_breaks", "tests/test_transpile.py::TestTranspile::test_recursion", "tests/test_transpile.py::TestTranspile::test_some", "tests/test_transpile.py::TestTranspile::test_space", "tests/test_transpile.py::TestTranspile::test_time", "tests/test_transpile.py::TestTranspile::test_types", "tests/test_transpile.py::TestTranspile::test_unary", "tests/test_transpile.py::TestTranspile::test_unsupported_level", "tests/test_transpile.py::TestTranspile::test_weird_chars", "tests/test_transpile.py::TestTranspile::test_with" ]
[]
MIT License
18,390
783
[ "sqlglot/dialects/bigquery.py", "sqlglot/generator.py", "sqlglot/parser.py" ]
mkdocs__mkdocs-3700
30e8142315127bcc2b05ee14ff99f300a7126a87
2024-05-09 14:28:04
8058b78f530c19778bfaed6f803007c77967f31e
diff --git a/mkdocs/theme.py b/mkdocs/theme.py index bf587201..b45f1079 100644 --- a/mkdocs/theme.py +++ b/mkdocs/theme.py @@ -138,6 +138,9 @@ class Theme(MutableMapping[str, Any]): f"Please upgrade to a current version of the theme." ) + if theme_config is None: + theme_config = {} + log.debug(f"Loaded theme configuration for '{name}' from '{file_path}': {theme_config}") if parent_theme := theme_config.pop('extends', None):
Empty mkdocs_theme.yml breaks build Hello! In the docs its [stated](https://www.mkdocs.org/dev-guide/themes/#theme-configuration) that a theme **can** have an empty `mkdocs_theme.yml` file: > However, if the theme offers no configuration options, the file is still required and can be left blank. Unfortunately this seems to have changed recently and now themes with empty `mkdocs_theme.yml` files are causing an exception when building: ```shell > mkdocs build --verbose DEBUG - Loading configuration file: ./mkdocs.yml DEBUG - Loaded theme configuration for 'custom_theme' from './venv/lib/python3.12/site-packages/custom_theme/mkdocs_theme.yml': None Traceback (most recent call last): [...] File "./venv/lib/python3.12/site-packages/mkdocs/config/config_options.py", line 868, in run_validation return theme.Theme(**theme_config) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "./venv/lib/python3.12/site-packages/mkdocs/theme.py", line 61, in __init__ self._load_theme_config(name) File "./venv/lib/python3.12/site-packages/mkdocs/theme.py", line 143, in _load_theme_config if parent_theme := theme_config.pop('extends', None): ^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'pop' ```
mkdocs/mkdocs
diff --git a/mkdocs/tests/theme_tests.py b/mkdocs/tests/theme_tests.py index f9989fb3..ddc526bf 100644 --- a/mkdocs/tests/theme_tests.py +++ b/mkdocs/tests/theme_tests.py @@ -104,3 +104,22 @@ class ThemeTests(unittest.TestCase): ], ) self.assertEqual(theme.static_templates, {'sitemap.xml', 'child.html', 'parent.html'}) + + def test_empty_config_file(self): + # Test for themes with *empty* mkdocs_theme.yml. + # See https://github.com/mkdocs/mkdocs/issues/3699 + m = mock.Mock( + # yaml.load returns "None" for an empty file + side_effect=[None] + ) + with mock.patch('yaml.load', m) as m: + theme = Theme(name='mkdocs') + # Should only have the default name and locale __vars set in + # Theme.__init__() + self.assertEqual( + dict(theme), + { + 'name': 'mkdocs', + 'locale': parse_locale('en'), + }, + )
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "hatch", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
anyio==4.9.0 backports.tarfile==1.2.0 certifi==2025.1.31 cffi==1.17.1 click==8.1.8 cryptography==44.0.2 distlib==0.3.9 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 ghp-import==2.1.0 h11==0.14.0 hatch==1.14.0 hatchling==1.27.0 httpcore==1.0.7 httpx==0.28.1 hyperlink==21.0.0 idna==3.10 importlib_metadata==8.6.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jeepney==0.9.0 Jinja2==3.1.6 keyring==25.6.0 Markdown==3.7 markdown-it-py==3.0.0 MarkupSafe==3.0.2 mdurl==0.1.2 mergedeep==1.3.4 -e git+https://github.com/mkdocs/mkdocs.git@30e8142315127bcc2b05ee14ff99f300a7126a87#egg=mkdocs mkdocs-get-deps==0.2.0 more-itertools==10.6.0 packaging @ file:///croot/packaging_1734472117206/work pathspec==0.12.1 pexpect==4.9.0 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work ptyprocess==0.7.0 pycparser==2.22 Pygments==2.19.1 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 PyYAML==6.0.2 pyyaml_env_tag==0.1 rich==14.0.0 SecretStorage==3.3.3 shellingham==1.5.4 six==1.17.0 sniffio==1.3.1 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tomli_w==1.2.0 tomlkit==0.13.2 trove-classifiers==2025.3.19.19 typing_extensions==4.13.0 userpath==1.9.2 uv==0.6.11 virtualenv==20.29.3 watchdog==6.0.0 zipp==3.21.0 zstandard==0.23.0
name: mkdocs channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - anyio==4.9.0 - backports-tarfile==1.2.0 - certifi==2025.1.31 - cffi==1.17.1 - click==8.1.8 - cryptography==44.0.2 - distlib==0.3.9 - filelock==3.18.0 - ghp-import==2.1.0 - h11==0.14.0 - hatch==1.14.0 - hatchling==1.27.0 - httpcore==1.0.7 - httpx==0.28.1 - hyperlink==21.0.0 - idna==3.10 - importlib-metadata==8.6.1 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jeepney==0.9.0 - jinja2==3.1.6 - keyring==25.6.0 - markdown==3.7 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - mdurl==0.1.2 - mergedeep==1.3.4 - mkdocs==1.6.0 - mkdocs-get-deps==0.2.0 - more-itertools==10.6.0 - pathspec==0.12.1 - pexpect==4.9.0 - platformdirs==4.3.7 - ptyprocess==0.7.0 - pycparser==2.22 - pygments==2.19.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - pyyaml-env-tag==0.1 - rich==14.0.0 - secretstorage==3.3.3 - shellingham==1.5.4 - six==1.17.0 - sniffio==1.3.1 - tomli-w==1.2.0 - tomlkit==0.13.2 - trove-classifiers==2025.3.19.19 - typing-extensions==4.13.0 - userpath==1.9.2 - uv==0.6.11 - virtualenv==20.29.3 - watchdog==6.0.0 - zipp==3.21.0 - zstandard==0.23.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/theme_tests.py::ThemeTests::test_empty_config_file" ]
[]
[ "mkdocs/tests/theme_tests.py::ThemeTests::test_custom_dir", "mkdocs/tests/theme_tests.py::ThemeTests::test_custom_dir_only", "mkdocs/tests/theme_tests.py::ThemeTests::test_inherited_theme", "mkdocs/tests/theme_tests.py::ThemeTests::test_no_theme_config", "mkdocs/tests/theme_tests.py::ThemeTests::test_simple_theme", "mkdocs/tests/theme_tests.py::ThemeTests::test_vars" ]
[]
BSD 2-Clause "Simplified" License
18,392
147
[ "mkdocs/theme.py" ]
lincc-frameworks__nested-pandas-73
a196bd63cfa77bdb74ad2a00d1637de5b714c367
2024-05-09 15:04:58
a196bd63cfa77bdb74ad2a00d1637de5b714c367
diff --git a/src/nested_pandas/series/accessor.py b/src/nested_pandas/series/accessor.py index 021fbd7..8a075a7 100644 --- a/src/nested_pandas/series/accessor.py +++ b/src/nested_pandas/series/accessor.py @@ -91,13 +91,15 @@ class NestSeriesAccessor(MutableMapping): index = None for field in fields: list_array = cast(pa.ListArray, struct_array.field(field)) + flat_array = list_array.flatten() if index is None: index = self.get_flat_index() flat_series[field] = pd.Series( - list_array.flatten(), + flat_array, index=pd.Series(index, name=self._series.index.name), name=field, copy=False, + dtype=pd.ArrowDtype(flat_array.type), ) return pd.DataFrame(flat_series)
.nest.to_flat() should return pd.ArrowDtyped dataframe **Bug report** It is currently returning "native" pandas dtypes which is inconsistent with what `.nest["field"]` returns **Before submitting** Please check the following: - [ ] I have described the situation in which the bug arose, including what code was executed, information about my environment, and any applicable data others will need to reproduce the problem. - [ ] I have included available evidence of the unexpected behavior (including error messages, screenshots, and/or plots) as well as a descriprion of what I expected instead. - [ ] If I have a solution in mind, I have provided an explanation and/or pseudocode and/or task list.
lincc-frameworks/nested-pandas
diff --git a/tests/nested_pandas/nestedframe/test_nestedframe.py b/tests/nested_pandas/nestedframe/test_nestedframe.py index cff96e4..4bfd710 100644 --- a/tests/nested_pandas/nestedframe/test_nestedframe.py +++ b/tests/nested_pandas/nestedframe/test_nestedframe.py @@ -76,7 +76,8 @@ def test_add_nested_with_flat_df(): base = base.add_nested(nested, "nested") assert "nested" in base.columns - assert base.nested.nest.to_flat().equals(nested) + # to_flat() gives pd.ArrowDtype, so we skip dtype check here + assert_frame_equal(base.nested.nest.to_flat(), nested, check_dtype=False) def test_add_nested_with_flat_df_and_mismatched_index(): diff --git a/tests/nested_pandas/series/test_accessor.py b/tests/nested_pandas/series/test_accessor.py index 807657b..9a02aa2 100644 --- a/tests/nested_pandas/series/test_accessor.py +++ b/tests/nested_pandas/series/test_accessor.py @@ -101,12 +101,14 @@ def test_to_flat(): index=[0, 0, 0, 1, 1, 1], name="a", copy=False, + dtype=pd.ArrowDtype(pa.float64()), ), "b": pd.Series( data=[-4.0, -5.0, -6.0, -3.0, -4.0, -5.0], index=[0, 0, 0, 1, 1, 1], name="b", copy=False, + dtype=pd.ArrowDtype(pa.float64()), ), }, index=pd.Index([0, 0, 0, 1, 1, 1], name="idx"), @@ -140,6 +142,7 @@ def test_to_flat_with_fields(): index=[0, 0, 0, 1, 1, 1], name="a", copy=False, + dtype=pd.ArrowDtype(pa.float64()), ), }, ) @@ -527,7 +530,7 @@ def test_to_flat_dropna(): """ flat = pd.DataFrame( - data={"c": [0.0, 2, 4, 1, np.NaN, 3, 1, 4, 1], "d": [5, 4, 7, 5, 3, 1, 9, 3, 4]}, + data={"c": [0, 2, 4, 1, np.NaN, 3, 1, 4, 1], "d": [5, 4, 7, 5, 3, 1, 9, 3, 4]}, index=[0, 0, 0, 1, 1, 1, 2, 2, 2], ) nested = pack_flat(flat, name="nested") @@ -542,4 +545,5 @@ def test_to_flat_dropna(): data={"c": [0.0, 2, 4, 1, 3, 1, 4, 1], "d": [5, 4, 7, 5, 1, 9, 3, 4]}, index=[0, 0, 0, 1, 1, 2, 2, 2], ), + check_dtype=False, # filtered's Series are pd.ArrowDtype )
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 1 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
accessible-pygments==0.0.5 alabaster==0.7.16 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 astroid==3.3.9 asttokens==3.0.0 asv==0.6.3 asv_runner==0.2.1 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 bleach==6.2.0 build==1.2.2.post1 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 comm==0.2.2 coverage==7.8.0 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fqdn==1.5.1 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 identify==2.6.9 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 jupytext==1.16.7 markdown-it-py==3.0.0 MarkupSafe==3.0.2 matplotlib-inline==0.1.7 mdit-py-plugins==0.4.2 mdurl==0.1.2 mistune==3.1.3 mypy==1.15.0 mypy-extensions==1.0.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbsphinx==0.9.7 nest-asyncio==1.6.0 -e git+https://github.com/lincc-frameworks/nested-pandas.git@a196bd63cfa77bdb74ad2a00d1637de5b714c367#egg=nested_pandas nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pycparser==2.22 pydata-sphinx-theme==0.15.4 Pygments==2.19.1 Pympler==1.1 pyproject_hooks==1.2.0 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 ruff==0.11.2 Send2Trash==1.8.3 six==1.17.0 sniffio==1.3.1 snowballstemmer==2.2.0 soupsieve==2.6 Sphinx==7.4.7 sphinx-autoapi==3.6.0 sphinx-book-theme==1.1.4 sphinx-copybutton==0.5.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 stack-data==0.6.3 stdlib-list==0.11.1 tabulate==0.9.0 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 zipp==3.21.0
name: nested-pandas channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - accessible-pygments==0.0.5 - alabaster==0.7.16 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - astroid==3.3.9 - asttokens==3.0.0 - asv==0.6.3 - asv-runner==0.2.1 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - build==1.2.2.post1 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - comm==0.2.2 - coverage==7.8.0 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fqdn==1.5.1 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - jupytext==1.16.7 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - matplotlib-inline==0.1.7 - mdit-py-plugins==0.4.2 - mdurl==0.1.2 - mistune==3.1.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbsphinx==0.9.7 - nest-asyncio==1.6.0 - nested-pandas==0.1.dev108+ga196bd6 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pycparser==2.22 - pydata-sphinx-theme==0.15.4 - pygments==2.19.1 - pympler==1.1 - pyproject-hooks==1.2.0 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - ruff==0.11.2 - send2trash==1.8.3 - six==1.17.0 - sniffio==1.3.1 - snowballstemmer==2.2.0 - soupsieve==2.6 - sphinx==7.4.7 - sphinx-autoapi==3.6.0 - sphinx-book-theme==1.1.4 - sphinx-copybutton==0.5.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - stack-data==0.6.3 - stdlib-list==0.11.1 - tabulate==0.9.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - zipp==3.21.0 prefix: /opt/conda/envs/nested-pandas
[ "tests/nested_pandas/series/test_accessor.py::test_to_flat", "tests/nested_pandas/series/test_accessor.py::test_to_flat_with_fields" ]
[ "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna_inplace_base", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna_inplace_nested", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna_errors", "tests/nested_pandas/series/test_accessor.py::test_to_flat_dropna" ]
[ "tests/nested_pandas/nestedframe/test_nestedframe.py::test_nestedframe_construction", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_all_columns", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_nested_columns", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_is_known_hierarchical_column", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_with_flat_df", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_with_flat_df_and_mismatched_index", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_with_series", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_with_series_and_mismatched_index", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_query", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_reduce", "tests/nested_pandas/series/test_accessor.py::test_registered", "tests/nested_pandas/series/test_accessor.py::test_to_lists", "tests/nested_pandas/series/test_accessor.py::test_to_lists_with_fields", "tests/nested_pandas/series/test_accessor.py::test_fields", "tests/nested_pandas/series/test_accessor.py::test_flat_length", "tests/nested_pandas/series/test_accessor.py::test_set_flat_field", "tests/nested_pandas/series/test_accessor.py::test_set_list_field", "tests/nested_pandas/series/test_accessor.py::test_pop_field", "tests/nested_pandas/series/test_accessor.py::test_query_flat_1", "tests/nested_pandas/series/test_accessor.py::test_query_flat_empty_rows", "tests/nested_pandas/series/test_accessor.py::test_get_list_series", "tests/nested_pandas/series/test_accessor.py::test___getitem___single_field", "tests/nested_pandas/series/test_accessor.py::test___getitem___multiple_fields", "tests/nested_pandas/series/test_accessor.py::test___setitem__", "tests/nested_pandas/series/test_accessor.py::test___setitem___with_series_with_index", "tests/nested_pandas/series/test_accessor.py::test___setitem___raises_for_wrong_length", "tests/nested_pandas/series/test_accessor.py::test___setitem___raises_for_wrong_index", "tests/nested_pandas/series/test_accessor.py::test___delitem__", "tests/nested_pandas/series/test_accessor.py::test___iter__", "tests/nested_pandas/series/test_accessor.py::test___len__" ]
[]
MIT License
18,393
212
[ "src/nested_pandas/series/accessor.py" ]
xCDAT__xcdat-653
77457577ebd358a86123049f78693e36719c8792
2024-05-09 17:26:40
7d99c852f05c6fcf8ff2b8aafe9dabe5fcb40cba
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/xCDAT/xcdat/pull/653?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=xCDAT) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 100.00%. Comparing base [(`7745757`)](https://app.codecov.io/gh/xCDAT/xcdat/commit/77457577ebd358a86123049f78693e36719c8792?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=xCDAT) to head [(`b7f6fe9`)](https://app.codecov.io/gh/xCDAT/xcdat/pull/653?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=xCDAT). <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #653 +/- ## ========================================= Coverage 100.00% 100.00% ========================================= Files 15 15 Lines 1543 1544 +1 ========================================= + Hits 1543 1544 +1 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/xCDAT/xcdat/pull/653?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=xCDAT). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=xCDAT).
diff --git a/xcdat/regridder/regrid2.py b/xcdat/regridder/regrid2.py index 823215d..9b71979 100644 --- a/xcdat/regridder/regrid2.py +++ b/xcdat/regridder/regrid2.py @@ -150,6 +150,7 @@ def _regrid( other_sizes = list(other_dims.values()) data_shape = [y_length * x_length] + other_sizes + # output data is always float32 in original code output_data = np.zeros(data_shape, dtype=np.float32) output_mask = np.ones(data_shape, dtype=np.float32) @@ -212,7 +213,11 @@ def _regrid( output_data = output_data.reshape(output_data_shape) - output_order = [x + 2 for x in range(input_data_var.ndim - 2)] + [0, 1] + # temp dimensional ordering + temp_dims = [y_name, x_name] + list(other_dims.keys()) + + # map temp ordering to input ordering + output_order = [temp_dims.index(x) for x in input_data_var.dims] output_data = output_data.transpose(output_order)
[Bug]: Regrid2 breaks in `_preserve_bounds` because `_regrid` incorrectly transposes `output_data` shape, which doesn't align with original dim order used by bounds ### What happened? There is an issue where transposing the shape of data causes misalignment with the original dimension order. When we attempt to preserve bounds, the original dimension order is still being used which does not align with the transposed dimension order. ### Example Let's say we have `ds_a` with an original dimension of shape of `(lat: 1, lev: 2, lon: 3)`. After transposing the data, `output_data` become `shape=(2, 1, 3)`. https://github.com/xCDAT/xcdat/blob/d0e33aaea04ffeca0301cd7773e4f981c7957653/xcdat/regridder/regrid2.py#L164-L172 We recreate the `xr.DataArray` (`output_da`) using `output_data` and `dims`. As mentioned above, the shape of `output_data` is now transposed, but it does not align with the original `dims`. This results in `output_da` having a new dimension shape of `(lat: 2, lev: 1, lon: 3)` https://github.com/xCDAT/xcdat/blob/d0e33aaea04ffeca0301cd7773e4f981c7957653/xcdat/regridder/regrid2.py#L184-L197 When we attempt to preserve `lat_bnds` in `_preserve_bounds()`, the original `lat_bnds` still has has a shape of `(lat: 1, lev: 2, lon: 3)`, which does not align with `(lat: 2, lev: 1, lon: 3)`. https://github.com/xCDAT/xcdat/blob/d0e33aaea04ffeca0301cd7773e4f981c7957653/xcdat/regridder/base.py#L48-L58 This results in `ValueError: cannot reindex or align along dimension 'lat' because of conflicting dimension sizes: {1, 2} (note: an index is found along that dimension with size=1)`. ### What did you expect to happen? Are there are possible answers you came across? Maybe `output_data` shape should align with the original dim order or we should also transpose the shape of the bounds? ### Minimal Complete Verifiable Example (MVCE) ```python import numpy as np import xarray as xr import xcdat as xc # 1. Create two datasets with dimensions (lat=1, lev=2, lon=3) ds_a = xr.Dataset( { "lat": xr.DataArray( name="lat", dims="lat", data=[0], attrs={"axis": "Y", "bounds": "lat_bnds"} ), "lev": xr.DataArray(name="lev", dims="lev", data=[0, 1], attrs={"axis": "Z"}), "lon": xr.DataArray( name="lon", dims="lon", data=[0, 1, 2], attrs={"axis": "X"} ), } ) ds_a["T"] = xr.DataArray(name="T", dims=["lat", "lev", "lon"], data=np.zeros((1, 2, 3))) ds_a = ds_a.bounds.add_missing_bounds(axes=["X", "Y", "Z"]) # Manually add lat_bnds because xCDAT does not support adding bounds for # singleton coords (yet) ds_a["lat_bnds"] = xr.DataArray(name="lat_bnds", dims=["lat", "bnds"], data=[[-1, 1]]) ds_b = ds_a.copy() # 2. Regrid dataset b to a using regrid2, bilinear output_grid = ds_a.regridder.grid ds_b_regrid = ds_b.regridder.horizontal( "T", output_grid, tool="regrid2", method="bilinear" ) # ValueError: cannot reindex or align along dimension 'lat' because of conflicting dimension sizes: {1, 2} (note: an index is found along that dimension with size=1) # 3. Breaks because `_regrid` incorrectly reorders dimensions # Resulting in the `output_data` shape to become (lat=2, lev=1, lon=3). ˘ ``` ### Relevant log output ```python ValueError Traceback (most recent call last) File /global/u2/v/vo13/E3SM-Project/e3sm_diags/auxiliary_tools/cdat_regression_testing/657-meridional-mean-2d/657_meridional_mean_2d_run_script.py:19 16 ds_b = ds_a.copy() 18 output_grid = ds_a.regridder.grid ---> 19 ds_b_regrid = ds_b.regridder.horizontal( 20 "T", output_grid, tool="regrid2", method="bilinear" 21 ) File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xcdat/regridder/accessor.py:324, in RegridderAccessor.horizontal(self, data_var, output_grid, tool, **options) 322 input_grid = _get_input_grid(self._ds, data_var, ["X", "Y"]) 323 regridder = regrid_tool(input_grid, output_grid, **options) --> 324 output_ds = regridder.horizontal(data_var, self._ds) 326 return output_ds File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xcdat/regridder/regrid2.py:85, in Regrid2Regridder.horizontal(self, data_var, ds) 79 input_data_var = input_data_var.where(src_mask != 0.0, masked_value) 81 output_data = _regrid( 82 input_data_var, src_lat_bnds, src_lon_bnds, dst_lat_bnds, dst_lon_bnds 83 ) ---> 85 output_ds = _build_dataset( 86 ds, 87 data_var, 88 output_data, 89 dst_lat_bnds, 90 dst_lon_bnds, 91 self._input_grid, 92 self._output_grid, 93 ) 95 return output_ds File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xcdat/regridder/regrid2.py:206, in _build_dataset(ds, data_var, output_data, dst_lat_bnds, dst_lon_bnds, input_grid, output_grid) 199 output_data_vars[data_var] = output_da 201 output_ds = xr.Dataset( 202 output_data_vars, 203 attrs=input_grid.attrs.copy(), 204 ) --> 206 output_ds = _preserve_bounds(ds, output_grid, output_ds, ["X", "Y"]) 208 return output_ds File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xcdat/regridder/base.py:56, in _preserve_bounds(input_ds, output_grid, output_ds, drop_axis) 54 else: 55 if bnds.name not in output_ds: ---> 56 output_ds[bnds.name] = bnds.copy() 58 return output_ds File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xarray/core/dataset.py:1603, in Dataset.__setitem__(self, key, value) 1598 if isinstance(value, Dataset): 1599 raise TypeError( 1600 "Cannot assign a Dataset to a single key - only a DataArray or Variable " 1601 "object can be stored under a single key." 1602 ) -> 1603 self.update({key: value}) 1605 elif utils.iterable_of_hashable(key): 1606 keylist = list(key) File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xarray/core/dataset.py:5617, in Dataset.update(self, other) 5581 def update(self, other: CoercibleMapping) -> Self: 5582 """Update this dataset's variables with those from another dataset. 5583 5584 Just like :py:meth:`dict.update` this is a in-place operation. (...) 5615 Dataset.merge 5616 """ -> 5617 merge_result = dataset_update_method(self, other) 5618 return self._replace(inplace=True, **merge_result._asdict()) File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xarray/core/merge.py:1075, in dataset_update_method(dataset, other) 1072 if coord_names: 1073 other[key] = value.drop_vars(coord_names) -> 1075 return merge_core( 1076 [dataset, other], 1077 priority_arg=1, 1078 indexes=dataset.xindexes, 1079 combine_attrs="override", 1080 ) File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xarray/core/merge.py:711, in merge_core(objects, compat, join, combine_attrs, priority_arg, explicit_coords, indexes, fill_value, skip_align_args) 708 skip_align_objs = [(pos, objects.pop(pos)) for pos in skip_align_args] 710 coerced = coerce_pandas_values(objects) --> 711 aligned = deep_align( 712 coerced, join=join, copy=False, indexes=indexes, fill_value=fill_value 713 ) 715 for pos, obj in skip_align_objs: 716 aligned.insert(pos, obj) File /global/u2/v/vo13/mambaforge/envs/e3sm_diags_dev_nompi_659/lib/python3.10/site-packages/xarray/core/alignment.py:946, in deep_align(objects, join, copy, indexes, exclude, raise_on_invalid, fill_value) 943 else: 944 out.append(variables) --> 946 aligned = align( 947 *targets, 948 join=join, 949 copy=copy, 950 indexes=indexes, 951 exclude=exclude, ... 477 f"cannot reindex or align along dimension {dim!r} " 478 f"because of conflicting dimension sizes: {sizes!r}" + add_err_msg 479 ) ValueError: cannot reindex or align along dimension 'lat' because of conflicting dimension sizes: {1, 2} (note: an index is found along that dimension with size=1) ``` ### Anything else we need to know? _No response_ ### Environment Latest `main` xCDAT
xCDAT/xcdat
diff --git a/tests/test_regrid.py b/tests/test_regrid.py index c7253f4..d413cb0 100644 --- a/tests/test_regrid.py +++ b/tests/test_regrid.py @@ -372,6 +372,30 @@ class TestRegrid2Regridder: } ) + # source ordering is time, height, lat, lon + @pytest.mark.parametrize( + "ordering", + [ + ("time", "lat", "height", "lon"), + ("lat", "lon", "height", "time"), + ("lat", "height", "time", "lon"), + # no change in ordering + ("time", "height", "lat", "lon"), + ], + ) + def test_ordering(self, ordering): + ds = self.coarse_4d_ds + + output_grid = grid.create_gaussian_grid(4) + + ds["ts"] = ds.ts.transpose(*ordering) + + regridder = regrid2.Regrid2Regridder(ds, output_grid) + + output_ds = regridder.horizontal("ts", ds) + + assert ds.ts.dims == output_ds.ts.dims + def test_vertical_placeholder(self): ds = fixtures.generate_dataset( decode_times=True, cf_compliant=False, has_bounds=True
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.7
{ "env_vars": null, "env_yml_path": [ "conda-env/dev.yml" ], "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": true, "packages": "environment.yml", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
accessible-pygments @ file:///home/conda/feedstock_root/build_artifacts/accessible-pygments_1734956106558/work alabaster @ file:///home/conda/feedstock_root/build_artifacts/alabaster_1733750398730/work anyio @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_anyio_1742243108/work argon2-cffi @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi_1733311059102/work argon2-cffi-bindings @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi-bindings_1725356582126/work arrow @ file:///home/conda/feedstock_root/build_artifacts/arrow_1733584251875/work asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1733250440834/work async-lru @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_async-lru_1742153708/work attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1741918516150/work babel @ file:///home/conda/feedstock_root/build_artifacts/babel_1738490167835/work beautifulsoup4 @ file:///home/conda/feedstock_root/build_artifacts/beautifulsoup4_1738740337718/work black @ file:///home/conda/feedstock_root/build_artifacts/black-recipe_1682491947088/work bleach @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_bleach_1737382993/work bokeh @ file:///home/conda/feedstock_root/build_artifacts/bokeh_1741848529421/work Brotli @ file:///home/conda/feedstock_root/build_artifacts/brotli-split_1725267488082/work cached-property @ file:///home/conda/feedstock_root/build_artifacts/cached_property_1615209429212/work certifi @ file:///home/conda/feedstock_root/build_artifacts/certifi_1739515848642/work/certifi cf_xarray @ file:///home/conda/feedstock_root/build_artifacts/cf_xarray_1742393228644/work cffi @ file:///home/conda/feedstock_root/build_artifacts/cffi_1725560564262/work cfgv @ file:///home/conda/feedstock_root/build_artifacts/cfgv_1734267080977/work cftime @ file:///home/conda/feedstock_root/build_artifacts/cftime_1725400458727/work charset-normalizer @ file:///home/conda/feedstock_root/build_artifacts/charset-normalizer_1735929714516/work cli-ui @ file:///home/conda/feedstock_root/build_artifacts/cli-ui_1661937930158/work click @ file:///home/conda/feedstock_root/build_artifacts/click_1734858813237/work cloudpickle @ file:///home/conda/feedstock_root/build_artifacts/cloudpickle_1736947526808/work colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1733218098505/work comm @ file:///home/conda/feedstock_root/build_artifacts/comm_1733502965406/work contextlib2 @ file:///home/conda/feedstock_root/build_artifacts/contextlib2_1734475221200/work contourpy @ file:///home/conda/feedstock_root/build_artifacts/contourpy_1731428304374/work coverage @ file:///home/conda/feedstock_root/build_artifacts/coverage_1743381246335/work cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1733332471406/work cytoolz @ file:///home/conda/feedstock_root/build_artifacts/cytoolz_1734107202838/work dask @ file:///home/conda/feedstock_root/build_artifacts/dask-core_1742597902501/work debugpy @ file:///home/conda/feedstock_root/build_artifacts/debugpy_1741148385682/work decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1740384970518/work defusedxml @ file:///home/conda/feedstock_root/build_artifacts/defusedxml_1615232257335/work distlib @ file:///home/conda/feedstock_root/build_artifacts/distlib_1733238395481/work distributed @ file:///home/conda/feedstock_root/build_artifacts/distributed_1742601855521/work docopt @ file:///home/conda/feedstock_root/build_artifacts/docopt_1733817844261/work docutils @ file:///home/conda/feedstock_root/build_artifacts/docutils_1733217766141/work esmpy @ file:///home/conda/feedstock_root/build_artifacts/esmpy_1734359272810/work/src/addon/esmpy exceptiongroup @ file:///home/conda/feedstock_root/build_artifacts/exceptiongroup_1733208806608/work executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1733569351617/work fastjsonschema @ file:///home/conda/feedstock_root/build_artifacts/python-fastjsonschema_1733235979760/work/dist filelock @ file:///home/conda/feedstock_root/build_artifacts/filelock_1741969488311/work flake8 @ file:///home/conda/feedstock_root/build_artifacts/flake8_1669396691980/work flake8-isort @ file:///home/conda/feedstock_root/build_artifacts/flake8-isort_1671787420602/work fonttools @ file:///home/conda/feedstock_root/build_artifacts/fonttools_1738940303262/work fqdn @ file:///home/conda/feedstock_root/build_artifacts/fqdn_1733327382592/work/dist fsspec @ file:///home/conda/feedstock_root/build_artifacts/fsspec_1743361113926/work future @ file:///home/conda/feedstock_root/build_artifacts/future_1738926421307/work gsw @ file:///home/conda/feedstock_root/build_artifacts/gsw_1726897812010/work gsw-xarray @ file:///home/conda/feedstock_root/build_artifacts/gsw-xarray_1662892279205/work h11 @ file:///home/conda/feedstock_root/build_artifacts/h11_1733327467879/work h2 @ file:///home/conda/feedstock_root/build_artifacts/h2_1738578511449/work hpack @ file:///home/conda/feedstock_root/build_artifacts/hpack_1737618293087/work httpcore @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_httpcore_1731707562/work httpx @ file:///home/conda/feedstock_root/build_artifacts/httpx_1733663348460/work hyperframe @ file:///home/conda/feedstock_root/build_artifacts/hyperframe_1737618333194/work identify @ file:///home/conda/feedstock_root/build_artifacts/identify_1741502659866/work idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1733211830134/work imagesize @ file:///home/conda/feedstock_root/build_artifacts/imagesize_1656939531508/work importlib_metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1737420181517/work importlib_resources @ file:///home/conda/feedstock_root/build_artifacts/importlib_resources_1736252299705/work iniconfig @ file:///home/conda/feedstock_root/build_artifacts/iniconfig_1733223141826/work ipykernel @ file:///home/conda/feedstock_root/build_artifacts/ipykernel_1719845459717/work ipython @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_ipython_1741457126/work ipython_pygments_lexers @ file:///home/conda/feedstock_root/build_artifacts/ipython_pygments_lexers_1737123620466/work isoduration @ file:///home/conda/feedstock_root/build_artifacts/isoduration_1733493628631/work/dist isort @ file:///home/conda/feedstock_root/build_artifacts/isort_1675033873689/work jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1733300866624/work Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1741263328855/work json5 @ file:///home/conda/feedstock_root/build_artifacts/json5_1733272076743/work jsonpointer @ file:///home/conda/feedstock_root/build_artifacts/jsonpointer_1725302941992/work jsonschema @ file:///home/conda/feedstock_root/build_artifacts/jsonschema_1733472696581/work jsonschema-specifications @ file:///tmp/tmpk0f344m9/src jupyter-events @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_jupyter_events_1738765986/work jupyter-lsp @ file:///home/conda/feedstock_root/build_artifacts/jupyter-lsp-meta_1733492907176/work/jupyter-lsp jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1733440914442/work jupyter_core @ file:///home/conda/feedstock_root/build_artifacts/jupyter_core_1727163409502/work jupyter_server @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_1734702637701/work jupyter_server_terminals @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_terminals_1733427956852/work jupyterlab @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_1741964057182/work jupyterlab_pygments @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_pygments_1733328101776/work jupyterlab_server @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_server_1733599573484/work kiwisolver @ file:///home/conda/feedstock_root/build_artifacts/kiwisolver_1725459263097/work llvmlite==0.44.0 locket @ file:///home/conda/feedstock_root/build_artifacts/locket_1650660393415/work lz4 @ file:///home/conda/feedstock_root/build_artifacts/lz4_1733474243637/work MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1733219680183/work matplotlib==3.10.1 matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1733416936468/work mccabe @ file:///home/conda/feedstock_root/build_artifacts/mccabe_1733216466933/work mistune @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_mistune_1742402716/work msgpack @ file:///home/conda/feedstock_root/build_artifacts/msgpack-python_1725974992554/work munkres==1.1.4 mypy @ file:///home/conda/feedstock_root/build_artifacts/mypy-split_1687448130571/work mypy_extensions @ file:///home/conda/feedstock_root/build_artifacts/mypy_extensions_1733230897951/work narwhals @ file:///home/conda/feedstock_root/build_artifacts/narwhals_1742841036354/work nbclient @ file:///home/conda/feedstock_root/build_artifacts/nbclient_1734628800805/work nbconvert @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_nbconvert-core_1738067871/work nbformat @ file:///home/conda/feedstock_root/build_artifacts/nbformat_1733402752141/work nbsphinx @ file:///home/conda/feedstock_root/build_artifacts/nbsphinx_1741075436613/work nc-time-axis @ file:///home/conda/feedstock_root/build_artifacts/nc-time-axis_1734603295314/work nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1733325553580/work netCDF4 @ file:///home/conda/feedstock_root/build_artifacts/netcdf4_1733253093772/work nodeenv @ file:///home/conda/feedstock_root/build_artifacts/nodeenv_1734112117269/work notebook_shim @ file:///home/conda/feedstock_root/build_artifacts/notebook-shim_1733408315203/work numba @ file:///home/conda/feedstock_root/build_artifacts/numba_1739224689554/work numpy @ file:///home/conda/feedstock_root/build_artifacts/numpy_1730588022105/work/dist/numpy-2.1.3-cp311-cp311-linux_x86_64.whl#sha256=1f5924614bd9bbde9f19a84deaf511e80e6a1225443be24354a5ca153876529c overrides @ file:///home/conda/feedstock_root/build_artifacts/overrides_1734587627321/work packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1733203243479/work pandas @ file:///home/conda/feedstock_root/build_artifacts/pandas_1726878443020/work pandocfilters @ file:///home/conda/feedstock_root/build_artifacts/pandocfilters_1631603243851/work parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1733271261340/work partd @ file:///home/conda/feedstock_root/build_artifacts/partd_1715026491486/work pathspec @ file:///home/conda/feedstock_root/build_artifacts/pathspec_1733233363808/work pexpect @ file:///home/conda/feedstock_root/build_artifacts/pexpect_1733301927746/work pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1733327343728/work pillow @ file:///home/conda/feedstock_root/build_artifacts/pillow_1735929690690/work pkgutil_resolve_name @ file:///home/conda/feedstock_root/build_artifacts/pkgutil-resolve-name_1733344503739/work platformdirs @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_platformdirs_1742485085/work pluggy @ file:///home/conda/feedstock_root/build_artifacts/pluggy_1733222765875/work pre-commit @ file:///home/conda/feedstock_root/build_artifacts/pre-commit_1679105598521/work prometheus_client @ file:///home/conda/feedstock_root/build_artifacts/prometheus_client_1733327310477/work prompt_toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1737453357274/work psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1740663149797/work ptyprocess @ file:///home/conda/feedstock_root/build_artifacts/ptyprocess_1733302279685/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl#sha256=92c32ff62b5fd8cf325bec5ab90d7be3d2a8ca8c8a3813ff487a8d2002630d1f pure_eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1733569405015/work pyarrow==19.0.1 pycodestyle @ file:///home/conda/feedstock_root/build_artifacts/pycodestyle_1669306857274/work pycparser @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_pycparser_1733195786/work pydata-sphinx-theme==0.15.4 pyflakes @ file:///home/conda/feedstock_root/build_artifacts/pyflakes_1669319921641/work Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1736243443484/work pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1743089729650/work PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1733217236728/work pytest @ file:///home/conda/feedstock_root/build_artifacts/pytest_1740946542080/work pytest-cov @ file:///home/conda/feedstock_root/build_artifacts/pytest-cov_1733223023082/work python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1733215673016/work python-json-logger @ file:///home/conda/feedstock_root/build_artifacts/python-json-logger_1677079630776/work pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1706886791323/work PyYAML @ file:///home/conda/feedstock_root/build_artifacts/pyyaml_1737454647378/work pyzmq @ file:///home/conda/feedstock_root/build_artifacts/pyzmq_1741805139187/work referencing @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_referencing_1737836872/work requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1733217035951/work rfc3339_validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3339-validator_1733599910982/work rfc3986-validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3986-validator_1598024191506/work roman-numerals-py @ file:///home/conda/feedstock_root/build_artifacts/roman-numerals-py_1740240236123/work rpds-py @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rpds-py_1743037725/work schema @ file:///home/conda/feedstock_root/build_artifacts/schema_1714829163029/work scipy @ file:///home/conda/feedstock_root/build_artifacts/scipy-split_1739790648951/work/dist/scipy-1.15.2-cp311-cp311-linux_x86_64.whl#sha256=034f74dff07afe60a41ed832856d3d7e1ec1374d115cd88d525ace252f5b36fc Send2Trash @ file:///home/conda/feedstock_root/build_artifacts/send2trash_1733322040660/work shapely @ file:///home/conda/feedstock_root/build_artifacts/shapely_1741166964285/work six @ file:///home/conda/feedstock_root/build_artifacts/six_1733380938961/work sniffio @ file:///home/conda/feedstock_root/build_artifacts/sniffio_1733244044561/work snowballstemmer @ file:///home/conda/feedstock_root/build_artifacts/snowballstemmer_1637143057757/work sortedcontainers @ file:///home/conda/feedstock_root/build_artifacts/sortedcontainers_1738440353519/work soupsieve @ file:///home/conda/feedstock_root/build_artifacts/soupsieve_1693929250441/work sparse @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_sparse_1736951003/work Sphinx @ file:///home/conda/feedstock_root/build_artifacts/sphinx_1740956487887/work sphinx-autosummary-accessors @ file:///home/conda/feedstock_root/build_artifacts/sphinx-autosummary-accessors_1741707161000/work sphinx-book-theme==1.1.4 sphinx-copybutton @ file:///home/conda/feedstock_root/build_artifacts/sphinx-copybutton_1734572975006/work sphinx_design @ file:///home/conda/feedstock_root/build_artifacts/sphinx-design_1734614570224/work sphinxcontrib-applehelp @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-applehelp_1733754101641/work sphinxcontrib-devhelp @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-devhelp_1733754113405/work sphinxcontrib-htmlhelp @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-htmlhelp_1733754280555/work sphinxcontrib-jsmath @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-jsmath_1733753744933/work sphinxcontrib-qthelp @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-qthelp_1733753408017/work sphinxcontrib-serializinghtml @ file:///home/conda/feedstock_root/build_artifacts/sphinxcontrib-serializinghtml_1733750479108/work stack_data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1733569443808/work tabulate @ file:///home/conda/feedstock_root/build_artifacts/tabulate_1733589744265/work tblib @ file:///home/conda/feedstock_root/build_artifacts/tblib_1733842374544/work tbump @ file:///home/conda/feedstock_root/build_artifacts/tbump_1652622700247/work terminado @ file:///home/conda/feedstock_root/build_artifacts/terminado_1710262609923/work tinycss2 @ file:///home/conda/feedstock_root/build_artifacts/tinycss2_1729802851396/work toml @ file:///home/conda/feedstock_root/build_artifacts/toml_1734091811753/work tomli @ file:///home/conda/feedstock_root/build_artifacts/tomli_1733256695513/work tomlkit @ file:///home/conda/feedstock_root/build_artifacts/tomlkit_1733230743009/work toolz @ file:///home/conda/feedstock_root/build_artifacts/toolz_1733736030883/work tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1732615904614/work traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1733367359838/work types-python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/types-python-dateutil_1733612335562/work typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_typing_extensions_1743201626/work typing_utils @ file:///home/conda/feedstock_root/build_artifacts/typing_utils_1733331286120/work tzdata @ file:///home/conda/feedstock_root/build_artifacts/python-tzdata_1742745135198/work ukkonen @ file:///home/conda/feedstock_root/build_artifacts/ukkonen_1725784031690/work unicodedata2 @ file:///home/conda/feedstock_root/build_artifacts/unicodedata2_1736692517942/work Unidecode @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_unidecode_1733714839/work uri-template @ file:///home/conda/feedstock_root/build_artifacts/uri-template_1733323593477/work/dist urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1734859416348/work virtualenv @ file:///home/conda/feedstock_root/build_artifacts/virtualenv_1741337798015/work wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1733231326287/work webcolors @ file:///home/conda/feedstock_root/build_artifacts/webcolors_1733359735138/work webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1733236011802/work websocket-client @ file:///home/conda/feedstock_root/build_artifacts/websocket-client_1733157342724/work xarray @ file:///home/conda/feedstock_root/build_artifacts/xarray_1742448343846/work -e git+https://github.com/xCDAT/xcdat.git@77457577ebd358a86123049f78693e36719c8792#egg=xcdat xesmf @ file:///home/conda/feedstock_root/build_artifacts/xesmf_1733034062694/work xgcm @ file:///home/conda/feedstock_root/build_artifacts/xgcm_1733136171236/work xyzservices @ file:///home/conda/feedstock_root/build_artifacts/xyzservices_1737234886776/work zict @ file:///home/conda/feedstock_root/build_artifacts/zict_1733261551178/work zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1732827521216/work zstandard==0.23.0
name: xcdat channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - accessible-pygments=0.0.5=pyhd8ed1ab_1 - alabaster=1.0.0=pyhd8ed1ab_1 - anyio=4.9.0=pyh29332c3_0 - argon2-cffi=23.1.0=pyhd8ed1ab_1 - argon2-cffi-bindings=21.2.0=py311h9ecbd09_5 - arrow=1.3.0=pyhd8ed1ab_1 - asttokens=3.0.0=pyhd8ed1ab_1 - async-lru=2.0.5=pyh29332c3_0 - attrs=25.3.0=pyh71513ae_0 - aws-c-auth=0.8.6=hd08a7f5_4 - aws-c-cal=0.8.7=h043a21b_0 - aws-c-common=0.12.0=hb9d3cd8_0 - aws-c-compression=0.3.1=h3870646_2 - aws-c-event-stream=0.5.4=h04a3f94_2 - aws-c-http=0.9.4=hb9b18c6_4 - aws-c-io=0.17.0=h3dad3f2_6 - aws-c-mqtt=0.12.2=h108da3e_2 - aws-c-s3=0.7.13=h822ba82_2 - aws-c-sdkutils=0.2.3=h3870646_2 - aws-checksums=0.2.3=h3870646_2 - aws-crt-cpp=0.31.0=h55f77e1_4 - aws-sdk-cpp=1.11.510=h37a5c72_3 - azure-core-cpp=1.14.0=h5cfcd09_0 - azure-identity-cpp=1.10.0=h113e628_0 - azure-storage-blobs-cpp=12.13.0=h3cf044e_1 - azure-storage-common-cpp=12.8.0=h736e048_1 - azure-storage-files-datalake-cpp=12.12.0=ha633028_1 - babel=2.17.0=pyhd8ed1ab_0 - beautifulsoup4=4.13.3=pyha770c72_0 - black=23.3.0=py311h38be061_1 - bleach=6.2.0=pyh29332c3_4 - bleach-with-css=6.2.0=h82add2a_4 - blosc=1.21.6=he440d0b_1 - bokeh=3.7.0=pyhd8ed1ab_0 - brotli=1.1.0=hb9d3cd8_2 - brotli-bin=1.1.0=hb9d3cd8_2 - brotli-python=1.1.0=py311hfdbb021_2 - bzip2=1.0.8=h4bc722e_7 - c-ares=1.34.4=hb9d3cd8_0 - ca-certificates=2025.2.25=h06a4308_0 - cached-property=1.5.2=hd8ed1ab_1 - cached_property=1.5.2=pyha770c72_1 - certifi=2025.1.31=pyhd8ed1ab_0 - cf_xarray=0.10.4=pyhd8ed1ab_0 - cffi=1.17.1=py311hf29c0ef_0 - cfgv=3.3.1=pyhd8ed1ab_1 - cftime=1.6.4=py311h9f3472d_1 - charset-normalizer=3.4.1=pyhd8ed1ab_0 - cli-ui=0.17.2=pyhd8ed1ab_0 - click=8.1.8=pyh707e725_0 - cloudpickle=3.1.1=pyhd8ed1ab_0 - colorama=0.4.6=pyhd8ed1ab_1 - comm=0.2.2=pyhd8ed1ab_1 - contextlib2=21.6.0=pyhd8ed1ab_1 - contourpy=1.3.1=py311hd18a35c_0 - coverage=7.8.0=py311h2dc5d0c_0 - cycler=0.12.1=pyhd8ed1ab_1 - cytoolz=1.0.1=py311h9ecbd09_0 - dask=2025.3.0=pyhd8ed1ab_0 - dask-core=2025.3.0=pyhd8ed1ab_0 - debugpy=1.8.13=py311hfdbb021_0 - decorator=5.2.1=pyhd8ed1ab_0 - defusedxml=0.7.1=pyhd8ed1ab_0 - distlib=0.3.9=pyhd8ed1ab_1 - distributed=2025.3.0=pyhd8ed1ab_0 - docopt=0.6.2=pyhd8ed1ab_2 - docutils=0.21.2=pyhd8ed1ab_1 - esmf=8.7.0=nompi_h6063b07_1 - esmpy=8.7.0=pyhecae5ae_1 - exceptiongroup=1.2.2=pyhd8ed1ab_1 - executing=2.1.0=pyhd8ed1ab_1 - filelock=3.18.0=pyhd8ed1ab_0 - flake8=6.0.0=pyhd8ed1ab_0 - flake8-isort=6.0.0=pyhd8ed1ab_0 - fonttools=4.56.0=py311h2dc5d0c_0 - fqdn=1.5.1=pyhd8ed1ab_1 - freetype=2.13.3=h48d6fc4_0 - fsspec=2025.3.1=pyhd8ed1ab_0 - future=1.0.0=pyhd8ed1ab_2 - geos=3.13.1=h97f6797_0 - gflags=2.2.2=h5888daf_1005 - glog=0.7.1=hbabe93e_0 - gsw=3.6.19=py311h9f3472d_1 - gsw-xarray=0.3.0=pyhd8ed1ab_0 - h11=0.14.0=pyhd8ed1ab_1 - h2=4.2.0=pyhd8ed1ab_0 - hdf4=4.2.15=h2a13503_7 - hdf5=1.14.4=nompi_h2d575fe_105 - hpack=4.1.0=pyhd8ed1ab_0 - httpcore=1.0.7=pyh29332c3_1 - httpx=0.28.1=pyhd8ed1ab_0 - hyperframe=6.1.0=pyhd8ed1ab_0 - identify=2.6.9=pyhd8ed1ab_0 - idna=3.10=pyhd8ed1ab_1 - imagesize=1.4.1=pyhd8ed1ab_0 - importlib-metadata=8.6.1=pyha770c72_0 - importlib_resources=6.5.2=pyhd8ed1ab_0 - iniconfig=2.0.0=pyhd8ed1ab_1 - ipykernel=6.29.5=pyh3099207_0 - ipython=9.0.2=pyhfb0248b_0 - ipython_pygments_lexers=1.1.1=pyhd8ed1ab_0 - isoduration=20.11.0=pyhd8ed1ab_1 - isort=5.12.0=pyhd8ed1ab_1 - jedi=0.19.2=pyhd8ed1ab_1 - jinja2=3.1.6=pyhd8ed1ab_0 - json5=0.10.0=pyhd8ed1ab_1 - jsonpointer=3.0.0=py311h38be061_1 - jsonschema=4.23.0=pyhd8ed1ab_1 - jsonschema-specifications=2024.10.1=pyhd8ed1ab_1 - jsonschema-with-format-nongpl=4.23.0=hd8ed1ab_1 - jupyter-lsp=2.2.5=pyhd8ed1ab_1 - jupyter_client=8.6.3=pyhd8ed1ab_1 - jupyter_core=5.7.2=pyh31011fe_1 - jupyter_events=0.12.0=pyh29332c3_0 - jupyter_server=2.15.0=pyhd8ed1ab_0 - jupyter_server_terminals=0.5.3=pyhd8ed1ab_1 - jupyterlab=4.3.6=pyhd8ed1ab_0 - jupyterlab_pygments=0.3.0=pyhd8ed1ab_2 - jupyterlab_server=2.27.3=pyhd8ed1ab_1 - keyutils=1.6.1=h166bdaf_0 - kiwisolver=1.4.7=py311hd18a35c_0 - krb5=1.21.3=h659f571_0 - lcms2=2.17=h717163a_0 - ld_impl_linux-64=2.40=h12ee557_0 - lerc=4.0.0=h27087fc_0 - libabseil=20250127.1=cxx17_hbbce691_0 - libaec=1.1.3=h59595ed_0 - libarrow=19.0.1=h120c447_5_cpu - libarrow-acero=19.0.1=hcb10f89_5_cpu - libarrow-dataset=19.0.1=hcb10f89_5_cpu - libarrow-substrait=19.0.1=h1bed206_5_cpu - libblas=3.9.0=31_h59b9bed_openblas - libbrotlicommon=1.1.0=hb9d3cd8_2 - libbrotlidec=1.1.0=hb9d3cd8_2 - libbrotlienc=1.1.0=hb9d3cd8_2 - libcblas=3.9.0=31_he106b2a_openblas - libcrc32c=1.1.2=h9c3ff4c_0 - libcurl=8.12.1=h332b0f4_0 - libdeflate=1.23=h4ddbbb0_0 - libedit=3.1.20250104=pl5321h7949ede_0 - libev=4.33=hd590300_2 - libevent=2.1.12=hf998b51_1 - libexpat=2.6.4=h5888daf_0 - libffi=3.4.4=h6a678d5_1 - libgcc=14.2.0=h767d61c_2 - libgcc-ng=14.2.0=h69a702a_2 - libgfortran=14.2.0=h69a702a_2 - libgfortran5=14.2.0=hf1ad2bd_2 - libgomp=14.2.0=h767d61c_2 - libgoogle-cloud=2.36.0=hc4361e1_1 - libgoogle-cloud-storage=2.36.0=h0121fbd_1 - libgrpc=1.71.0=he753a82_0 - libiconv=1.18=h4ce23a2_1 - libjpeg-turbo=3.0.0=hd590300_1 - liblapack=3.9.0=31_h7ac8fdf_openblas - liblzma=5.6.4=hb9d3cd8_0 - libnetcdf=4.9.2=nompi_h5ddbaa4_116 - libnghttp2=1.64.0=h161d5f1_0 - libnsl=2.0.1=hd590300_0 - libopenblas=0.3.29=pthreads_h94d23a6_0 - libopentelemetry-cpp=1.19.0=hd1b1c89_0 - libopentelemetry-cpp-headers=1.19.0=ha770c72_0 - libparquet=19.0.1=h081d1f1_5_cpu - libpng=1.6.47=h943b412_0 - libprotobuf=5.29.3=h501fc15_0 - libre2-11=2024.07.02=hba17884_3 - libsodium=1.0.20=h4ab18f5_0 - libsqlite=3.49.1=hee588c1_2 - libssh2=1.11.1=hf672d98_0 - libstdcxx=14.2.0=h8f9b012_2 - libstdcxx-ng=14.2.0=h4852527_2 - libthrift=0.21.0=h0e7cc3e_0 - libtiff=4.7.0=hd9ff511_3 - libutf8proc=2.10.0=h4c51ac1_0 - libuuid=2.38.1=h0b41bf4_0 - libwebp-base=1.5.0=h851e524_0 - libxcb=1.17.0=h8a09558_0 - libxcrypt=4.4.36=hd590300_1 - libxml2=2.13.7=h0d44e9d_0 - libzip=1.11.2=h6991a6a_0 - libzlib=1.3.1=hb9d3cd8_2 - llvmlite=0.44.0=py311h9c9ff8c_1 - locket=1.0.0=pyhd8ed1ab_0 - lz4=4.3.3=py311h8c6ae76_2 - lz4-c=1.10.0=h5888daf_1 - markupsafe=3.0.2=py311h2dc5d0c_1 - matplotlib-base=3.10.1=py311h2b939e6_0 - matplotlib-inline=0.1.7=pyhd8ed1ab_1 - mccabe=0.7.0=pyhd8ed1ab_1 - mistune=3.1.3=pyh29332c3_0 - msgpack-python=1.1.0=py311hd18a35c_0 - munkres=1.1.4=pyh9f0ad1d_0 - mypy=1.4.0=py311h459d7ec_0 - mypy_extensions=1.0.0=pyha770c72_1 - narwhals=1.32.0=pyhd8ed1ab_0 - nbclient=0.10.2=pyhd8ed1ab_0 - nbconvert=7.16.6=hb482800_0 - nbconvert-core=7.16.6=pyh29332c3_0 - nbconvert-pandoc=7.16.6=hed9df3c_0 - nbformat=5.10.4=pyhd8ed1ab_1 - nbsphinx=0.9.7=pyhd8ed1ab_0 - nc-time-axis=1.4.1=pyhd8ed1ab_1 - ncurses=6.5=h2d0b736_3 - nest-asyncio=1.6.0=pyhd8ed1ab_1 - netcdf-fortran=4.6.1=nompi_ha5d1325_108 - netcdf4=1.7.2=nompi_py311h7c29e4f_101 - nlohmann_json=3.11.3=he02047a_1 - nodeenv=1.9.1=pyhd8ed1ab_1 - notebook-shim=0.2.4=pyhd8ed1ab_1 - numba=0.61.0=py311h4e1c48f_1 - numpy=2.1.3=py311h71ddf71_0 - openjpeg=2.5.3=h5fbd93e_0 - openssl=3.4.1=h7b32b05_0 - orc=2.1.1=h17f744e_1 - overrides=7.7.0=pyhd8ed1ab_1 - packaging=24.2=pyhd8ed1ab_2 - pandas=2.2.3=py311h7db5c69_1 - pandoc=3.6.4=ha770c72_0 - pandocfilters=1.5.0=pyhd8ed1ab_0 - parso=0.8.4=pyhd8ed1ab_1 - partd=1.4.2=pyhd8ed1ab_0 - pathspec=0.12.1=pyhd8ed1ab_1 - pexpect=4.9.0=pyhd8ed1ab_1 - pickleshare=0.7.5=pyhd8ed1ab_1004 - pillow=11.1.0=py311h1322bbf_0 - pip=25.0.1=pyh8b19718_0 - pkgutil-resolve-name=1.3.10=pyhd8ed1ab_2 - platformdirs=4.3.7=pyh29332c3_0 - pluggy=1.5.0=pyhd8ed1ab_1 - pre-commit=3.2.0=pyha770c72_0 - prometheus-cpp=1.3.0=ha5d0236_0 - prometheus_client=0.21.1=pyhd8ed1ab_0 - prompt-toolkit=3.0.50=pyha770c72_0 - psutil=7.0.0=py311h9ecbd09_0 - pthread-stubs=0.4=hb9d3cd8_1002 - ptyprocess=0.7.0=pyhd8ed1ab_1 - pure_eval=0.2.3=pyhd8ed1ab_1 - pyarrow=19.0.1=py311h38be061_0 - pyarrow-core=19.0.1=py311h4854187_0_cpu - pycodestyle=2.10.0=pyhd8ed1ab_0 - pycparser=2.22=pyh29332c3_1 - pydata-sphinx-theme=0.15.4=pyhd8ed1ab_0 - pyflakes=3.0.1=pyhd8ed1ab_0 - pygments=2.19.1=pyhd8ed1ab_0 - pyparsing=3.2.3=pyhd8ed1ab_1 - pysocks=1.7.1=pyha55dd90_7 - pytest=8.3.5=pyhd8ed1ab_0 - pytest-cov=6.0.0=pyhd8ed1ab_1 - python=3.11.11=h9e4cc4f_2_cpython - python-dateutil=2.9.0.post0=pyhff2d567_1 - python-fastjsonschema=2.21.1=pyhd8ed1ab_0 - python-json-logger=2.0.7=pyhd8ed1ab_0 - python-tzdata=2025.2=pyhd8ed1ab_0 - python_abi=3.11=5_cp311 - pytz=2024.1=pyhd8ed1ab_0 - pyyaml=6.0.2=py311h2dc5d0c_2 - pyzmq=26.3.0=py311h7deb3e3_0 - qhull=2020.2=h434a139_5 - re2=2024.07.02=h9925aae_3 - readline=8.2=h5eee18b_0 - referencing=0.36.2=pyh29332c3_0 - requests=2.32.3=pyhd8ed1ab_1 - rfc3339-validator=0.1.4=pyhd8ed1ab_1 - rfc3986-validator=0.1.1=pyh9f0ad1d_0 - roman-numerals-py=3.1.0=pyhd8ed1ab_0 - rpds-py=0.24.0=py311h687327b_0 - s2n=1.5.14=h6c98b2b_0 - schema=0.7.7=pyhd8ed1ab_0 - scipy=1.15.2=py311h8f841c2_0 - send2trash=1.8.3=pyh0d859eb_1 - setuptools=75.8.2=pyhff2d567_0 - shapely=2.0.7=py311h3dc67b8_1 - six=1.17.0=pyhd8ed1ab_0 - snappy=1.2.1=h8bd8927_1 - sniffio=1.3.1=pyhd8ed1ab_1 - snowballstemmer=2.2.0=pyhd8ed1ab_0 - sortedcontainers=2.4.0=pyhd8ed1ab_1 - soupsieve=2.5=pyhd8ed1ab_1 - sparse=0.15.5=pyh72ffeb9_0 - sphinx=8.2.3=pyhd8ed1ab_0 - sphinx-autosummary-accessors=2025.3.1=pyhd8ed1ab_0 - sphinx-book-theme=1.1.4=pyh29332c3_0 - sphinx-copybutton=0.5.2=pyhd8ed1ab_1 - sphinx-design=0.6.1=pyhd8ed1ab_2 - sphinxcontrib-applehelp=2.0.0=pyhd8ed1ab_1 - sphinxcontrib-devhelp=2.0.0=pyhd8ed1ab_1 - sphinxcontrib-htmlhelp=2.1.0=pyhd8ed1ab_1 - sphinxcontrib-jsmath=1.0.1=pyhd8ed1ab_1 - sphinxcontrib-qthelp=2.0.0=pyhd8ed1ab_1 - sphinxcontrib-serializinghtml=1.1.10=pyhd8ed1ab_1 - sqlite=3.49.1=h9eae976_2 - stack_data=0.6.3=pyhd8ed1ab_1 - tabulate=0.9.0=pyhd8ed1ab_2 - tblib=3.0.0=pyhd8ed1ab_1 - tbump=6.9.0=pyhd8ed1ab_0 - terminado=0.18.1=pyh0d859eb_0 - tinycss2=1.4.0=pyhd8ed1ab_0 - tk=8.6.13=noxft_h4845f30_101 - toml=0.10.2=pyhd8ed1ab_1 - tomli=2.2.1=pyhd8ed1ab_1 - tomlkit=0.13.2=pyha770c72_1 - toolz=1.0.0=pyhd8ed1ab_1 - tornado=6.4.2=py311h9ecbd09_0 - traitlets=5.14.3=pyhd8ed1ab_1 - types-python-dateutil=2.9.0.20241206=pyhd8ed1ab_0 - typing-extensions=4.13.0=h9fa5a19_1 - typing_extensions=4.13.0=pyh29332c3_1 - typing_utils=0.1.0=pyhd8ed1ab_1 - tzdata=2025a=h04d1e81_0 - ukkonen=1.0.1=py311hd18a35c_5 - unicodedata2=16.0.0=py311h9ecbd09_0 - unidecode=1.3.8=pyh29332c3_1 - uri-template=1.3.0=pyhd8ed1ab_1 - urllib3=2.3.0=pyhd8ed1ab_0 - virtualenv=20.29.3=pyhd8ed1ab_0 - wcwidth=0.2.13=pyhd8ed1ab_1 - webcolors=24.11.1=pyhd8ed1ab_0 - webencodings=0.5.1=pyhd8ed1ab_3 - websocket-client=1.8.0=pyhd8ed1ab_1 - wheel=0.45.1=pyhd8ed1ab_1 - xarray=2025.3.0=pyhd8ed1ab_0 - xesmf=0.8.8=pyhd8ed1ab_1 - xgcm=0.8.1=pyhd8ed1ab_1 - xorg-libxau=1.0.12=hb9d3cd8_0 - xorg-libxdmcp=1.1.5=hb9d3cd8_0 - xyzservices=2025.1.0=pyhd8ed1ab_0 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7f98852_2 - zeromq=4.3.5=h3b0a872_7 - zict=3.0.0=pyhd8ed1ab_1 - zipp=3.21.0=pyhd8ed1ab_1 - zlib=1.3.1=hb9d3cd8_2 - zstandard=0.23.0=py311h9ecbd09_1 - zstd=1.5.7=hb8e6e7a_2 - pip: - xcdat==0.7.0 prefix: /opt/conda/envs/xcdat
[ "tests/test_regrid.py::TestRegrid2Regridder::test_ordering[ordering0]", "tests/test_regrid.py::TestRegrid2Regridder::test_ordering[ordering1]", "tests/test_regrid.py::TestRegrid2Regridder::test_ordering[ordering2]" ]
[]
[ "tests/test_regrid.py::TestXGCMRegridder::test_multiple_z_axes", "tests/test_regrid.py::TestXGCMRegridder::test_vertical_regrid_level_name_mismatch", "tests/test_regrid.py::TestXGCMRegridder::test_vertical_regrid", "tests/test_regrid.py::TestXGCMRegridder::test_target_data", "tests/test_regrid.py::TestXGCMRegridder::test_target_data_da", "tests/test_regrid.py::TestXGCMRegridder::test_target_data_ds", "tests/test_regrid.py::TestXGCMRegridder::test_target_data_error", "tests/test_regrid.py::TestXGCMRegridder::test_conservative", "tests/test_regrid.py::TestXGCMRegridder::test_grid_positions[left]", "tests/test_regrid.py::TestXGCMRegridder::test_grid_positions[center]", "tests/test_regrid.py::TestXGCMRegridder::test_grid_positions[right]", "tests/test_regrid.py::TestXGCMRegridder::test_grid_positions_malformed", "tests/test_regrid.py::TestXGCMRegridder::test_manual_grid_positions", "tests/test_regrid.py::TestXGCMRegridder::test_horizontal_placeholder", "tests/test_regrid.py::TestXGCMRegridder::test_methods", "tests/test_regrid.py::TestXGCMRegridder::test_missing_input_z_coord", "tests/test_regrid.py::TestXGCMRegridder::test_missing_output_z_coord", "tests/test_regrid.py::TestXGCMRegridder::test_missing_input_z_bounds", "tests/test_regrid.py::TestRegrid2Regridder::test_ordering[ordering3]", "tests/test_regrid.py::TestRegrid2Regridder::test_vertical_placeholder", "tests/test_regrid.py::TestRegrid2Regridder::test_output_bounds", "tests/test_regrid.py::TestRegrid2Regridder::test_output_bounds_missing_temporal", "tests/test_regrid.py::TestRegrid2Regridder::test_align_axis[src0-dst0-expected_west0-expected_east0-0]", "tests/test_regrid.py::TestRegrid2Regridder::test_align_axis[src1-dst1-expected_west1-expected_east1-1]", "tests/test_regrid.py::TestRegrid2Regridder::test_align_axis[src2-dst2-expected_west2-expected_east2-0]", "tests/test_regrid.py::TestRegrid2Regridder::test_align_axis[src3-dst3-expected_west3-expected_east3-0]", "tests/test_regrid.py::TestRegrid2Regridder::test_align_axis[src4-dst4-expected_west4-expected_east4-1]", "tests/test_regrid.py::TestRegrid2Regridder::test_align_axis[src5-dst5-expected_west5-expected_east5-0]", "tests/test_regrid.py::TestRegrid2Regridder::test_align_axis[src6-dst6-expected_west6-expected_east6-0]", "tests/test_regrid.py::TestRegrid2Regridder::test_unknown_variable", "tests/test_regrid.py::TestRegrid2Regridder::test_regrid_input_mask", "tests/test_regrid.py::TestRegrid2Regridder::test_regrid_input_mask_unmapped_to_nan", "tests/test_regrid.py::TestRegrid2Regridder::test_preserve_attrs", "tests/test_regrid.py::TestRegrid2Regridder::test_regrid_2d", "tests/test_regrid.py::TestRegrid2Regridder::test_regrid_fine_coarse_2d", "tests/test_regrid.py::TestRegrid2Regridder::test_regrid_3d", "tests/test_regrid.py::TestRegrid2Regridder::test_regrid_4d", "tests/test_regrid.py::TestRegrid2Regridder::test_map_longitude_coarse_to_fine", "tests/test_regrid.py::TestRegrid2Regridder::test_map_longitude_fine_to_coarse", "tests/test_regrid.py::TestRegrid2Regridder::test_map_latitude_coarse_to_fine", "tests/test_regrid.py::TestRegrid2Regridder::test_map_latitude_fine_to_coarse", "tests/test_regrid.py::TestRegrid2Regridder::test_extract_bounds", "tests/test_regrid.py::TestRegrid2Regridder::test_reversed_extract_bounds", "tests/test_regrid.py::TestRegrid2Regridder::test_get_bounds_ensure_dtype", "tests/test_regrid.py::TestXESMFRegridder::test_vertical_placeholder", "tests/test_regrid.py::TestXESMFRegridder::test_regrid", "tests/test_regrid.py::TestXESMFRegridder::test_flags[periodic-True-_periodic]", "tests/test_regrid.py::TestXESMFRegridder::test_flags[extrap_method-inverse_dist-_extrap_method]", "tests/test_regrid.py::TestXESMFRegridder::test_flags[extrap_method-nearest_s2d-_extrap_method]", "tests/test_regrid.py::TestXESMFRegridder::test_flags[extrap_dist_exponent-0.1-_extrap_dist_exponent]", "tests/test_regrid.py::TestXESMFRegridder::test_flags[extrap_num_src_pnts-10-_extrap_num_src_pnts]", "tests/test_regrid.py::TestXESMFRegridder::test_flags[ignore_degenerate-False-_ignore_degenerate]", "tests/test_regrid.py::TestXESMFRegridder::test_no_variable", "tests/test_regrid.py::TestXESMFRegridder::test_invalid_method", "tests/test_regrid.py::TestXESMFRegridder::test_invalid_extra_method", "tests/test_regrid.py::TestXESMFRegridder::test_preserve_bounds", "tests/test_regrid.py::TestGrid::test_create_axis", "tests/test_regrid.py::TestGrid::test_create_axis_user_attrs", "tests/test_regrid.py::TestGrid::test_create_axis_from_list", "tests/test_regrid.py::TestGrid::test_create_axis_no_bnds", "tests/test_regrid.py::TestGrid::test_create_axis_user_bnds", "tests/test_regrid.py::TestGrid::test_create_axis_invalid_name", "tests/test_regrid.py::TestGrid::test_empty_grid", "tests/test_regrid.py::TestGrid::test_create_grid_with_coords", "tests/test_regrid.py::TestGrid::test_create_grid_with_tuple_of_coords_and_no_bounds", "tests/test_regrid.py::TestGrid::test_create_grid_with_tuple_of_coords_and_bounds", "tests/test_regrid.py::TestGrid::test_create_grid_user_attrs", "tests/test_regrid.py::TestGrid::test_create_grid_wrong_axis_value", "tests/test_regrid.py::TestGrid::test_uniform_grid", "tests/test_regrid.py::TestGrid::test_gaussian_grid", "tests/test_regrid.py::TestGrid::test_global_mean_grid", "tests/test_regrid.py::TestGrid::test_raises_error_for_global_mean_grid_if_an_axis_has_multiple_dimensions", "tests/test_regrid.py::TestGrid::test_zonal_grid", "tests/test_regrid.py::TestGrid::test_raises_error_for_zonal_grid_if_an_axis_has_multiple_dimensions", "tests/test_regrid.py::TestAccessor::test_preserve_mask_from_input", "tests/test_regrid.py::TestAccessor::test_horizontal", "tests/test_regrid.py::TestAccessor::test_vertical", "tests/test_regrid.py::TestAccessor::test_vertical_multiple_z_axes", "tests/test_regrid.py::TestAccessor::test_grid", "tests/test_regrid.py::TestAccessor::test_grid_raises_error_when_dataset_has_multiple_dims_for_an_axis", "tests/test_regrid.py::TestAccessor::test_horizontal_tool_check", "tests/test_regrid.py::TestAccessor::test_vertical_tool_check", "tests/test_regrid.py::TestBase::test_preserve_bounds", "tests/test_regrid.py::TestBase::test_preserve_bounds_does_not_drop_axis_if_axis_does_not_exist", "tests/test_regrid.py::TestBase::test_regridder_implementation" ]
[]
Apache License 2.0
18,394
295
[ "xcdat/regridder/regrid2.py" ]
narwhals-dev__narwhals-143
b22fc47f6ca376fa0ae9115800fa9b8ddfdbe99b
2024-05-11 20:12:52
2a3693b8bbbb02bc65d69603a0e4589ab9de026f
diff --git a/narwhals/_pandas_like/series.py b/narwhals/_pandas_like/series.py index 854ba161..897e7ffc 100644 --- a/narwhals/_pandas_like/series.py +++ b/narwhals/_pandas_like/series.py @@ -346,7 +346,7 @@ class PandasSeries: def n_unique(self) -> int: ser = self._series - return ser.nunique() # type: ignore[no-any-return] + return ser.nunique(dropna=False) # type: ignore[no-any-return] def sample( self,
`n_unique`: pandas skips nulls, polars counts we may need some additional logic under the hood to align them here: ```python In [30]: pl.Series([1., None, None, 2.]).n_unique() Out[30]: 3 In [31]: pd.Series([1., None, None, 2.]).nunique() Out[31]: 2 ```
narwhals-dev/narwhals
diff --git a/tests/expr/n_unique_test.py b/tests/expr/n_unique_test.py new file mode 100644 index 00000000..5a9f7ff2 --- /dev/null +++ b/tests/expr/n_unique_test.py @@ -0,0 +1,27 @@ +from typing import Any + +import pandas as pd +import polars as pl +import pytest + +import narwhals as nw +from tests.utils import compare_dicts + +data = { + "a": [1.0, None, None, 3.0], + "b": [1.0, None, 4, 5.0], +} + + [email protected]("constructor", [pd.DataFrame, pl.DataFrame]) +def test_over_single(constructor: Any) -> None: + df = nw.from_native(constructor(data), eager_only=True) + result = df.select(nw.all().n_unique()) + expected = { + "a": [3], + "b": [4], + } + compare_dicts(result, expected) + assert df["a"].n_unique() == 3 + assert df["b"].n_unique() == 4 + compare_dicts(result, expected)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 cfgv==3.4.0 covdefaults==2.3.0 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 filelock==3.18.0 hypothesis==6.130.5 identify==2.6.9 iniconfig==2.1.0 -e git+https://github.com/narwhals-dev/narwhals.git@b22fc47f6ca376fa0ae9115800fa9b8ddfdbe99b#egg=narwhals nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 platformdirs==4.3.7 pluggy==1.5.0 polars==1.26.0 pre_commit==4.2.0 pyarrow==19.0.1 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 six==1.17.0 sortedcontainers==2.4.0 tomli==2.2.1 tzdata==2025.2 virtualenv==20.29.3
name: narwhals channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - cfgv==3.4.0 - covdefaults==2.3.0 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - filelock==3.18.0 - hypothesis==6.130.5 - identify==2.6.9 - iniconfig==2.1.0 - narwhals==0.8.10 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - platformdirs==4.3.7 - pluggy==1.5.0 - polars==1.26.0 - pre-commit==4.2.0 - pyarrow==19.0.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - six==1.17.0 - sortedcontainers==2.4.0 - tomli==2.2.1 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/narwhals
[ "tests/expr/n_unique_test.py::test_over_single[DataFrame0]" ]
[]
[ "tests/expr/n_unique_test.py::test_over_single[DataFrame1]" ]
[]
MIT License
18,406
161
[ "narwhals/_pandas_like/series.py" ]
conan-io__conan-16243
cab4f18453af93582d42b5f001f768df0cfe3058
2024-05-13 10:26:24
a3d2fbcefe1cbdff55efb085d7c177c3d1e32dc8
diff --git a/conan/internal/api/detect_api.py b/conan/internal/api/detect_api.py index 5f2eabebd..e90894b29 100644 --- a/conan/internal/api/detect_api.py +++ b/conan/internal/api/detect_api.py @@ -384,9 +384,14 @@ def detect_default_compiler(): return None, None, None if platform.system() == "Windows": - compiler, version, compiler_exe = detect_msvc_compiler() - if compiler: - return compiler, version, compiler_exe + ide_version = _detect_vs_ide_version() + version = {"17": "193", "16": "192", "15": "191"}.get(str(ide_version)) # Map to compiler + if ide_version == "17": + update = detect_msvc_update(version) # FIXME weird passing here the 193 compiler version + if update and int(update) >= 10: + version = "194" + if version: + return 'msvc', Version(version), None if platform.system() == "SunOS": sun_cc, sun_cc_version, compiler_exe = detect_suncc_compiler() @@ -409,7 +414,7 @@ def detect_default_compiler(): def default_msvc_ide_version(version): - version = {"193": "17", "192": "16", "191": "15"}.get(str(version)) + version = {"194": "17", "193": "17", "192": "16", "191": "15"}.get(str(version)) if version: return Version(version) diff --git a/conan/internal/runner/docker.py b/conan/internal/runner/docker.py index ebc6374e3..77aabaf0a 100644 --- a/conan/internal/runner/docker.py +++ b/conan/internal/runner/docker.py @@ -90,7 +90,7 @@ class DockerRunner: profile_list = set(self.args.profile_build + self.args.profile_host) else: profile_list = self.args.profile_host or self.args.profile_build - + # Update the profile paths for i, raw_arg in enumerate(raw_args): for i, raw_profile in enumerate(profile_list): @@ -111,7 +111,7 @@ class DockerRunner: if not (self.dockerfile or self.image): raise ConanException("'dockerfile' or docker image name is needed") self.image = self.image or 'conan-runner-default' - self.name = self.configfile.image or f'conan-runner-{host_profile.runner.get("suffix", "docker")}' + self.name = self.configfile.run.name or f'conan-runner-{host_profile.runner.get("suffix", "docker")}' self.remove = str(host_profile.runner.get('remove', 'false')).lower() == 'true' self.cache = str(host_profile.runner.get('cache', 'clean')) self.container = None diff --git a/conan/tools/microsoft/visual.py b/conan/tools/microsoft/visual.py index 8c929e979..1632e3b95 100644 --- a/conan/tools/microsoft/visual.py +++ b/conan/tools/microsoft/visual.py @@ -59,7 +59,8 @@ def msvc_version_to_vs_ide_version(version): '190': '14', '191': '15', '192': '16', - '193': '17'} + '193': '17', + '194': '17'} # Note both 193 and 194 belong to VS 17 2022 return _visuals[str(version)] @@ -75,7 +76,8 @@ def msvc_version_to_toolset_version(version): '190': 'v140', '191': 'v141', '192': 'v142', - "193": 'v143'} + "193": 'v143', + "194": 'v143'} return toolsets.get(str(version)) @@ -140,6 +142,7 @@ class VCVars: compiler_update = conanfile.settings.get_safe("compiler.update", "") # The equivalent of compiler 19.26 is toolset 14.26 vcvars_ver = "14.{}{}".format(compiler_version[-1], compiler_update) + vcvarsarch = _vcvars_arch(conanfile) winsdk_version = conanfile.conf.get("tools.microsoft:winsdk_version", check_type=str) diff --git a/conans/client/conf/__init__.py b/conans/client/conf/__init__.py index 15836051d..129ceb76f 100644 --- a/conans/client/conf/__init__.py +++ b/conans/client/conf/__init__.py @@ -94,14 +94,14 @@ compiler: "10", "10.1", "10.2", "10.3", "10.4", "10.5", "11", "11.1", "11.2", "11.3", "11.4", "12", "12.1", "12.2", "12.3", - "13", "13.1", "13.2", + "13", "13.1", "13.2", "14", "14.1"] libcxx: [libstdc++, libstdc++11] threads: [null, posix, win32] # Windows MinGW exception: [null, dwarf2, sjlj, seh] # Windows MinGW cppstd: [null, 98, gnu98, 11, gnu11, 14, gnu14, 17, gnu17, 20, gnu20, 23, gnu23] msvc: - version: [170, 180, 190, 191, 192, 193] + version: [170, 180, 190, 191, 192, 193, 194] update: [null, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] runtime: [static, dynamic] runtime_type: [Debug, Release] diff --git a/conans/client/conf/detect_vs.py b/conans/client/conf/detect_vs.py index f0c48c749..4db783a87 100644 --- a/conans/client/conf/detect_vs.py +++ b/conans/client/conf/detect_vs.py @@ -12,7 +12,7 @@ def vs_installation_path(version): def vs_detect_update(version): - version = {"193": "17", "192": "16", "191": "15"}.get(str(version)) + version = {"194": "17", "193": "17", "192": "16", "191": "15"}.get(str(version)) full_version = _vs_installation_path(version)[1] components = full_version.split(".") if len(components) > 1: diff --git a/conans/client/graph/compatibility.py b/conans/client/graph/compatibility.py index c72c4377c..967ddc90e 100644 --- a/conans/client/graph/compatibility.py +++ b/conans/client/graph/compatibility.py @@ -30,26 +30,43 @@ from conan.errors import ConanException def cppstd_compat(conanfile): # It will try to find packages with all the cppstd versions extension_properties = getattr(conanfile, "extension_properties", {}) - if extension_properties.get("compatibility_cppstd") is False: - return [] compiler = conanfile.settings.get_safe("compiler") compiler_version = conanfile.settings.get_safe("compiler.version") cppstd = conanfile.settings.get_safe("compiler.cppstd") - if not compiler or not compiler_version or not cppstd: + if not compiler or not compiler_version: return [] base = dict(conanfile.settings.values_list) - cppstd_possible_values = supported_cppstd(conanfile) - if cppstd_possible_values is None: - conanfile.output.warning(f'No cppstd compatibility defined for compiler "{compiler}"') - return [] - ret = [] - for _cppstd in cppstd_possible_values: - if _cppstd is None or _cppstd == cppstd: + factors = [] # List of list, each sublist is a potential combination + if cppstd is not None and extension_properties.get("compatibility_cppstd") is not False: + cppstd_possible_values = supported_cppstd(conanfile) + if cppstd_possible_values is None: + conanfile.output.warning(f'No cppstd compatibility defined for compiler "{compiler}"') + else: + factors.append([{"compiler.cppstd": v} for v in cppstd_possible_values if v != cppstd]) + + if compiler == "msvc": + msvc_fallback = {"194": "193"}.get(compiler_version) + if msvc_fallback: + factors.append([{"compiler.version": msvc_fallback}]) + + combinations = [] + for factor in factors: + if not combinations: + combinations = factor continue + new_combinations = [] + for comb in combinations: + for f in factor: + comb = comb.copy() + comb.update(f) + new_combinations.append(comb) + combinations = new_combinations + + ret = [] + for comb in combinations: configuration = base.copy() - configuration["compiler.cppstd"] = _cppstd + configuration.update(comb) ret.append({"settings": [(k, v) for k, v in configuration.items()]}) - return ret """
[bug] Docker runner does not honor custom container name ### Describe the bug When trying to use official ConanDockerTools images with the new feature [Docker runners](https://docs.conan.io/2/reference/runners/docker.html), I wanted to use a custom container name (e.g conan_linux_gcc11), however, the current behavior uses image name instead and ignores my configuration file. ``` conan create all --version=1.0.1 -pr linux-gcc11 ======== Exporting recipe to the cache ======== paho-mqtt-cpp/1.0.1: Exporting package recipe: /Users/uilian/Development/conan/conan-center-index/recipes/paho-mqtt-cpp/all/conanfile.py paho-mqtt-cpp/1.0.1: exports: File 'conandata.yml' found. Exporting it... paho-mqtt-cpp/1.0.1: Calling export_sources() paho-mqtt-cpp/1.0.1: Copied 1 '.py' file: conanfile.py paho-mqtt-cpp/1.0.1: Copied 1 '.yml' file: conandata.yml paho-mqtt-cpp/1.0.1: Copied 1 '.patch' file: 1.0.1-0001-fix-cmake.patch paho-mqtt-cpp/1.0.1: Exported to cache folder: /Users/uilian/.conan2/p/paho-c2a77d934f3de/e paho-mqtt-cpp/1.0.1: Exported: paho-mqtt-cpp/1.0.1#f7c87fa70a8dc4d8274efeb500f73320 (2024-05-10 10:03:04 UTC) ======== Input profiles ======== Profile host: [settings] arch=x86_64 build_type=Release compiler=gcc compiler.cppstd=17 compiler.libcxx=libstdc++11 compiler.version=11 os=Linux [conf] Profile build: [settings] arch=armv8 build_type=Release compiler=apple-clang compiler.cppstd=17 compiler.libcxx=libc++ compiler.version=15 os=Macos [conf] ┌───────────────────────────────┐ | Creating the docker container | └───────────────────────────────┘ ERROR: Imposible to run the container "conanio/gcc11-ubuntu16.04:2.3.0" with image "conanio/gcc11-ubuntu16.04:2.3.0" 400 Client Error for http+docker://localhost/v1.43/containers/create?name=conanio%2Fgcc11-ubuntu16.04%3A2.3.0: Bad Request ("Invalid container name (conanio/gcc11-ubuntu16.04:2.3.0), only [a-zA-Z0-9][a-zA-Z0-9_.-] are allowed") ``` The 🐛 is because the code is passing the image name instead of the container name to Docker: https://github.com/conan-io/conan/blob/2.3.0/conan/internal/runner/docker.py#L114 🍔 /cc @davidsanfal #### Environment OS: OSX 14.4.1 (23E224) Arch: Mac M1 MAX Conan version: 2.3.0 Docker version: 25.0.4-rd Rancher version: 1.13.1 ### How to reproduce it To reproduce this error in Mac, I need a profile file and a configuration file, plus, the docker image downloaded. ``` # ~/.conan2/profiles/linux-gcc11 [settings] arch=x86_64 build_type=Release compiler=gcc compiler.cppstd=17 compiler.libcxx=libstdc++11 compiler.version=11 os=Linux [runner] type=docker cache=clean remove=true configfile=/Users/uilian/.conan2/runners/linux-gcc11 ``` ``` # ~/.conan2/runners/linux-gcc11 image: conanio/gcc11-ubuntu16.04:2.3.0 run: name: conan_linux_gcc11 containerUser: conan privileged: False ``` Once you have these files in your Conan cache folder, you will need to run: ``` docker pull conanio/gcc11-ubuntu16.04:2.3.0 conan new cmake_lib -d name=foo -d version=0.1.0 conan create . -pr:b default -pr:h linux-gcc11 ``` (I ran docker pull separated only to illustrate)
conan-io/conan
diff --git a/conans/test/integration/command/runner_test.py b/conans/test/integration/command/runner_test.py index 5341d7309..f809236bd 100644 --- a/conans/test/integration/command/runner_test.py +++ b/conans/test/integration/command/runner_test.py @@ -141,7 +141,8 @@ def test_create_docker_runner_dockerfile_file_path(): client.save({"host": profile_host, "build": profile_build}) client.run("new cmake_lib -d name=pkg -d version=0.2") client.run("create . -pr:h host -pr:b build") - print(client.out) + + assert "Container conan-runner-docker running" in client.out assert "Restore: pkg/0.2" in client.out assert "Restore: pkg/0.2:8631cf963dbbb4d7a378a64a6fd1dc57558bc2fe" in client.out assert "Restore: pkg/0.2:8631cf963dbbb4d7a378a64a6fd1dc57558bc2fe metadata" in client.out @@ -249,7 +250,7 @@ def test_create_docker_runner_profile_abs_path(): cache=copy remove=True """) - + client.save({"host": profile_host, "build": profile_build}) client.run("new cmake_lib -d name=pkg -d version=0.2") client.run(f"create . -pr:h '{os.path.join(client.current_folder, 'host')}' -pr:b '{os.path.join(client.current_folder, 'build')}'") @@ -272,6 +273,8 @@ def test_create_docker_runner_profile_abs_path_from_configfile(): build: dockerfile: {dockerfile_path("Dockerfile_test")} build_context: {conan_base_path()} + run: + name: my-custom-conan-runner-container """) client.save({"configfile.yaml": configfile}) @@ -301,11 +304,12 @@ def test_create_docker_runner_profile_abs_path_from_configfile(): cache=copy remove=True """) - + client.save({"host": profile_host, "build": profile_build}) client.run("new cmake_lib -d name=pkg -d version=0.2") client.run(f"create . -pr:h '{os.path.join(client.current_folder, 'host')}' -pr:b '{os.path.join(client.current_folder, 'build')}'") + assert "Container my-custom-conan-runner-container running" in client.out assert "Restore: pkg/0.2" in client.out assert "Restore: pkg/0.2:8631cf963dbbb4d7a378a64a6fd1dc57558bc2fe" in client.out assert "Restore: pkg/0.2:8631cf963dbbb4d7a378a64a6fd1dc57558bc2fe metadata" in client.out @@ -357,11 +361,11 @@ def test_create_docker_runner_profile_abs_path_from_configfile_with_args(): cache=copy remove=True """) - + client.save({"host": profile_host, "build": profile_build}) client.run("new cmake_lib -d name=pkg -d version=0.2") client.run(f"create . -pr:h '{os.path.join(client.current_folder, 'host')}' -pr:b '{os.path.join(client.current_folder, 'build')}'") - print(client.out) + assert "test/integration/command/dockerfiles/Dockerfile_args" in client.out assert "Restore: pkg/0.2" in client.out assert "Restore: pkg/0.2:8631cf963dbbb4d7a378a64a6fd1dc57558bc2fe" in client.out @@ -434,4 +438,4 @@ def test_create_docker_runner_default_build_profile_error(): client.save({"host_clean": profile_host}) client.run("new cmake_lib -d name=pkg -d version=0.2") with pytest.raises(Exception, match="ERROR: The default build profile '/root/.conan2/profiles/default' doesn't exist.") as exception: - client.run("create . -pr:h host_clean") \ No newline at end of file + client.run("create . -pr:h host_clean") diff --git a/conans/test/integration/package_id/test_cache_compatibles.py b/conans/test/integration/package_id/test_cache_compatibles.py index f98dd7fe6..702b11e6d 100644 --- a/conans/test/integration/package_id/test_cache_compatibles.py +++ b/conans/test/integration/package_id/test_cache_compatibles.py @@ -377,6 +377,27 @@ class TestDefaultCompat: c.run("install --requires=app/0.1 --build=missing") assert re.search(r"Skipped binaries(\s*)tool/0.1", c.out) + def test_msvc_194_fallback(self): + c = TestClient() + save(c.cache.default_profile_path, "") + c.save({"conanfile.py": GenConanfile("mylib", "1.0").with_settings("os", "arch", + "compiler", "build_type"), + "profile_build": "[settings]\nos=Windows\narch=x86_64"}) + + c.run("create . -s os=Windows -s arch=x86_64 -s build_type=Release " + "-s compiler=msvc " + "-s compiler.version=193 -s compiler.cppstd=17 " + "-s compiler.runtime=dynamic -pr:b=profile_build") + package_id1 = c.created_package_id("mylib/1.0") + + # Try to install with cppstd 14, it will find cppstd 17 as compatible + c.run("install --requires=mylib/1.0@ -s os=Windows -s arch=x86_64 -s build_type=Release " + "-s compiler=msvc " + "-s compiler.version=194 -s compiler.cppstd=14 " + "-s compiler.runtime=dynamic -pr:b=profile_build") + assert "mylib/1.0: Main binary package 'e340edd75790e7156c595edebd3d98b10a2e091e' missing."\ + f"Using compatible package '{package_id1}'" + class TestErrorsCompatibility: """ when the plugin fails, we want a clear message and a helpful trace diff --git a/conans/test/unittests/tools/cmake/test_cmaketoolchain.py b/conans/test/unittests/tools/cmake/test_cmaketoolchain.py index b08dc13b7..8bba79509 100644 --- a/conans/test/unittests/tools/cmake/test_cmaketoolchain.py +++ b/conans/test/unittests/tools/cmake/test_cmaketoolchain.py @@ -194,7 +194,7 @@ def test_osx_deployment_target(conanfile_apple): def conanfile_msvc(): c = ConanFile(None) c.settings = Settings({"os": ["Windows"], - "compiler": {"msvc": {"version": ["193"], "cppstd": ["20"], + "compiler": {"msvc": {"version": ["193", "194"], "cppstd": ["20"], "update": [None, 8, 9]}}, "build_type": ["Release"], "arch": ["x86"]}) @@ -226,6 +226,14 @@ def test_toolset_update_version(conanfile_msvc): assert 'set(CMAKE_GENERATOR_TOOLSET "v143,version=14.38" CACHE STRING "" FORCE)' in toolchain.content +def test_toolset_update_version_overflow(conanfile_msvc): + # https://github.com/conan-io/conan/issues/15583 + conanfile_msvc.settings.compiler.version = "194" + conanfile_msvc.settings.compiler.update = "8" + toolchain = CMakeToolchain(conanfile_msvc) + assert 'set(CMAKE_GENERATOR_TOOLSET "v143,version=14.48" CACHE STRING "" FORCE)' in toolchain.content + + def test_toolset_x64(conanfile_msvc): # https://github.com/conan-io/conan/issues/11144 conanfile_msvc.conf.define("tools.cmake.cmaketoolchain:toolset_arch", "x64") diff --git a/conans/test/unittests/tools/microsoft/test_msvs_toolset.py b/conans/test/unittests/tools/microsoft/test_msvs_toolset.py index b5f8b1a5d..14574127e 100644 --- a/conans/test/unittests/tools/microsoft/test_msvs_toolset.py +++ b/conans/test/unittests/tools/microsoft/test_msvs_toolset.py @@ -15,6 +15,7 @@ def test_invalid_compiler(): @pytest.mark.parametrize("compiler_version,expected_toolset", [ + ("194", "v143"), ("193", "v143"), ("192", "v142"), ("191", "v141"),
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 6 }
2.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "conans/requirements.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
beautifulsoup4==4.13.3 bottle==0.13.2 certifi==2025.1.31 charset-normalizer==3.4.1 colorama==0.4.6 -e git+https://github.com/conan-io/conan.git@cab4f18453af93582d42b5f001f768df0cfe3058#egg=conan distro==1.8.0 docker==5.0.3 exceptiongroup==1.2.2 execnet==2.1.1 fasteners==0.19 idna==3.10 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 mock==1.3.0 packaging==24.2 parameterized==0.9.0 patch-ng==1.17.4 pbr==6.1.1 pluggy==1.5.0 pluginbase==1.0.1 PyJWT==2.10.1 pytest==7.4.4 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 six==1.17.0 soupsieve==2.6 tomli==2.2.1 typing_extensions==4.13.0 urllib3==1.26.20 waitress==3.0.2 WebOb==1.8.9 websocket-client==1.8.0 WebTest==2.0.35
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - beautifulsoup4==4.13.3 - bottle==0.13.2 - certifi==2025.1.31 - charset-normalizer==3.4.1 - colorama==0.4.6 - conan==2.3.1 - distro==1.8.0 - docker==5.0.3 - exceptiongroup==1.2.2 - execnet==2.1.1 - fasteners==0.19 - idna==3.10 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - mock==1.3.0 - packaging==24.2 - parameterized==0.9.0 - patch-ng==1.17.4 - pbr==6.1.1 - pluggy==1.5.0 - pluginbase==1.0.1 - pyjwt==2.10.1 - pytest==7.4.4 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - six==1.17.0 - soupsieve==2.6 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==1.26.20 - waitress==3.0.2 - webob==1.8.9 - websocket-client==1.8.0 - webtest==2.0.35 prefix: /opt/conda/envs/conan
[ "conans/test/integration/package_id/test_cache_compatibles.py::TestDefaultCompat::test_msvc_194_fallback", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_toolset_update_version_overflow", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_default[194-v143]" ]
[]
[ "conans/test/integration/package_id/test_cache_compatibles.py::TestCacheCompatibles::test_compatible_build_type", "conans/test/integration/package_id/test_cache_compatibles.py::TestCacheCompatibles::test_compatible_recipe_reference", "conans/test/integration/package_id/test_cache_compatibles.py::test_cppstd", "conans/test/integration/package_id/test_cache_compatibles.py::test_cppstd_validated", "conans/test/integration/package_id/test_cache_compatibles.py::test_cppstd_server", "conans/test/integration/package_id/test_cache_compatibles.py::TestDefaultCompat::test_default_cppstd_compatibility", "conans/test/integration/package_id/test_cache_compatibles.py::TestDefaultCompat::test_fail_with_options_deleted", "conans/test/integration/package_id/test_cache_compatibles.py::TestDefaultCompat::test_header_only_build_missing", "conans/test/integration/package_id/test_cache_compatibles.py::TestDefaultCompat::test_check_min_cppstd", "conans/test/integration/package_id/test_cache_compatibles.py::TestDefaultCompat::test_check_min_cppstd_interface", "conans/test/integration/package_id/test_cache_compatibles.py::TestDefaultCompat::test_can_create_multiple", "conans/test/integration/package_id/test_cache_compatibles.py::TestDefaultCompat::test_unnecessary_builds", "conans/test/integration/package_id/test_cache_compatibles.py::TestErrorsCompatibility::test_error_compatibility", "conans/test/integration/package_id/test_cache_compatibles.py::TestErrorsCompatibility::test_remove_plugin_file", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_cmake_toolchain", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_remove", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_filter", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_dict_keys", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_template_remove", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_template_change", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_context_change", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_context_update", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_context_replace", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_replace_block", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_add_new_block", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_user_toolchain", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_osx_deployment_target", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_toolset", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_toolset_update_version", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_toolset_x64", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_toolset_cuda", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_older_msvc_toolset", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_older_msvc_toolset_update", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_msvc_xp_toolsets", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_no_fpic_when_not_an_option", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_fpic_when_shared_true[True]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_fpic_when_shared_true[False]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_fpic_when_not_shared", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_no_fpic_on_windows", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_fpic_disabled", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_fpic_enabled", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_libcxx_abi_flag", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_apple_cmake_osx_sysroot[Macos-None-x86_64-macosx]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_apple_cmake_osx_sysroot[Macos-None-armv7-macosx]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_apple_cmake_osx_sysroot[iOS-iphonesimulator-armv8-iphonesimulator]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_apple_cmake_osx_sysroot[watchOS-watchsimulator-armv8-watchsimulator]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_apple_cmake_osx_sysroot_sdk_mandatory[iOS-x86_64-]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_apple_cmake_osx_sysroot_sdk_mandatory[watchOS-armv8-]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_apple_cmake_osx_sysroot_sdk_mandatory[tvOS-x86_64-]", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_compilers_block", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::test_linker_scripts_block", "conans/test/unittests/tools/cmake/test_cmaketoolchain.py::TestCrossBuild::test_cmake_system_name", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_invalid_compiler", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_default[193-v143]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_default[192-v142]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_default[191-v141]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_default[190-v140]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_default[180-v120]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_default[170-v110]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_custom[193-v143_xp-v143_xp]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_custom[192-v142_xp-v142_xp]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_custom[191-v141_xp-v141_xp]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_custom[190-v140_xp-v140_xp]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_custom[180-v120_xp-v120_xp]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_msvc_custom[170-v110_xp-v110_xp]", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_old_compiler", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.3-classic-Intel", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.2-classic-Intel", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.1-classic-Intel", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.3-icx-Intel", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.2-icx-Intel", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.1-icx-Intel", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.3-dpcpp-Intel(R)", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.2-dpcpp-Intel(R)", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.1-dpcpp-Intel(R)", "conans/test/unittests/tools/microsoft/test_msvs_toolset.py::test_intel_cc_default[2021.3-None-Intel(R)" ]
[]
MIT License
18,412
2,419
[ "conan/internal/api/detect_api.py", "conan/internal/runner/docker.py", "conan/tools/microsoft/visual.py", "conans/client/conf/__init__.py", "conans/client/conf/detect_vs.py", "conans/client/graph/compatibility.py" ]
getsentry__sentry-python-3070
a02eb9c26badfe0d11429d018399455f4394fef7
2024-05-14 14:00:49
a02eb9c26badfe0d11429d018399455f4394fef7
antonpirker: This breaks now a lot of tests because they assume `sentry-trace` to be there, when there is no transaction it seems...
diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py index 36aab289..a6b1905a 100644 --- a/sentry_sdk/tracing.py +++ b/sentry_sdk/tracing.py @@ -426,12 +426,18 @@ class Span: If the span's containing transaction doesn't yet have a ``baggage`` value, this will cause one to be generated and stored. """ + if not self.containing_transaction: + # Do not propagate headers if there is no containing transaction. Otherwise, this + # span ends up being the root span of a new trace, and since it does not get sent + # to Sentry, the trace will be missing a root transaction. The dynamic sampling + # context will also be missing, breaking dynamic sampling & traces. + return + yield SENTRY_TRACE_HEADER_NAME, self.to_traceparent() - if self.containing_transaction: - baggage = self.containing_transaction.get_baggage().serialize() - if baggage: - yield BAGGAGE_HEADER_NAME, baggage + baggage = self.containing_transaction.get_baggage().serialize() + if baggage: + yield BAGGAGE_HEADER_NAME, baggage @classmethod def from_traceparent(
Dynamic sampling context might be missing from Celery Beat transactions ### How do you use Sentry? Sentry Saas (sentry.io) ### Version Latest 2.x ### Steps to Reproduce Update: [See here](https://github.com/szokeasaurusrex/issue-reproductions/tree/main/getsentry/sentry-python/3068) for a simple demonstration of the broken behavior. Under investigation – if the dynamic sampling context is missing from transactions started in Celery Beat, this would explain strange behavior we observe in Sentry where the parent (Celery Beat) transaction is missing while the child transactions are all present ### Expected Result Celery Beat transactions contain a dynamic sampling context ### Actual Result In some cases, the dynamic sampling context might be missing
getsentry/sentry-python
diff --git a/tests/integrations/aiohttp/test_aiohttp.py b/tests/integrations/aiohttp/test_aiohttp.py index a07fe010..092b20ad 100644 --- a/tests/integrations/aiohttp/test_aiohttp.py +++ b/tests/integrations/aiohttp/test_aiohttp.py @@ -404,13 +404,17 @@ async def test_trace_from_headers_if_performance_enabled( # The aiohttp_client is instrumented so will generate the sentry-trace header and add request. # Get the sentry-trace header from the request so we can later compare with transaction events. client = await aiohttp_client(app) - resp = await client.get("/") + with start_transaction(): + # Headers are only added to the span if there is an active transaction + resp = await client.get("/") + sentry_trace_header = resp.request_info.headers.get("sentry-trace") trace_id = sentry_trace_header.split("-")[0] assert resp.status == 500 - msg_event, error_event, transaction_event = events + # Last item is the custom transaction event wrapping `client.get("/")` + msg_event, error_event, transaction_event, _ = events assert msg_event["contexts"]["trace"] assert "trace_id" in msg_event["contexts"]["trace"] diff --git a/tests/integrations/celery/test_update_celery_task_headers.py b/tests/integrations/celery/test_update_celery_task_headers.py index b1588e86..e94379f7 100644 --- a/tests/integrations/celery/test_update_celery_task_headers.py +++ b/tests/integrations/celery/test_update_celery_task_headers.py @@ -77,33 +77,6 @@ def test_span_with_transaction(sentry_init): ) -def test_span_with_no_transaction(sentry_init): - sentry_init(enable_tracing=True) - headers = {} - - with sentry_sdk.start_span(op="test_span") as span: - updated_headers = _update_celery_task_headers(headers, span, False) - - assert updated_headers["sentry-trace"] == span.to_traceparent() - assert updated_headers["headers"]["sentry-trace"] == span.to_traceparent() - assert "baggage" not in updated_headers.keys() - assert "baggage" not in updated_headers["headers"].keys() - - -def test_custom_span(sentry_init): - sentry_init(enable_tracing=True) - span = sentry_sdk.tracing.Span() - headers = {} - - with sentry_sdk.start_transaction(name="test_transaction"): - updated_headers = _update_celery_task_headers(headers, span, False) - - assert updated_headers["sentry-trace"] == span.to_traceparent() - assert updated_headers["headers"]["sentry-trace"] == span.to_traceparent() - assert "baggage" not in updated_headers.keys() - assert "baggage" not in updated_headers["headers"].keys() - - def test_span_with_transaction_custom_headers(sentry_init): sentry_init(enable_tracing=True) headers = { @@ -137,36 +110,3 @@ def test_span_with_transaction_custom_headers(sentry_init): assert updated_headers["headers"]["baggage"] == combined_baggage.serialize( include_third_party=True ) - - -def test_span_with_no_transaction_custom_headers(sentry_init): - sentry_init(enable_tracing=True) - headers = { - "baggage": BAGGAGE_VALUE, - "sentry-trace": SENTRY_TRACE_VALUE, - } - - with sentry_sdk.start_span(op="test_span") as span: - updated_headers = _update_celery_task_headers(headers, span, False) - - assert updated_headers["sentry-trace"] == span.to_traceparent() - assert updated_headers["headers"]["sentry-trace"] == span.to_traceparent() - assert updated_headers["baggage"] == headers["baggage"] - assert updated_headers["headers"]["baggage"] == headers["baggage"] - - -def test_custom_span_custom_headers(sentry_init): - sentry_init(enable_tracing=True) - span = sentry_sdk.tracing.Span() - headers = { - "baggage": BAGGAGE_VALUE, - "sentry-trace": SENTRY_TRACE_VALUE, - } - - with sentry_sdk.start_transaction(name="test_transaction"): - updated_headers = _update_celery_task_headers(headers, span, False) - - assert updated_headers["sentry-trace"] == span.to_traceparent() - assert updated_headers["headers"]["sentry-trace"] == span.to_traceparent() - assert updated_headers["baggage"] == headers["baggage"] - assert updated_headers["headers"]["baggage"] == headers["baggage"] diff --git a/tests/integrations/httpx/test_httpx.py b/tests/integrations/httpx/test_httpx.py index fa22c444..ff93dd38 100644 --- a/tests/integrations/httpx/test_httpx.py +++ b/tests/integrations/httpx/test_httpx.py @@ -5,6 +5,7 @@ import httpx import pytest import responses +import sentry_sdk from sentry_sdk import capture_message, start_transaction from sentry_sdk.consts import MATCH_ALL, SPANDATA from sentry_sdk.integrations.httpx import HttpxIntegration @@ -258,10 +259,11 @@ def test_option_trace_propagation_targets( integrations=[HttpxIntegration()], ) - if asyncio.iscoroutinefunction(httpx_client.get): - asyncio.get_event_loop().run_until_complete(httpx_client.get(url)) - else: - httpx_client.get(url) + with sentry_sdk.start_transaction(): # Must be in a transaction to propagate headers + if asyncio.iscoroutinefunction(httpx_client.get): + asyncio.get_event_loop().run_until_complete(httpx_client.get(url)) + else: + httpx_client.get(url) request_headers = httpx_mock.get_request().headers @@ -271,6 +273,22 @@ def test_option_trace_propagation_targets( assert "sentry-trace" not in request_headers +def test_do_not_propagate_outside_transaction(sentry_init, httpx_mock): + httpx_mock.add_response() + + sentry_init( + traces_sample_rate=1.0, + trace_propagation_targets=[MATCH_ALL], + integrations=[HttpxIntegration()], + ) + + httpx_client = httpx.Client() + httpx_client.get("http://example.com/") + + request_headers = httpx_mock.get_request().headers + assert "sentry-trace" not in request_headers + + @pytest.mark.tests_internal_exceptions def test_omit_url_data_if_parsing_fails(sentry_init, capture_events): sentry_init(integrations=[HttpxIntegration()]) diff --git a/tests/tracing/test_propagation.py b/tests/tracing/test_propagation.py new file mode 100644 index 00000000..730bf267 --- /dev/null +++ b/tests/tracing/test_propagation.py @@ -0,0 +1,40 @@ +import sentry_sdk +import pytest + + +def test_standalone_span_iter_headers(sentry_init): + sentry_init(enable_tracing=True) + + with sentry_sdk.start_span(op="test") as span: + with pytest.raises(StopIteration): + # We should not have any propagation headers + next(span.iter_headers()) + + +def test_span_in_span_iter_headers(sentry_init): + sentry_init(enable_tracing=True) + + with sentry_sdk.start_span(op="test"): + with sentry_sdk.start_span(op="test2") as span_inner: + with pytest.raises(StopIteration): + # We should not have any propagation headers + next(span_inner.iter_headers()) + + +def test_span_in_transaction(sentry_init): + sentry_init(enable_tracing=True) + + with sentry_sdk.start_transaction(op="test"): + with sentry_sdk.start_span(op="test2") as span: + # Ensure the headers are there + next(span.iter_headers()) + + +def test_span_in_span_in_transaction(sentry_init): + sentry_init(enable_tracing=True) + + with sentry_sdk.start_transaction(op="test"): + with sentry_sdk.start_span(op="test2"): + with sentry_sdk.start_span(op="test3") as span_inner: + # Ensure the headers are there + next(span_inner.iter_headers())
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pre-commit" ], "pre_install": null, "python": "3.9", "reqs_path": [ "test-requirements.txt", "devenv-requirements.txt" ], "test_cmd": "pytest tests/ --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asttokens==3.0.0 attrs==25.3.0 black==25.1.0 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 colorama==0.4.6 coverage==7.8.0 cryptography==44.0.2 decorator==5.2.1 distlib==0.3.9 dnspython==2.7.0 docopt==0.6.2 exceptiongroup==1.2.2 executing==2.2.0 filelock==3.18.0 flake8==5.0.4 flake8-bugbear==23.3.12 identify==2.6.9 idna==3.10 iniconfig==2.1.0 ipdb==0.13.13 ipython==8.18.1 jedi==0.19.2 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 loguru==0.7.3 MarkupSafe==3.0.2 matplotlib-inline==0.1.7 mccabe==0.7.0 mockupdb==1.8.1 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 packaging==24.2 parso==0.8.4 pathspec==0.12.1 pep8-naming==0.14.1 pexpect==4.9.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prompt_toolkit==3.0.50 ptyprocess==0.7.0 pure_eval==0.2.3 py==1.11.0 pycodestyle==2.9.1 pycparser==2.22 pyflakes==2.5.0 Pygments==2.19.1 pymongo==4.11.3 pyrsistent==0.20.0 PySocks==1.7.1 pytest==6.2.5 pytest-asyncio==0.20.3 pytest-cov==6.0.0 pytest-forked==1.6.0 pytest-localserver==0.9.0.post0 pytest-watch==4.2.0 PyYAML==6.0.2 referencing==0.36.2 requests==2.32.3 responses==0.25.7 rpds-py==0.24.0 -e git+https://github.com/getsentry/sentry-python.git@a02eb9c26badfe0d11429d018399455f4394fef7#egg=sentry_sdk stack-data==0.6.3 toml==0.10.2 tomli==2.2.1 traitlets==5.14.3 types-certifi==2021.10.8.3 types-cffi==1.17.0.20250326 types-protobuf==5.29.1.20250315 types-pyOpenSSL==24.1.0.20240722 types-redis==4.6.0.20241004 types-setuptools==78.1.0.20250329 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3 watchdog==6.0.0 wcwidth==0.2.13 Werkzeug==3.1.3
name: sentry-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asttokens==3.0.0 - attrs==25.3.0 - black==25.1.0 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - colorama==0.4.6 - coverage==7.8.0 - cryptography==44.0.2 - decorator==5.2.1 - distlib==0.3.9 - dnspython==2.7.0 - docopt==0.6.2 - exceptiongroup==1.2.2 - executing==2.2.0 - filelock==3.18.0 - flake8==5.0.4 - flake8-bugbear==23.3.12 - identify==2.6.9 - idna==3.10 - iniconfig==2.1.0 - ipdb==0.13.13 - ipython==8.18.1 - jedi==0.19.2 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - loguru==0.7.3 - markupsafe==3.0.2 - matplotlib-inline==0.1.7 - mccabe==0.7.0 - mockupdb==1.8.1 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - packaging==24.2 - parso==0.8.4 - pathspec==0.12.1 - pep8-naming==0.14.1 - pexpect==4.9.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prompt-toolkit==3.0.50 - ptyprocess==0.7.0 - pure-eval==0.2.3 - py==1.11.0 - pycodestyle==2.9.1 - pycparser==2.22 - pyflakes==2.5.0 - pygments==2.19.1 - pymongo==4.11.3 - pyrsistent==0.20.0 - pysocks==1.7.1 - pytest==6.2.5 - pytest-asyncio==0.20.3 - pytest-cov==6.0.0 - pytest-forked==1.6.0 - pytest-localserver==0.9.0.post0 - pytest-watch==4.2.0 - pyyaml==6.0.2 - referencing==0.36.2 - requests==2.32.3 - responses==0.25.7 - rpds-py==0.24.0 - sentry-sdk==2.1.1 - stack-data==0.6.3 - toml==0.10.2 - tomli==2.2.1 - traitlets==5.14.3 - types-certifi==2021.10.8.3 - types-cffi==1.17.0.20250326 - types-protobuf==5.29.1.20250315 - types-pyopenssl==24.1.0.20240722 - types-redis==4.6.0.20241004 - types-setuptools==78.1.0.20250329 - typing-extensions==4.13.0 - urllib3==2.3.0 - virtualenv==20.29.3 - watchdog==6.0.0 - wcwidth==0.2.13 - werkzeug==3.1.3 prefix: /opt/conda/envs/sentry-python
[ "tests/tracing/test_propagation.py::test_standalone_span_iter_headers", "tests/tracing/test_propagation.py::test_span_in_span_iter_headers" ]
[ "tests/test_basics.py::test_auto_enabling_integrations_catches_import_error", "tests/test_new_scopes_compat_event.py::test_event", "tests/test_new_scopes_compat_event.py::test_event2", "tests/test_new_scopes_compat_event.py::test_event3", "tests/test_new_scopes_compat_event.py::test_event4", "tests/test_new_scopes_compat_event.py::test_event5", "tests/test_utils.py::test_installed_modules", "tests/integrations/pymongo/test_pymongo.py::test_transactions[False]", "tests/integrations/pymongo/test_pymongo.py::test_transactions[True]", "tests/integrations/pymongo/test_pymongo.py::test_breadcrumbs[False]", "tests/integrations/pymongo/test_pymongo.py::test_breadcrumbs[True]" ]
[ "tests/test_api.py::test_get_current_span", "tests/test_api.py::test_get_current_span_default_hub", "tests/test_api.py::test_get_current_span_default_hub_with_transaction", "tests/test_api.py::test_traceparent_with_tracing_enabled", "tests/test_api.py::test_traceparent_with_tracing_disabled", "tests/test_api.py::test_baggage_with_tracing_disabled", "tests/test_api.py::test_baggage_with_tracing_enabled", "tests/test_api.py::test_continue_trace", "tests/test_api.py::test_is_initialized", "tests/test_api.py::test_get_client", "tests/test_api.py::test_set_tags", "tests/test_basics.py::test_processors", "tests/test_basics.py::test_generic_mechanism", "tests/test_basics.py::test_option_before_send", "tests/test_basics.py::test_option_before_send_discard", "tests/test_basics.py::test_option_before_send_transaction", "tests/test_basics.py::test_option_before_send_transaction_discard", "tests/test_basics.py::test_option_before_breadcrumb", "tests/test_basics.py::test_option_enable_tracing[None-None-False-None]", "tests/test_basics.py::test_option_enable_tracing[False-0.0-False-0.0]", "tests/test_basics.py::test_option_enable_tracing[False-1.0-False-1.0]", "tests/test_basics.py::test_option_enable_tracing[None-1.0-True-1.0]", "tests/test_basics.py::test_option_enable_tracing[True-1.0-True-1.0]", "tests/test_basics.py::test_option_enable_tracing[None-0.0-True-0.0]", "tests/test_basics.py::test_option_enable_tracing[True-0.0-True-0.0]", "tests/test_basics.py::test_option_enable_tracing[True-None-True-1.0]", "tests/test_basics.py::test_breadcrumb_arguments", "tests/test_basics.py::test_push_scope", "tests/test_basics.py::test_push_scope_null_client", "tests/test_basics.py::test_breadcrumbs", "tests/test_basics.py::test_attachments", "tests/test_basics.py::test_integration_scoping", "tests/test_basics.py::test_scope_event_processor_order", "tests/test_basics.py::test_capture_event_with_scope_kwargs", "tests/test_basics.py::test_dedupe_event_processor_drop_records_client_report", "tests/test_basics.py::test_event_processor_drop_records_client_report", "tests/test_basics.py::test_get_sdk_name[installed_integrations0-sentry.python.django]", "tests/test_basics.py::test_get_sdk_name[installed_integrations1-sentry.python.flask]", "tests/test_basics.py::test_get_sdk_name[installed_integrations2-sentry.python.fastapi]", "tests/test_basics.py::test_get_sdk_name[installed_integrations3-sentry.python.bottle]", "tests/test_basics.py::test_get_sdk_name[installed_integrations4-sentry.python.falcon]", "tests/test_basics.py::test_get_sdk_name[installed_integrations5-sentry.python.quart]", "tests/test_basics.py::test_get_sdk_name[installed_integrations6-sentry.python.sanic]", "tests/test_basics.py::test_get_sdk_name[installed_integrations7-sentry.python.starlette]", "tests/test_basics.py::test_get_sdk_name[installed_integrations8-sentry.python.chalice]", "tests/test_basics.py::test_get_sdk_name[installed_integrations9-sentry.python.serverless]", "tests/test_basics.py::test_get_sdk_name[installed_integrations10-sentry.python.pyramid]", "tests/test_basics.py::test_get_sdk_name[installed_integrations11-sentry.python.tornado]", "tests/test_basics.py::test_get_sdk_name[installed_integrations12-sentry.python.aiohttp]", "tests/test_basics.py::test_get_sdk_name[installed_integrations13-sentry.python.aws_lambda]", "tests/test_basics.py::test_get_sdk_name[installed_integrations14-sentry.python.gcp]", "tests/test_basics.py::test_get_sdk_name[installed_integrations15-sentry.python.beam]", "tests/test_basics.py::test_get_sdk_name[installed_integrations16-sentry.python.asgi]", "tests/test_basics.py::test_get_sdk_name[installed_integrations17-sentry.python.wsgi]", "tests/test_basics.py::test_get_sdk_name[installed_integrations18-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations19-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations20-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations21-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations22-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations23-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations24-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations25-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations26-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations27-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations28-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations29-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations30-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations31-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations32-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations33-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations34-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations35-sentry.python]", "tests/test_basics.py::test_get_sdk_name[installed_integrations36-sentry.python.django]", "tests/test_basics.py::test_get_sdk_name[installed_integrations37-sentry.python.flask]", "tests/test_basics.py::test_get_sdk_name[installed_integrations38-sentry.python.fastapi]", "tests/test_basics.py::test_get_sdk_name[installed_integrations39-sentry.python.bottle]", "tests/test_basics.py::test_get_sdk_name[installed_integrations40-sentry.python.falcon]", "tests/test_basics.py::test_get_sdk_name[installed_integrations41-sentry.python.quart]", "tests/test_basics.py::test_get_sdk_name[installed_integrations42-sentry.python.sanic]", "tests/test_basics.py::test_get_sdk_name[installed_integrations43-sentry.python.starlette]", "tests/test_basics.py::test_get_sdk_name[installed_integrations44-sentry.python.chalice]", "tests/test_basics.py::test_get_sdk_name[installed_integrations45-sentry.python.serverless]", "tests/test_basics.py::test_get_sdk_name[installed_integrations46-sentry.python.pyramid]", "tests/test_basics.py::test_get_sdk_name[installed_integrations47-sentry.python.tornado]", "tests/test_basics.py::test_get_sdk_name[installed_integrations48-sentry.python.aiohttp]", "tests/test_basics.py::test_get_sdk_name[installed_integrations49-sentry.python.aws_lambda]", "tests/test_basics.py::test_get_sdk_name[installed_integrations50-sentry.python.gcp]", "tests/test_basics.py::test_get_sdk_name[installed_integrations51-sentry.python.beam]", "tests/test_basics.py::test_get_sdk_name[installed_integrations52-sentry.python.asgi]", "tests/test_basics.py::test_get_sdk_name[installed_integrations53-sentry.python.wsgi]", "tests/test_basics.py::test_functions_to_trace", "tests/test_basics.py::test_functions_to_trace_with_class", "tests/test_basics.py::test_redis_disabled_when_not_installed", "tests/test_basics.py::test_multiple_setup_integrations_calls", "tests/test_basics.py::test_staticmethod_tracing", "tests/test_basics.py::test_classmethod_tracing", "tests/test_client.py::test_transport_option", "tests/test_client.py::test_proxy[testcase0]", "tests/test_client.py::test_proxy[testcase1]", "tests/test_client.py::test_proxy[testcase2]", "tests/test_client.py::test_proxy[testcase3]", "tests/test_client.py::test_proxy[testcase4]", "tests/test_client.py::test_proxy[testcase5]", "tests/test_client.py::test_proxy[testcase6]", "tests/test_client.py::test_proxy[testcase7]", "tests/test_client.py::test_proxy[testcase8]", "tests/test_client.py::test_proxy[testcase9]", "tests/test_client.py::test_proxy[testcase10]", "tests/test_client.py::test_proxy[testcase11]", "tests/test_client.py::test_proxy[testcase12]", "tests/test_client.py::test_proxy[testcase13]", "tests/test_client.py::test_proxy[testcase14]", "tests/test_client.py::test_proxy[testcase15]", "tests/test_client.py::test_proxy[testcase16]", "tests/test_client.py::test_proxy[testcase17]", "tests/test_client.py::test_proxy[testcase18]", "tests/test_client.py::test_proxy[testcase19]", "tests/test_client.py::test_proxy[testcase20]", "tests/test_client.py::test_socks_proxy[testcase0]", "tests/test_client.py::test_socks_proxy[testcase1]", "tests/test_client.py::test_socks_proxy[testcase2]", "tests/test_client.py::test_socks_proxy[testcase3]", "tests/test_client.py::test_socks_proxy[testcase4]", "tests/test_client.py::test_socks_proxy[testcase5]", "tests/test_client.py::test_socks_proxy[testcase6]", "tests/test_client.py::test_socks_proxy[testcase7]", "tests/test_client.py::test_socks_proxy[testcase8]", "tests/test_client.py::test_simple_transport", "tests/test_client.py::test_ignore_errors", "tests/test_client.py::test_include_local_variables_enabled", "tests/test_client.py::test_include_local_variables_disabled", "tests/test_client.py::test_include_source_context_enabled", "tests/test_client.py::test_include_source_context_disabled", "tests/test_client.py::test_function_names[integrations0]", "tests/test_client.py::test_function_names[integrations1]", "tests/test_client.py::test_attach_stacktrace_enabled", "tests/test_client.py::test_attach_stacktrace_enabled_no_locals", "tests/test_client.py::test_attach_stacktrace_in_app", "tests/test_client.py::test_attach_stacktrace_disabled", "tests/test_client.py::test_capture_event_works", "tests/test_client.py::test_atexit[10]", "tests/test_client.py::test_atexit[20]", "tests/test_client.py::test_configure_scope_available", "tests/test_client.py::test_client_debug_option_enabled", "tests/test_client.py::test_client_debug_option_disabled[True]", "tests/test_client.py::test_client_debug_option_disabled[False]", "tests/test_client.py::test_weird_chars", "tests/test_client.py::test_nan", "tests/test_client.py::test_cyclic_frame_vars", "tests/test_client.py::test_cyclic_data", "tests/test_client.py::test_databag_depth_stripping", "tests/test_client.py::test_databag_string_stripping", "tests/test_client.py::test_databag_breadth_stripping", "tests/test_client.py::test_chained_exceptions", "tests/test_client.py::test_broken_mapping", "tests/test_client.py::test_mapping_sends_exception", "tests/test_client.py::test_object_sends_exception", "tests/test_client.py::test_errno_errors", "tests/test_client.py::test_non_string_variables", "tests/test_client.py::test_dict_changed_during_iteration", "tests/test_client.py::test_init_string_types[http://894b7d594095440f8dfea9b300e6f572@localhost:8000/20]", "tests/test_client.py::test_init_string_types[http://894b7d594095440f8dfea9b300e6f572@localhost:8000/21]", "tests/test_client.py::test_max_breadcrumbs_option[sdk_options0-100]", "tests/test_client.py::test_max_breadcrumbs_option[sdk_options1-50]", "tests/test_client.py::test_multiple_positional_args", "tests/test_client.py::test_max_value_length_option[sdk_options0-1024]", "tests/test_client.py::test_max_value_length_option[sdk_options1-1800]", "tests/test_client.py::test_debug_option[None--False]", "tests/test_client.py::test_debug_option[None-t-True]", "tests/test_client.py::test_debug_option[None-1-True]", "tests/test_client.py::test_debug_option[None-True-True]", "tests/test_client.py::test_debug_option[None-true-True]", "tests/test_client.py::test_debug_option[None-f-False]", "tests/test_client.py::test_debug_option[None-0-False]", "tests/test_client.py::test_debug_option[None-False-False]", "tests/test_client.py::test_debug_option[None-false-False]", "tests/test_client.py::test_debug_option[None-xxx-False]", "tests/test_client.py::test_debug_option[True--True]", "tests/test_client.py::test_debug_option[True-t-True]", "tests/test_client.py::test_debug_option[True-1-True]", "tests/test_client.py::test_debug_option[True-True-True]", "tests/test_client.py::test_debug_option[True-true-True]", "tests/test_client.py::test_debug_option[True-f-True]", "tests/test_client.py::test_debug_option[True-0-True]", "tests/test_client.py::test_debug_option[True-False-True]", "tests/test_client.py::test_debug_option[True-false-True]", "tests/test_client.py::test_debug_option[True-xxx-True]", "tests/test_client.py::test_debug_option[False--False]", "tests/test_client.py::test_debug_option[False-t-False]", "tests/test_client.py::test_debug_option[False-1-False]", "tests/test_client.py::test_debug_option[False-True-False]", "tests/test_client.py::test_debug_option[False-true-False]", "tests/test_client.py::test_debug_option[False-f-False]", "tests/test_client.py::test_debug_option[False-0-False]", "tests/test_client.py::test_debug_option[False-False-False]", "tests/test_client.py::test_debug_option[False-false-False]", "tests/test_client.py::test_debug_option[False-xxx-False]", "tests/test_client.py::test_error_sampler[test_config0]", "tests/test_client.py::test_error_sampler[test_config1]", "tests/test_client.py::test_error_sampler[test_config2]", "tests/test_client.py::test_error_sampler[test_config3]", "tests/test_client.py::test_error_sampler[test_config4]", "tests/test_client.py::test_error_sampler[test_config5]", "tests/test_client.py::test_error_sampler[test_config6]", "tests/test_client.py::test_error_sampler[test_config7]", "tests/test_client.py::test_error_sampler[test_config8]", "tests/test_client.py::test_error_sampler[test_config9]", "tests/test_client.py::test_error_sampler[test_config10]", "tests/test_client.py::test_error_sampler[test_config11]", "tests/test_client.py::test_error_sampler[test_config12]", "tests/test_client.py::test_error_sampler[test_config13]", "tests/test_client.py::test_error_sampler[test_config14]", "tests/test_client.py::test_error_sampler[test_config15]", "tests/test_client.py::test_error_sampler[test_config16]", "tests/test_client.py::test_uwsgi_warnings[opt0-missing_flags0]", "tests/test_client.py::test_uwsgi_warnings[opt1-missing_flags1]", "tests/test_client.py::test_uwsgi_warnings[opt2-missing_flags2]", "tests/test_client.py::test_uwsgi_warnings[opt3-missing_flags3]", "tests/test_client.py::test_uwsgi_warnings[opt4-missing_flags4]", "tests/test_client.py::test_uwsgi_warnings[opt5-missing_flags5]", "tests/test_client.py::test_uwsgi_warnings[opt6-missing_flags6]", "tests/test_client.py::test_uwsgi_warnings[opt7-missing_flags7]", "tests/test_client.py::test_uwsgi_warnings[opt8-missing_flags8]", "tests/test_client.py::test_uwsgi_warnings[opt9-missing_flags9]", "tests/test_client.py::test_uwsgi_warnings[opt10-missing_flags10]", "tests/test_client.py::test_uwsgi_warnings[opt11-missing_flags11]", "tests/test_client.py::test_uwsgi_warnings[opt12-missing_flags12]", "tests/test_conftest.py::test_string_containing[dogs", "tests/test_conftest.py::test_string_containing[go,", "tests/test_conftest.py::test_string_containing[I", "tests/test_conftest.py::test_string_containing[dogs-True]", "tests/test_conftest.py::test_string_containing[-False]", "tests/test_conftest.py::test_string_containing[dog-False]", "tests/test_conftest.py::test_string_containing[good", "tests/test_conftest.py::test_string_containing[cats-False]", "tests/test_conftest.py::test_string_containing[1231-False]", "tests/test_conftest.py::test_string_containing[11.21-False]", "tests/test_conftest.py::test_string_containing[test_string10-False]", "tests/test_conftest.py::test_string_containing[test_string11-False]", "tests/test_conftest.py::test_string_containing[True-False]", "tests/test_conftest.py::test_dictionary_containing[test_dict0-True]", "tests/test_conftest.py::test_dictionary_containing[test_dict1-True]", "tests/test_conftest.py::test_dictionary_containing[test_dict2-False]", "tests/test_conftest.py::test_dictionary_containing[test_dict3-False]", "tests/test_conftest.py::test_dictionary_containing[test_dict4-False]", "tests/test_conftest.py::test_dictionary_containing[test_dict5-False]", "tests/test_conftest.py::test_dictionary_containing[{\"dogs\":", "tests/test_conftest.py::test_dictionary_containing[1231-False]", "tests/test_conftest.py::test_dictionary_containing[11.21-False]", "tests/test_conftest.py::test_dictionary_containing[test_dict9-False]", "tests/test_conftest.py::test_dictionary_containing[True-False]", "tests/test_conftest.py::test_object_described_by[test_obj0-True-True-True]", "tests/test_conftest.py::test_object_described_by[test_obj1-True-True-True]", "tests/test_conftest.py::test_object_described_by[test_obj2-False-True-False]", "tests/test_conftest.py::test_object_described_by[test_obj3-False-True-False]", "tests/test_conftest.py::test_object_described_by[test_obj4-False-True-False]", "tests/test_conftest.py::test_object_described_by[test_obj5-False-True-False]", "tests/test_conftest.py::test_object_described_by[test_obj6-False-False-True]", "tests/test_conftest.py::test_object_described_by[test_obj7-False-False-False]", "tests/test_conftest.py::test_object_described_by[Good", "tests/test_conftest.py::test_object_described_by[test_obj9-False-False-False]", "tests/test_conftest.py::test_object_described_by[1231-False-False-False]", "tests/test_conftest.py::test_object_described_by[11.21-False-False-False]", "tests/test_conftest.py::test_object_described_by[test_obj12-False-False-False]", "tests/test_conftest.py::test_object_described_by[True-False-False-False]", "tests/test_crons.py::test_decorator", "tests/test_crons.py::test_decorator_error", "tests/test_crons.py::test_contextmanager", "tests/test_crons.py::test_contextmanager_error", "tests/test_crons.py::test_capture_checkin_simple", "tests/test_crons.py::test_sample_rate_doesnt_affect_crons", "tests/test_crons.py::test_capture_checkin_new_id", "tests/test_crons.py::test_end_to_end", "tests/test_crons.py::test_monitor_config", "tests/test_crons.py::test_decorator_monitor_config", "tests/test_crons.py::test_decorator_no_monitor_config", "tests/test_crons.py::test_capture_checkin_sdk_not_initialized", "tests/test_crons.py::test_scope_data_in_checkin", "tests/test_crons.py::test_decorator_async", "tests/test_crons.py::test_decorator_error_async", "tests/test_crons.py::test_contextmanager_async", "tests/test_crons.py::test_contextmanager_error_async", "tests/test_envelope.py::test_add_and_get_basic_event", "tests/test_envelope.py::test_add_and_get_transaction_event", "tests/test_envelope.py::test_add_and_get_session", "tests/test_envelope.py::test_envelope_headers", "tests/test_envelope.py::test_envelope_with_sized_items", "tests/test_envelope.py::test_envelope_with_implicitly_sized_items", "tests/test_envelope.py::test_envelope_with_two_attachments", "tests/test_envelope.py::test_envelope_with_empty_attachments", "tests/test_envelope.py::test_envelope_without_headers", "tests/test_lru_cache.py::test_illegal_size[-10]", "tests/test_lru_cache.py::test_illegal_size[-1]", "tests/test_lru_cache.py::test_illegal_size[0]", "tests/test_lru_cache.py::test_simple_set_get", "tests/test_lru_cache.py::test_overwrite", "tests/test_lru_cache.py::test_cache_eviction", "tests/test_metrics.py::test_increment[threads]", "tests/test_metrics.py::test_timing[threads]", "tests/test_metrics.py::test_timing_decorator[threads]", "tests/test_metrics.py::test_timing_basic[threads]", "tests/test_metrics.py::test_distribution[threads]", "tests/test_metrics.py::test_set[threads]", "tests/test_metrics.py::test_gauge[threads]", "tests/test_metrics.py::test_transaction_name[threads]", "tests/test_metrics.py::test_metric_summaries[threads]", "tests/test_metrics.py::test_metric_name_normalization[threads-first-metric-nano-second-first-metric@nanosecond]", "tests/test_metrics.py::test_metric_name_normalization[threads-another_metric?-nano", "tests/test_metrics.py::test_metric_name_normalization[threads-metric-nanosecond-metric@nanosecond]", "tests/test_metrics.py::test_metric_name_normalization[threads-my.amaze.metric", "tests/test_metrics.py::test_metric_name_normalization[threads-m\\xe9tr\\xedc-nan\\xf6secon\\u010f-m_tr_c@nansecon]", "tests/test_metrics.py::test_metric_tag_normalization[threads-metric_tag0-expected_tag0]", "tests/test_metrics.py::test_metric_tag_normalization[threads-metric_tag1-expected_tag1]", "tests/test_metrics.py::test_metric_tag_normalization[threads-metric_tag2-expected_tag2]", "tests/test_metrics.py::test_metric_tag_normalization[threads-metric_tag3-expected_tag3]", "tests/test_metrics.py::test_metric_tag_normalization[threads-metric_tag4-expected_tag4]", "tests/test_metrics.py::test_metric_tag_normalization[threads-metric_tag5-expected_tag5]", "tests/test_metrics.py::test_before_emit_metric[threads]", "tests/test_metrics.py::test_aggregator_flush[threads]", "tests/test_metrics.py::test_tag_serialization[threads]", "tests/test_metrics.py::test_flush_recursion_protection[threads]", "tests/test_metrics.py::test_flush_recursion_protection_background_flush[threads]", "tests/test_transport.py::test_transport_works[threads-0-True-close-True]", "tests/test_transport.py::test_transport_works[threads-0-True-close-False]", "tests/test_transport.py::test_transport_works[threads-0-True-flush-True]", "tests/test_transport.py::test_transport_works[threads-0-True-flush-False]", "tests/test_transport.py::test_transport_works[threads-0-False-close-True]", "tests/test_transport.py::test_transport_works[threads-0-False-close-False]", "tests/test_transport.py::test_transport_works[threads-0-False-flush-True]", "tests/test_transport.py::test_transport_works[threads-0-False-flush-False]", "tests/test_transport.py::test_transport_works[threads-9-True-close-True]", "tests/test_transport.py::test_transport_works[threads-9-True-close-False]", "tests/test_transport.py::test_transport_works[threads-9-True-flush-True]", "tests/test_transport.py::test_transport_works[threads-9-True-flush-False]", "tests/test_transport.py::test_transport_works[threads-9-False-close-True]", "tests/test_transport.py::test_transport_works[threads-9-False-close-False]", "tests/test_transport.py::test_transport_works[threads-9-False-flush-True]", "tests/test_transport.py::test_transport_works[threads-9-False-flush-False]", "tests/utils/test_contextvars.py::test_leaks[threads]", "tests/test_metrics.py::test_multiple", "tests/test_monitor.py::test_no_monitor_if_disabled", "tests/test_monitor.py::test_monitor_if_enabled", "tests/test_monitor.py::test_monitor_unhealthy", "tests/test_monitor.py::test_transaction_uses_downsampled_rate", "tests/test_monitor.py::test_monitor_no_thread_on_shutdown_no_errors", "tests/test_new_scopes_compat.py::test_configure_scope_sdk1", "tests/test_new_scopes_compat.py::test_push_scope_sdk1", "tests/test_new_scopes_compat.py::test_with_hub_sdk1", "tests/test_new_scopes_compat.py::test_with_hub_configure_scope_sdk1", "tests/test_new_scopes_compat.py::test_with_hub_push_scope_sdk1", "tests/test_new_scopes_compat.py::test_with_cloned_hub_sdk1", "tests/test_new_scopes_compat.py::test_with_cloned_hub_configure_scope_sdk1", "tests/test_new_scopes_compat.py::test_with_cloned_hub_push_scope_sdk1", "tests/test_profiler.py::test_profiler_invalid_mode[experiment-foo]", "tests/test_profiler.py::test_profiler_invalid_mode[experiment-gevent]", "tests/test_profiler.py::test_profiler_invalid_mode[non", "tests/test_profiler.py::test_profiler_valid_mode[experiment-thread]", "tests/test_profiler.py::test_profiler_valid_mode[experiment-sleep]", "tests/test_profiler.py::test_profiler_valid_mode[non", "tests/test_profiler.py::test_profiler_setup_twice[experiment]", "tests/test_profiler.py::test_profiler_setup_twice[non", "tests/test_profiler.py::test_profiles_sample_rate[experiment-profiler", "tests/test_profiler.py::test_profiles_sample_rate[non", "tests/test_profiler.py::test_profiles_sampler[profiler", "tests/test_profiler.py::test_minimum_unique_samples_required", "tests/test_profiler.py::test_profile_captured", "tests/test_profiler.py::test_get_frame_name[function]", "tests/test_profiler.py::test_get_frame_name[lambda]", "tests/test_profiler.py::test_get_frame_name[instance_method]", "tests/test_profiler.py::test_get_frame_name[instance_method_wrapped0]", "tests/test_profiler.py::test_get_frame_name[class_method]", "tests/test_profiler.py::test_get_frame_name[class_method_wrapped]", "tests/test_profiler.py::test_get_frame_name[static_method]", "tests/test_profiler.py::test_get_frame_name[inherited_instance_method]", "tests/test_profiler.py::test_get_frame_name[instance_method_wrapped1]", "tests/test_profiler.py::test_get_frame_name[inherited_class_method]", "tests/test_profiler.py::test_get_frame_name[inherited_class_method_wrapped]", "tests/test_profiler.py::test_get_frame_name[inherited_static_method]", "tests/test_profiler.py::test_extract_frame[simple]", "tests/test_profiler.py::test_extract_stack_with_max_depth[less", "tests/test_profiler.py::test_extract_stack_with_max_depth[greater", "tests/test_profiler.py::test_extract_stack_with_max_depth[equals]", "tests/test_profiler.py::test_extract_stack_with_cache[frame0-36]", "tests/test_profiler.py::test_thread_scheduler_single_background_thread[thread", "tests/test_profiler.py::test_thread_scheduler_no_thread_on_shutdown[thread", "tests/test_profiler.py::test_max_profile_duration_reached[thread", "tests/test_profiler.py::test_profile_processing[empty]", "tests/test_profiler.py::test_profile_processing[single", "tests/test_profiler.py::test_profile_processing[two", "tests/test_propagationcontext.py::test_empty_context", "tests/test_propagationcontext.py::test_context_with_values", "tests/test_propagationcontext.py::test_lacy_uuids", "tests/test_propagationcontext.py::test_property_setters", "tests/test_propagationcontext.py::test_update", "tests/test_scope.py::test_copying", "tests/test_scope.py::test_merging", "tests/test_scope.py::test_common_args", "tests/test_scope.py::test_load_trace_data_from_env[env0-excepted_value0]", "tests/test_scope.py::test_load_trace_data_from_env[env1-excepted_value1]", "tests/test_scope.py::test_load_trace_data_from_env[env2-excepted_value2]", "tests/test_scope.py::test_load_trace_data_from_env[env3-excepted_value3]", "tests/test_scope.py::test_load_trace_data_from_env[env4-excepted_value4]", "tests/test_scope.py::test_load_trace_data_from_env[env5-None]", "tests/test_scope.py::test_load_trace_data_from_env[env6-None]", "tests/test_scope.py::test_scope_client", "tests/test_scope.py::test_get_current_scope", "tests/test_scope.py::test_get_isolation_scope", "tests/test_scope.py::test_get_global_scope", "tests/test_scope.py::test_get_client", "tests/test_scope.py::test_set_client", "tests/test_scope.py::test_fork", "tests/test_scope.py::test_get_global_scope_tags", "tests/test_scope.py::test_get_global_with_scope", "tests/test_scope.py::test_get_global_with_isolation_scope", "tests/test_scope.py::test_get_isolation_scope_tags", "tests/test_scope.py::test_get_current_scope_tags", "tests/test_scope.py::test_with_isolation_scope", "tests/test_scope.py::test_with_isolation_scope_data", "tests/test_scope.py::test_with_use_isolation_scope", "tests/test_scope.py::test_with_use_isolation_scope_data", "tests/test_scope.py::test_with_new_scope", "tests/test_scope.py::test_with_new_scope_data", "tests/test_scope.py::test_with_use_scope_data", "tests/test_scope.py::test_nested_scopes_with_tags", "tests/test_scope.py::test_should_send_default_pii_true", "tests/test_scope.py::test_should_send_default_pii_false", "tests/test_scope.py::test_set_tags", "tests/test_scrubber.py::test_request_scrubbing", "tests/test_scrubber.py::test_stack_var_scrubbing", "tests/test_scrubber.py::test_breadcrumb_extra_scrubbing", "tests/test_scrubber.py::test_span_data_scrubbing", "tests/test_scrubber.py::test_custom_denylist", "tests/test_scrubber.py::test_scrubbing_doesnt_affect_local_vars", "tests/test_scrubber.py::test_recursive_event_scrubber", "tests/test_serializer.py::test_bytes_serialization_decode", "tests/test_serializer.py::test_bytes_serialization_repr", "tests/test_serializer.py::test_bytearray_serialization_decode", "tests/test_serializer.py::test_bytearray_serialization_repr", "tests/test_serializer.py::test_memoryview_serialization_repr", "tests/test_serializer.py::test_serialize_sets", "tests/test_serializer.py::test_serialize_custom_mapping", "tests/test_serializer.py::test_custom_mapping_doesnt_mess_with_mock", "tests/test_serializer.py::test_trim_databag_breadth", "tests/test_serializer.py::test_no_trimming_if_max_request_body_size_is_always", "tests/test_serializer.py::test_max_value_length_default", "tests/test_serializer.py::test_max_value_length", "tests/test_sessions.py::test_basic", "tests/test_sessions.py::test_aggregates", "tests/test_sessions.py::test_aggregates_explicitly_disabled_session_tracking_request_mode", "tests/test_sessions.py::test_no_thread_on_shutdown_no_errors", "tests/test_spotlight.py::test_spotlight_off_by_default", "tests/test_spotlight.py::test_spotlight_default_url", "tests/test_spotlight.py::test_spotlight_custom_url", "tests/test_spotlight.py::test_spotlight_envelope", "tests/test_transport.py::test_transport_num_pools[None-2]", "tests/test_transport.py::test_transport_num_pools[2-2]", "tests/test_transport.py::test_transport_num_pools[10-10]", "tests/test_transport.py::test_socket_options", "tests/test_transport.py::test_keep_alive_true", "tests/test_transport.py::test_keep_alive_off_by_default", "tests/test_transport.py::test_socket_options_override_keep_alive", "tests/test_transport.py::test_socket_options_merge_with_keep_alive", "tests/test_transport.py::test_socket_options_override_defaults", "tests/test_transport.py::test_transport_infinite_loop", "tests/test_transport.py::test_transport_no_thread_on_shutdown_no_errors", "tests/test_transport.py::test_parse_rate_limits[-expected0]", "tests/test_transport.py::test_parse_rate_limits[invalid-expected1]", "tests/test_transport.py::test_parse_rate_limits[,,,-expected2]", "tests/test_transport.py::test_parse_rate_limits[42::organization,", "tests/test_transport.py::test_parse_rate_limits[4711:foobar;;transaction:organization-expected4]", "tests/test_transport.py::test_simple_rate_limits", "tests/test_transport.py::test_data_category_limits[200]", "tests/test_transport.py::test_data_category_limits[429]", "tests/test_transport.py::test_data_category_limits_reporting[200]", "tests/test_transport.py::test_data_category_limits_reporting[429]", "tests/test_transport.py::test_complex_limits_without_data_category[200]", "tests/test_transport.py::test_complex_limits_without_data_category[429]", "tests/test_transport.py::test_metric_bucket_limits[200]", "tests/test_transport.py::test_metric_bucket_limits[429]", "tests/test_transport.py::test_metric_bucket_limits_with_namespace[200]", "tests/test_transport.py::test_metric_bucket_limits_with_namespace[429]", "tests/test_transport.py::test_metric_bucket_limits_with_all_namespaces[200]", "tests/test_transport.py::test_metric_bucket_limits_with_all_namespaces[429]", "tests/test_utils.py::test_sanitize_url[http://localhost:8000-http://localhost:8000]", "tests/test_utils.py::test_sanitize_url[http://example.com-http://example.com]", "tests/test_utils.py::test_sanitize_url[https://example.com-https://example.com]", "tests/test_utils.py::test_sanitize_url[example.com?token=abc&sessionid=123&save=true-example.com?token=[Filtered]&sessionid=[Filtered]&save=[Filtered]]", "tests/test_utils.py::test_sanitize_url[http://example.com?token=abc&sessionid=123&save=true-http://example.com?token=[Filtered]&sessionid=[Filtered]&save=[Filtered]]", "tests/test_utils.py::test_sanitize_url[https://example.com?token=abc&sessionid=123&save=true-https://example.com?token=[Filtered]&sessionid=[Filtered]&save=[Filtered]]", "tests/test_utils.py::test_sanitize_url[http://localhost:8000/?token=abc&sessionid=123&save=true-http://localhost:8000/?token=[Filtered]&sessionid=[Filtered]&save=[Filtered]]", "tests/test_utils.py::test_sanitize_url[ftp://username:[email protected]:9876/bla/blub#foo-ftp://[Filtered]:[Filtered]@ftp.example.com:9876/bla/blub#foo]", "tests/test_utils.py::test_sanitize_url[https://username:[email protected]/bla/blub?token=abc&sessionid=123&save=true#fragment-https://[Filtered]:[Filtered]@example.com/bla/blub?token=[Filtered]&sessionid=[Filtered]&save=[Filtered]#fragment]", "tests/test_utils.py::test_sanitize_url[bla/blub/foo-bla/blub/foo]", "tests/test_utils.py::test_sanitize_url[/bla/blub/foo/-/bla/blub/foo/]", "tests/test_utils.py::test_sanitize_url[bla/blub/foo?token=abc&sessionid=123&save=true-bla/blub/foo?token=[Filtered]&sessionid=[Filtered]&save=[Filtered]]", "tests/test_utils.py::test_sanitize_url[/bla/blub/foo/?token=abc&sessionid=123&save=true-/bla/blub/foo/?token=[Filtered]&sessionid=[Filtered]&save=[Filtered]]", "tests/test_utils.py::test_sanitize_url_and_split[http://localhost:8000-expected_result0]", "tests/test_utils.py::test_sanitize_url_and_split[http://example.com-expected_result1]", "tests/test_utils.py::test_sanitize_url_and_split[https://example.com-expected_result2]", "tests/test_utils.py::test_sanitize_url_and_split[example.com?token=abc&sessionid=123&save=true-expected_result3]", "tests/test_utils.py::test_sanitize_url_and_split[http://example.com?token=abc&sessionid=123&save=true-expected_result4]", "tests/test_utils.py::test_sanitize_url_and_split[https://example.com?token=abc&sessionid=123&save=true-expected_result5]", "tests/test_utils.py::test_sanitize_url_and_split[http://localhost:8000/?token=abc&sessionid=123&save=true-expected_result6]", "tests/test_utils.py::test_sanitize_url_and_split[ftp://username:[email protected]:9876/bla/blub#foo-expected_result7]", "tests/test_utils.py::test_sanitize_url_and_split[https://username:[email protected]/bla/blub?token=abc&sessionid=123&save=true#fragment-expected_result8]", "tests/test_utils.py::test_sanitize_url_and_split[bla/blub/foo-expected_result9]", "tests/test_utils.py::test_sanitize_url_and_split[bla/blub/foo?token=abc&sessionid=123&save=true-expected_result10]", "tests/test_utils.py::test_sanitize_url_and_split[/bla/blub/foo/?token=abc&sessionid=123&save=true-expected_result11]", "tests/test_utils.py::test_parse_url[https://example.com-True-https://example.com--]", "tests/test_utils.py::test_parse_url[example.com?token=abc&sessionid=123&save=true-True-example.com-token=[Filtered]&sessionid=[Filtered]&save=[Filtered]-]", "tests/test_utils.py::test_parse_url[https://example.com?token=abc&sessionid=123&save=true-True-https://example.com-token=[Filtered]&sessionid=[Filtered]&save=[Filtered]-]", "tests/test_utils.py::test_parse_url[https://username:[email protected]/bla/blub?token=abc&sessionid=123&save=true#fragment-True-https://[Filtered]:[Filtered]@example.com/bla/blub-token=[Filtered]&sessionid=[Filtered]&save=[Filtered]-fragment]", "tests/test_utils.py::test_parse_url[bla/blub/foo-True-bla/blub/foo--]", "tests/test_utils.py::test_parse_url[/bla/blub/foo/#baz-True-/bla/blub/foo/--baz]", "tests/test_utils.py::test_parse_url[bla/blub/foo?token=abc&sessionid=123&save=true-True-bla/blub/foo-token=[Filtered]&sessionid=[Filtered]&save=[Filtered]-]", "tests/test_utils.py::test_parse_url[/bla/blub/foo/?token=abc&sessionid=123&save=true-True-/bla/blub/foo/-token=[Filtered]&sessionid=[Filtered]&save=[Filtered]-]", "tests/test_utils.py::test_parse_url[https://example.com-False-https://example.com--]", "tests/test_utils.py::test_parse_url[example.com?token=abc&sessionid=123&save=true-False-example.com-token=abc&sessionid=123&save=true-]", "tests/test_utils.py::test_parse_url[https://example.com?token=abc&sessionid=123&save=true-False-https://example.com-token=abc&sessionid=123&save=true-]", "tests/test_utils.py::test_parse_url[https://username:[email protected]/bla/blub?token=abc&sessionid=123&save=true#fragment-False-https://[Filtered]:[Filtered]@example.com/bla/blub-token=abc&sessionid=123&save=true-fragment]", "tests/test_utils.py::test_parse_url[bla/blub/foo-False-bla/blub/foo--]", "tests/test_utils.py::test_parse_url[/bla/blub/foo/#baz-False-/bla/blub/foo/--baz]", "tests/test_utils.py::test_parse_url[bla/blub/foo?token=abc&sessionid=123&save=true-False-bla/blub/foo-token=abc&sessionid=123&save=true-]", "tests/test_utils.py::test_parse_url[/bla/blub/foo/?token=abc&sessionid=123&save=true-False-/bla/blub/foo/-token=abc&sessionid=123&save=true-]", "tests/test_utils.py::test_accepts_valid_sample_rate[0.0]", "tests/test_utils.py::test_accepts_valid_sample_rate[0.1231]", "tests/test_utils.py::test_accepts_valid_sample_rate[1.0]", "tests/test_utils.py::test_accepts_valid_sample_rate[True]", "tests/test_utils.py::test_accepts_valid_sample_rate[False]", "tests/test_utils.py::test_warns_on_invalid_sample_rate[dogs", "tests/test_utils.py::test_warns_on_invalid_sample_rate[rate1]", "tests/test_utils.py::test_warns_on_invalid_sample_rate[rate2]", "tests/test_utils.py::test_warns_on_invalid_sample_rate[rate3]", "tests/test_utils.py::test_warns_on_invalid_sample_rate[rate4]", "tests/test_utils.py::test_warns_on_invalid_sample_rate[nan]", "tests/test_utils.py::test_warns_on_invalid_sample_rate[None]", "tests/test_utils.py::test_warns_on_invalid_sample_rate[-1.121]", "tests/test_utils.py::test_warns_on_invalid_sample_rate[1.231]", "tests/test_utils.py::test_include_source_context_when_serializing_frame[True]", "tests/test_utils.py::test_include_source_context_when_serializing_frame[False]", "tests/test_utils.py::test_match_regex_list[-regex_list0-False]", "tests/test_utils.py::test_match_regex_list[None-regex_list1-False]", "tests/test_utils.py::test_match_regex_list[-None-False]", "tests/test_utils.py::test_match_regex_list[None-None-False]", "tests/test_utils.py::test_match_regex_list[some-string-regex_list4-False]", "tests/test_utils.py::test_match_regex_list[some-string-None-False]", "tests/test_utils.py::test_match_regex_list[some-string-regex_list6-True]", "tests/test_utils.py::test_match_regex_list[some-string-regex_list7-False]", "tests/test_utils.py::test_match_regex_list[some-string-regex_list8-False]", "tests/test_utils.py::test_match_regex_list[some-string-regex_list9-True]", "tests/test_utils.py::test_match_regex_list[some-string-regex_list10-False]", "tests/test_utils.py::test_match_regex_list[some-string-regex_list11-True]", "tests/test_utils.py::test_parse_version[3.5.15-expected_result0]", "tests/test_utils.py::test_parse_version[2.0.9-expected_result1]", "tests/test_utils.py::test_parse_version[2.0.0-expected_result2]", "tests/test_utils.py::test_parse_version[0.6.0-expected_result3]", "tests/test_utils.py::test_parse_version[2.0.0.post1-expected_result4]", "tests/test_utils.py::test_parse_version[2.0.0rc3-expected_result5]", "tests/test_utils.py::test_parse_version[2.0.0rc2-expected_result6]", "tests/test_utils.py::test_parse_version[2.0.0rc1-expected_result7]", "tests/test_utils.py::test_parse_version[2.0.0b4-expected_result8]", "tests/test_utils.py::test_parse_version[2.0.0b3-expected_result9]", "tests/test_utils.py::test_parse_version[2.0.0b2-expected_result10]", "tests/test_utils.py::test_parse_version[2.0.0b1-expected_result11]", "tests/test_utils.py::test_parse_version[0.6beta3-expected_result12]", "tests/test_utils.py::test_parse_version[0.6beta2-expected_result13]", "tests/test_utils.py::test_parse_version[0.6beta1-expected_result14]", "tests/test_utils.py::test_parse_version[0.4.2b-expected_result15]", "tests/test_utils.py::test_parse_version[0.4.2a-expected_result16]", "tests/test_utils.py::test_parse_version[0.0.1-expected_result17]", "tests/test_utils.py::test_parse_version[0.0.0-expected_result18]", "tests/test_utils.py::test_parse_version[1-expected_result19]", "tests/test_utils.py::test_parse_version[1.0-expected_result20]", "tests/test_utils.py::test_parse_version[1.0.0-expected_result21]", "tests/test_utils.py::test_parse_version[", "tests/test_utils.py::test_parse_version[x1.0.0-None]", "tests/test_utils.py::test_parse_version[1.0.0x-None]", "tests/test_utils.py::test_parse_version[x1.0.0x-None]", "tests/test_utils.py::test_is_sentry_url_true[https://[email protected]/123456789-True]", "tests/test_utils.py::test_is_sentry_url_true[https://[email protected]/123456789-False]", "tests/test_utils.py::test_is_sentry_url_no_client", "tests/test_utils.py::test_get_error_message[-<lambda>]", "tests/test_utils.py::test_get_error_message[some-string-<lambda>]", "tests/test_utils.py::test_installed_modules_caching", "tests/test_utils.py::test_devnull_inaccessible", "tests/test_utils.py::test_devnull_not_found", "tests/test_utils.py::test_default_release", "tests/test_utils.py::test_default_release_empty_string", "tests/test_utils.py::test_ensure_integration_enabled_integration_enabled", "tests/test_utils.py::test_ensure_integration_enabled_integration_disabled", "tests/test_utils.py::test_ensure_integration_enabled_no_original_function_enabled", "tests/test_utils.py::test_ensure_integration_enabled_no_original_function_disabled", "tests/test_utils.py::test_ensure_integration_enabled_async_integration_enabled", "tests/test_utils.py::test_ensure_integration_enabled_async_integration_disabled", "tests/test_utils.py::test_ensure_integration_enabled_async_no_original_function_enabled", "tests/test_utils.py::test_ensure_integration_enabled_async_no_original_function_disabled", "tests/test_utils.py::test_duration_in_milliseconds[delta0-132.0]", "tests/test_utils.py::test_duration_in_milliseconds[delta1-3600132.0]", "tests/test_utils.py::test_duration_in_milliseconds[delta2-864000000.0]", "tests/test_utils.py::test_duration_in_milliseconds[delta3-0.1]", "tests/test_utils.py::test_get_current_thread_meta_explicit_thread", "tests/test_utils.py::test_get_current_thread_meta_bad_explicit_thread", "tests/test_utils.py::test_get_current_thread_meta_running_thread", "tests/test_utils.py::test_get_current_thread_meta_bad_running_thread", "tests/test_utils.py::test_get_current_thread_meta_main_thread", "tests/test_utils.py::test_get_current_thread_meta_failed_to_get_main_thread", "tests/integrations/test_gnu_backtrace.py::test_basic[0.", "tests/integrations/test_gnu_backtrace.py::test_basic[1.", "tests/integrations/test_gnu_backtrace.py::test_basic[10.", "tests/integrations/test_gnu_backtrace.py::test_basic[11.", "tests/integrations/test_gnu_backtrace.py::test_basic[12.", "tests/integrations/test_gnu_backtrace.py::test_basic[13.", "tests/integrations/test_gnu_backtrace.py::test_basic[14.", "tests/integrations/test_gnu_backtrace.py::test_basic[15.", "tests/integrations/test_gnu_backtrace.py::test_basic[16.", "tests/integrations/test_gnu_backtrace.py::test_basic[17.", "tests/integrations/test_gnu_backtrace.py::test_basic[18.", "tests/integrations/test_gnu_backtrace.py::test_basic[19.", "tests/integrations/test_gnu_backtrace.py::test_basic[2.", "tests/integrations/test_gnu_backtrace.py::test_basic[20.", "tests/integrations/test_gnu_backtrace.py::test_basic[21.", "tests/integrations/test_gnu_backtrace.py::test_basic[22.", "tests/integrations/test_gnu_backtrace.py::test_basic[23.", "tests/integrations/test_gnu_backtrace.py::test_basic[24.", "tests/integrations/test_gnu_backtrace.py::test_basic[25.", "tests/integrations/test_gnu_backtrace.py::test_basic[26.", "tests/integrations/test_gnu_backtrace.py::test_basic[27.", "tests/integrations/test_gnu_backtrace.py::test_basic[28.", "tests/integrations/test_gnu_backtrace.py::test_basic[29.", "tests/integrations/test_gnu_backtrace.py::test_basic[3.", "tests/integrations/test_gnu_backtrace.py::test_basic[30.", "tests/integrations/test_gnu_backtrace.py::test_basic[31.", "tests/integrations/test_gnu_backtrace.py::test_basic[4.", "tests/integrations/test_gnu_backtrace.py::test_basic[5.", "tests/integrations/test_gnu_backtrace.py::test_basic[6.", "tests/integrations/test_gnu_backtrace.py::test_basic[7.", "tests/integrations/test_gnu_backtrace.py::test_basic[8.", "tests/integrations/test_gnu_backtrace.py::test_basic[9.", "tests/integrations/argv/test_argv.py::test_basic", "tests/integrations/asyncio/test_asyncio.py::test_create_task", "tests/integrations/asyncio/test_asyncio.py::test_gather", "tests/integrations/asyncio/test_asyncio.py::test_exception", "tests/integrations/asyncio/test_asyncio.py::test_task_result", "tests/integrations/asyncio/test_asyncio.py::test_patch_asyncio", "tests/integrations/asyncio/test_asyncio.py::test_sentry_task_factory_no_factory", "tests/integrations/asyncio/test_asyncio.py::test_sentry_task_factory_with_factory", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_is_aws_http_error", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_is_aws_ok", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_is_aw_exception", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_aws_context[405--expected_context0]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_aws_context[200-something-but-not-json-expected_context1]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_aws_context[200-{\"accountId\":", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_is_gcp_http_error", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_is_gcp_ok", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_is_gcp_exception", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_gcp_context[405-None-expected_context0]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_gcp_context[200-something-but-not-json-expected_context1]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_gcp_context[200-{\"instance\":", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_provider[False-False-]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_provider[False-True-gcp]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_provider[True-False-aws]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_provider[True-True-aws]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_resource_context_unsupported_providers[alibaba_cloud]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_resource_context_unsupported_providers[azure]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_resource_context_unsupported_providers[ibm_cloud]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_resource_context_unsupported_providers[tencent_cloud]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_resource_context_supported_providers[aws]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_get_cloud_resource_context_supported_providers[gcp]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[-cloud_resource_context0-False-False]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[aws-cloud_resource_context1-False-False]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[gcp-cloud_resource_context2-False-False]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[azure-cloud_resource_context3-True-False]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[alibaba_cloud-cloud_resource_context4-True-False]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[ibm_cloud-cloud_resource_context5-True-False]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[tencent_cloud-cloud_resource_context6-True-False]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[-cloud_resource_context7-False-True]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[aws-cloud_resource_context8-False-True]", "tests/integrations/cloud_resource_context/test_cloud_resource_context.py::test_setup_once[gcp-cloud_resource_context9-False-True]", "tests/integrations/excepthook/test_excepthook.py::test_excepthook", "tests/integrations/excepthook/test_excepthook.py::test_always_value_excepthook", "tests/integrations/gcp/test_gcp.py::test_handled_exception", "tests/integrations/gcp/test_gcp.py::test_unhandled_exception", "tests/integrations/gcp/test_gcp.py::test_timeout_error", "tests/integrations/gcp/test_gcp.py::test_performance_no_error", "tests/integrations/gcp/test_gcp.py::test_performance_error", "tests/integrations/gcp/test_gcp.py::test_traces_sampler_gets_correct_values_in_sampling_context", "tests/integrations/gcp/test_gcp.py::test_error_has_new_trace_context_performance_enabled", "tests/integrations/gcp/test_gcp.py::test_error_has_new_trace_context_performance_disabled", "tests/integrations/gcp/test_gcp.py::test_error_has_existing_trace_context_performance_enabled", "tests/integrations/gcp/test_gcp.py::test_error_has_existing_trace_context_performance_disabled", "tests/integrations/logging/test_logging.py::test_logging_works_with_many_loggers[logger0]", "tests/integrations/logging/test_logging.py::test_logging_works_with_many_loggers[logger1]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs0-None]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs0-integrations1]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs0-integrations2]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs1-None]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs1-integrations1]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs1-integrations2]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs2-None]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs2-integrations1]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs2-integrations2]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs3-None]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs3-integrations1]", "tests/integrations/logging/test_logging.py::test_logging_defaults[kwargs3-integrations2]", "tests/integrations/logging/test_logging.py::test_logging_extra_data", "tests/integrations/logging/test_logging.py::test_logging_extra_data_integer_keys", "tests/integrations/logging/test_logging.py::test_logging_stack", "tests/integrations/logging/test_logging.py::test_logging_level", "tests/integrations/logging/test_logging.py::test_custom_log_level_names", "tests/integrations/logging/test_logging.py::test_logging_filters", "tests/integrations/logging/test_logging.py::test_logging_captured_warnings", "tests/integrations/logging/test_logging.py::test_ignore_logger", "tests/integrations/logging/test_logging.py::test_ignore_logger_wildcard", "tests/integrations/loguru/test_loguru.py::test_just_log[True-True-LoggingLevels.TRACE-None]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-True-LoggingLevels.DEBUG-None]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-True-LoggingLevels.INFO-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-True-LoggingLevels.SUCCESS-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-True-LoggingLevels.WARNING-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-True-LoggingLevels.ERROR-True]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-True-LoggingLevels.CRITICAL-True]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-False-LoggingLevels.TRACE-None]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-False-LoggingLevels.DEBUG-None]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-False-LoggingLevels.INFO-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-False-LoggingLevels.SUCCESS-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-False-LoggingLevels.WARNING-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-False-LoggingLevels.ERROR-True]", "tests/integrations/loguru/test_loguru.py::test_just_log[True-False-LoggingLevels.CRITICAL-True]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-True-LoggingLevels.TRACE-None]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-True-LoggingLevels.DEBUG-None]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-True-LoggingLevels.INFO-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-True-LoggingLevels.SUCCESS-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-True-LoggingLevels.WARNING-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-True-LoggingLevels.ERROR-True]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-True-LoggingLevels.CRITICAL-True]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-False-LoggingLevels.TRACE-None]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-False-LoggingLevels.DEBUG-None]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-False-LoggingLevels.INFO-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-False-LoggingLevels.SUCCESS-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-False-LoggingLevels.WARNING-False]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-False-LoggingLevels.ERROR-True]", "tests/integrations/loguru/test_loguru.py::test_just_log[False-False-LoggingLevels.CRITICAL-True]", "tests/integrations/loguru/test_loguru.py::test_breadcrumb_format", "tests/integrations/loguru/test_loguru.py::test_event_format", "tests/integrations/modules/test_modules.py::test_basic", "tests/integrations/pure_eval/test_pure_eval.py::test_include_local_variables_enabled[integrations0]", "tests/integrations/pure_eval/test_pure_eval.py::test_include_local_variables_enabled[integrations1]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase0]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase1]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase2]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase3]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase4]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase5]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase6]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase7]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase8]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase9]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase10]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase11]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase12]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase13]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase14]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase15]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase16]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase17]", "tests/integrations/pymongo/test_pymongo.py::test_strip_pii[testcase18]", "tests/integrations/requests/test_requests.py::test_crumb_capture", "tests/integrations/requests/test_requests.py::test_omit_url_data_if_parsing_fails", "tests/integrations/serverless/test_serverless.py::test_basic", "tests/integrations/serverless/test_serverless.py::test_flush_disabled", "tests/integrations/socket/test_socket.py::test_getaddrinfo_trace", "tests/integrations/socket/test_socket.py::test_create_connection_trace", "tests/integrations/stdlib/test_httplib.py::test_crumb_capture", "tests/integrations/stdlib/test_httplib.py::test_crumb_capture_hint", "tests/integrations/stdlib/test_httplib.py::test_empty_realurl", "tests/integrations/stdlib/test_httplib.py::test_httplib_misuse", "tests/integrations/stdlib/test_httplib.py::test_outgoing_trace_headers", "tests/integrations/stdlib/test_httplib.py::test_outgoing_trace_headers_head_sdk", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[trace_propagation_targets0-example.com-/-False]", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[None-example.com-/-False]", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[trace_propagation_targets2-example.com-/-True]", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[trace_propagation_targets3-example.com-/-True]", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[trace_propagation_targets4-example.com--False]", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[trace_propagation_targets5-example.com--True]", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[trace_propagation_targets6-example.net--False]", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[trace_propagation_targets7-good.example.net--True]", "tests/integrations/stdlib/test_httplib.py::test_option_trace_propagation_targets[trace_propagation_targets8-good.example.net-/some/thing-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-None-as_iterator-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-None-as_iterator-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-None-as_list-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-None-as_list-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-env_mapping1-as_iterator-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-env_mapping1-as_iterator-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-env_mapping1-as_list-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-env_mapping1-as_list-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-env_mapping2-as_iterator-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-env_mapping2-as_iterator-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-env_mapping2-as_list-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[True-env_mapping2-as_list-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-None-as_iterator-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-None-as_iterator-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-None-as_list-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-None-as_list-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-env_mapping1-as_iterator-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-env_mapping1-as_iterator-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-env_mapping1-as_list-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-env_mapping1-as_list-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-env_mapping2-as_iterator-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-env_mapping2-as_iterator-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-env_mapping2-as_list-True]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_basic[False-env_mapping2-as_list-False]", "tests/integrations/stdlib/test_subprocess.py::test_subprocess_invalid_args", "tests/integrations/threading/test_threading.py::test_handles_exceptions[integrations0]", "tests/integrations/threading/test_threading.py::test_handles_exceptions[integrations1]", "tests/integrations/threading/test_threading.py::test_propagates_hub[True]", "tests/integrations/threading/test_threading.py::test_propagates_hub[False]", "tests/integrations/threading/test_threading.py::test_propagates_threadpool_hub[True]", "tests/integrations/threading/test_threading.py::test_propagates_threadpool_hub[False]", "tests/integrations/threading/test_threading.py::test_double_patching", "tests/integrations/threading/test_threading.py::test_wrapper_attributes", "tests/integrations/wsgi/test_wsgi.py::test_basic", "tests/integrations/wsgi/test_wsgi.py::test_keyboard_interrupt_is_captured", "tests/integrations/wsgi/test_wsgi.py::test_transaction_with_error", "tests/integrations/wsgi/test_wsgi.py::test_transaction_no_error", "tests/integrations/wsgi/test_wsgi.py::test_has_trace_if_performance_enabled", "tests/integrations/wsgi/test_wsgi.py::test_has_trace_if_performance_disabled", "tests/integrations/wsgi/test_wsgi.py::test_trace_from_headers_if_performance_enabled", "tests/integrations/wsgi/test_wsgi.py::test_trace_from_headers_if_performance_disabled", "tests/integrations/wsgi/test_wsgi.py::test_traces_sampler_gets_correct_values_in_sampling_context", "tests/integrations/wsgi/test_wsgi.py::test_session_mode_defaults_to_request_mode_in_wsgi_handler", "tests/integrations/wsgi/test_wsgi.py::test_auto_session_tracking_with_aggregates", "tests/integrations/wsgi/test_wsgi.py::test_profile_sent", "tests/tracing/test_baggage.py::test_third_party_baggage", "tests/tracing/test_baggage.py::test_mixed_baggage", "tests/tracing/test_baggage.py::test_malformed_baggage", "tests/tracing/test_decorator.py::test_trace_decorator", "tests/tracing/test_decorator.py::test_trace_decorator_no_trx", "tests/tracing/test_decorator.py::test_trace_decorator_async", "tests/tracing/test_decorator.py::test_trace_decorator_async_no_trx", "tests/tracing/test_http_headers.py::test_to_traceparent[True]", "tests/tracing/test_http_headers.py::test_to_traceparent[False]", "tests/tracing/test_http_headers.py::test_to_traceparent[None]", "tests/tracing/test_http_headers.py::test_sentrytrace_extraction[True]", "tests/tracing/test_http_headers.py::test_sentrytrace_extraction[False]", "tests/tracing/test_http_headers.py::test_iter_headers", "tests/tracing/test_integration_tests.py::test_basic[0.0]", "tests/tracing/test_integration_tests.py::test_basic[1.0]", "tests/tracing/test_integration_tests.py::test_continue_from_headers[0.0-True]", "tests/tracing/test_integration_tests.py::test_continue_from_headers[0.0-False]", "tests/tracing/test_integration_tests.py::test_continue_from_headers[0.0-None]", "tests/tracing/test_integration_tests.py::test_continue_from_headers[1.0-True]", "tests/tracing/test_integration_tests.py::test_continue_from_headers[1.0-False]", "tests/tracing/test_integration_tests.py::test_continue_from_headers[1.0-None]", "tests/tracing/test_integration_tests.py::test_dynamic_sampling_head_sdk_creates_dsc[0.5]", "tests/tracing/test_integration_tests.py::test_dynamic_sampling_head_sdk_creates_dsc[1.0]", "tests/tracing/test_integration_tests.py::test_memory_usage[args0-100]", "tests/tracing/test_integration_tests.py::test_memory_usage[args1-0]", "tests/tracing/test_integration_tests.py::test_transactions_do_not_go_through_before_send", "tests/tracing/test_integration_tests.py::test_start_span_after_finish", "tests/tracing/test_integration_tests.py::test_trace_propagation_meta_head_sdk", "tests/tracing/test_misc.py::test_span_trimming", "tests/tracing/test_misc.py::test_transaction_naming", "tests/tracing/test_misc.py::test_start_transaction", "tests/tracing/test_misc.py::test_finds_transaction_on_scope", "tests/tracing/test_misc.py::test_finds_transaction_when_descendent_span_is_on_scope", "tests/tracing/test_misc.py::test_finds_orphan_span_on_scope", "tests/tracing/test_misc.py::test_finds_non_orphan_span_on_scope", "tests/tracing/test_misc.py::test_circular_references", "tests/tracing/test_misc.py::test_set_meaurement", "tests/tracing/test_misc.py::test_set_meaurement_public_api", "tests/tracing/test_misc.py::test_should_propagate_trace[None-http://example.com-False]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets1-http://example.com-False]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets2-http://example.com-True]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets3-localhost:8443/api/users-True]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets4-http://localhost:8443/api/users-True]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets5-mylocalhost:8080/api/users-True]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets6-/api/envelopes-True]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets7-/backend/api/envelopes-False]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets8-myApi.com/v2/projects-True]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets9-myApi.com/v1/projects-False]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets10-https://example.com-True]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets11-https://example.com-True]", "tests/tracing/test_misc.py::test_should_propagate_trace[trace_propagation_targets12-http://example.com/insecure/-False]", "tests/tracing/test_misc.py::test_should_propagate_trace_to_sentry[https://[email protected]/12312012-http://example.com-True]", "tests/tracing/test_misc.py::test_should_propagate_trace_to_sentry[https://[email protected]/12312012-https://[email protected]/12312012-False]", "tests/tracing/test_misc.py::test_should_propagate_trace_to_sentry[https://[email protected]/12312012-http://squirrelchasers.ingest.sentry.io/12312012-False]", "tests/tracing/test_misc.py::test_should_propagate_trace_to_sentry[https://[email protected]/12312012-http://ingest.sentry.io/12312012-True]", "tests/tracing/test_misc.py::test_should_propagate_trace_to_sentry[https://[email protected]/12312012-http://localsentry.example.com-False]", "tests/tracing/test_misc.py::test_start_transaction_updates_scope_name_source", "tests/tracing/test_misc.py::test_transaction_dropped_debug_not_started[True]", "tests/tracing/test_misc.py::test_transaction_dropped_debug_not_started[None]", "tests/tracing/test_misc.py::test_transaction_dropeed_sampled_false", "tests/tracing/test_noop_span.py::test_noop_start_transaction", "tests/tracing/test_noop_span.py::test_noop_start_span", "tests/tracing/test_noop_span.py::test_noop_transaction_start_child", "tests/tracing/test_noop_span.py::test_noop_span_start_child", "tests/tracing/test_propagation.py::test_span_in_transaction", "tests/tracing/test_propagation.py::test_span_in_span_in_transaction", "tests/tracing/test_sampling.py::test_sampling_decided_only_for_transactions", "tests/tracing/test_sampling.py::test_nested_transaction_sampling_override[True]", "tests/tracing/test_sampling.py::test_nested_transaction_sampling_override[False]", "tests/tracing/test_sampling.py::test_no_double_sampling", "tests/tracing/test_sampling.py::test_get_transaction_and_span_from_scope_regardless_of_sampling_decision[True]", "tests/tracing/test_sampling.py::test_get_transaction_and_span_from_scope_regardless_of_sampling_decision[False]", "tests/tracing/test_sampling.py::test_uses_traces_sample_rate_correctly[0.0-False]", "tests/tracing/test_sampling.py::test_uses_traces_sample_rate_correctly[0.25-False]", "tests/tracing/test_sampling.py::test_uses_traces_sample_rate_correctly[0.75-True]", "tests/tracing/test_sampling.py::test_uses_traces_sample_rate_correctly[1.0-True]", "tests/tracing/test_sampling.py::test_uses_traces_sampler_return_value_correctly[0.0-False]", "tests/tracing/test_sampling.py::test_uses_traces_sampler_return_value_correctly[0.25-False]", "tests/tracing/test_sampling.py::test_uses_traces_sampler_return_value_correctly[0.75-True]", "tests/tracing/test_sampling.py::test_uses_traces_sampler_return_value_correctly[1.0-True]", "tests/tracing/test_sampling.py::test_tolerates_traces_sampler_returning_a_boolean[True]", "tests/tracing/test_sampling.py::test_tolerates_traces_sampler_returning_a_boolean[False]", "tests/tracing/test_sampling.py::test_only_captures_transaction_when_sampled_is_true[True]", "tests/tracing/test_sampling.py::test_only_captures_transaction_when_sampled_is_true[False]", "tests/tracing/test_sampling.py::test_prefers_traces_sampler_to_traces_sample_rate[0-True]", "tests/tracing/test_sampling.py::test_prefers_traces_sampler_to_traces_sample_rate[1-False]", "tests/tracing/test_sampling.py::test_ignores_inherited_sample_decision_when_traces_sampler_defined[True]", "tests/tracing/test_sampling.py::test_ignores_inherited_sample_decision_when_traces_sampler_defined[False]", "tests/tracing/test_sampling.py::test_traces_sampler_doesnt_overwrite_explicitly_passed_sampling_decision[True]", "tests/tracing/test_sampling.py::test_traces_sampler_doesnt_overwrite_explicitly_passed_sampling_decision[False]", "tests/tracing/test_sampling.py::test_inherits_parent_sampling_decision_when_traces_sampler_undefined[True]", "tests/tracing/test_sampling.py::test_inherits_parent_sampling_decision_when_traces_sampler_undefined[False]", "tests/tracing/test_sampling.py::test_passes_parent_sampling_decision_in_sampling_context[True]", "tests/tracing/test_sampling.py::test_passes_parent_sampling_decision_in_sampling_context[False]", "tests/tracing/test_sampling.py::test_passes_custom_samling_context_from_start_transaction_to_traces_sampler", "tests/tracing/test_sampling.py::test_sample_rate_affects_errors", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[dogs", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[traces_sampler_return_value1]", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[traces_sampler_return_value2]", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[traces_sampler_return_value3]", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[traces_sampler_return_value4]", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[nan]", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[None]", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[-1.121]", "tests/tracing/test_sampling.py::test_warns_and_sets_sampled_to_false_on_invalid_traces_sampler_return_value[1.231]", "tests/tracing/test_sampling.py::test_records_lost_event_only_if_traces_sample_rate_enabled[None-False-reports_output0]", "tests/tracing/test_sampling.py::test_records_lost_event_only_if_traces_sample_rate_enabled[0.0-False-reports_output1]", "tests/tracing/test_sampling.py::test_records_lost_event_only_if_traces_sample_rate_enabled[1.0-True-reports_output2]", "tests/tracing/test_sampling.py::test_records_lost_event_only_if_traces_sampler_enabled[None-False-reports_output0]", "tests/tracing/test_sampling.py::test_records_lost_event_only_if_traces_sampler_enabled[<lambda>-False-reports_output1]", "tests/tracing/test_sampling.py::test_records_lost_event_only_if_traces_sampler_enabled[<lambda>-True-reports_output2]", "tests/utils/test_general.py::test_safe_repr_regressions", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x00-]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x00-abcd]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x00-\\u043b\\u043e\\u0448\\u0430\\u0434\\u044c]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x07-]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x07-abcd]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x07-\\u043b\\u043e\\u0448\\u0430\\u0434\\u044c]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x1b-]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x1b-abcd]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\x1b-\\u043b\\u043e\\u0448\\u0430\\u0434\\u044c]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\n-]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\n-abcd]", "tests/utils/test_general.py::test_safe_repr_non_printable[\\n-\\u043b\\u043e\\u0448\\u0430\\u0434\\u044c]", "tests/utils/test_general.py::test_abs_path", "tests/utils/test_general.py::test_filename", "tests/utils/test_general.py::test_parse_dsn_paths[https://[email protected]/123-https://sentry.io/api/123/envelope/]", "tests/utils/test_general.py::test_parse_dsn_paths[https://[email protected]/bam/123-https://sentry.io/bam/api/123/envelope/]", "tests/utils/test_general.py::test_parse_dsn_paths[https://[email protected]/bam/baz/123-https://sentry.io/bam/baz/api/123/envelope/]", "tests/utils/test_general.py::test_parse_invalid_dsn[https://[email protected]://[email protected]/https://[email protected]/asdfhttps://[email protected]/asdf/https://[email protected]/asdf/123/]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame0-None-None-None-resulting_frame0]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame1-None-None-None-resulting_frame1]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame2-None-None-None-resulting_frame2]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame3-None-None-None-resulting_frame3]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame4-None-None-None-resulting_frame4]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame5-None-None-None-resulting_frame5]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame6-None-None-None-resulting_frame6]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame7-in_app_include7-None-None-resulting_frame7]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame8-in_app_include8-None-None-resulting_frame8]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame9-in_app_include9-None-None-resulting_frame9]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame10-in_app_include10-None-None-resulting_frame10]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame11-in_app_include11-None-None-resulting_frame11]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame12-in_app_include12-None-None-resulting_frame12]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame13-in_app_include13-None-None-resulting_frame13]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame14-None-in_app_exclude14-None-resulting_frame14]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame15-None-in_app_exclude15-None-resulting_frame15]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame16-None-in_app_exclude16-None-resulting_frame16]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame17-None-in_app_exclude17-None-resulting_frame17]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame18-None-in_app_exclude18-None-resulting_frame18]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame19-None-in_app_exclude19-None-resulting_frame19]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame20-None-in_app_exclude20-None-resulting_frame20]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame21-None-None-None-resulting_frame21]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame22-in_app_include22-None-None-resulting_frame22]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame23-None-in_app_exclude23-None-resulting_frame23]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame24-None-None-/home/ubuntu/fastapi-resulting_frame24]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame25-in_app_include25-None-/home/ubuntu/fastapi-resulting_frame25]", "tests/utils/test_general.py::test_set_in_app_in_frames[frame26-None-in_app_exclude26-/home/ubuntu/fastapi-resulting_frame26]", "tests/utils/test_general.py::test_iter_stacktraces", "tests/utils/test_general.py::test_successful_base64_conversion[Dogs", "tests/utils/test_general.py::test_successful_base64_conversion[\\U0001f436-8J+Qtg==]", "tests/utils/test_general.py::test_successful_base64_conversion[\\u039a\\u03b1\\u03bb\\u03cc", "tests/utils/test_general.py::test_successful_base64_conversion[Of", "tests/utils/test_general.py::test_failed_base64_conversion[1231]", "tests/utils/test_general.py::test_failed_base64_conversion[True]", "tests/utils/test_general.py::test_failed_base64_conversion[input2]", "tests/utils/test_general.py::test_failed_base64_conversion[input3]", "tests/utils/test_general.py::test_failed_base64_conversion[None]", "tests/utils/test_general.py::test_failed_base64_conversion[yayfordogs]", "tests/utils/test_general.py::test_failed_base64_conversion[#dog]", "tests/utils/test_general.py::test_failed_base64_conversion[\\U0001f436]", "tests/utils/test_general.py::test_strip_string[None-None-None]", "tests/utils/test_general.py::test_strip_string[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-None-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]", "tests/utils/test_general.py::test_strip_string[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-256-result2]", "tests/utils/test_general.py::test_strip_string[\\xe9\\xe9\\xe9\\xe9-None-\\xe9\\xe9\\xe9\\xe9]", "tests/utils/test_general.py::test_strip_string[\\xe9\\xe9\\xe9\\xe9-5-result4]", "tests/utils/test_transaction.py::test_transaction_from_function", "tests/utils/test_transaction.py::test_transaction_from_function_partialmethod" ]
[]
MIT License
18,424
294
[ "sentry_sdk/tracing.py" ]
tobymao__sqlglot-3473
3bc1fbed40d9d0d05f189ca60fdc7af19b815e8b
2024-05-14 14:32:51
b7ce9c3018661f7b375bfe9d354d01728e0d37cc
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py index ea3832db..9e76599c 100644 --- a/sqlglot/dialects/snowflake.py +++ b/sqlglot/dialects/snowflake.py @@ -477,6 +477,14 @@ class Snowflake(Dialect): SCHEMA_KINDS = {"OBJECTS", "TABLES", "VIEWS", "SEQUENCES", "UNIQUE KEYS", "IMPORTED KEYS"} + def _parse_create(self) -> exp.Create | exp.Command: + expression = super()._parse_create() + if isinstance(expression, exp.Create) and expression.kind == "TAG": + # Replace the Table node with the enclosed Identifier + expression.this.replace(expression.this.this) + + return expression + def _parse_column_ops(self, this: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]: this = super()._parse_column_ops(this) @@ -729,6 +737,7 @@ class Snowflake(Dialect): "SQL_DOUBLE": TokenType.DOUBLE, "SQL_VARCHAR": TokenType.VARCHAR, "STORAGE INTEGRATION": TokenType.STORAGE_INTEGRATION, + "TAG": TokenType.TAG, "TIMESTAMP_TZ": TokenType.TIMESTAMPTZ, "TOP": TokenType.TOP, } diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index 8c029191..b3cd4ceb 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -2437,6 +2437,10 @@ class Property(Expression): arg_types = {"this": True, "value": True} +class AllowedValuesProperty(Expression): + arg_types = {"expressions": True} + + class AlgorithmProperty(Property): arg_types = {"this": True} diff --git a/sqlglot/generator.py b/sqlglot/generator.py index bdfeef38..66eb23a0 100644 --- a/sqlglot/generator.py +++ b/sqlglot/generator.py @@ -74,6 +74,8 @@ class Generator(metaclass=_Generator): TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = { **JSON_PATH_PART_TRANSFORMS, + exp.AllowedValuesProperty: lambda self, + e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}", exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", exp.CaseSpecificColumnConstraint: lambda _, @@ -401,6 +403,7 @@ class Generator(metaclass=_Generator): NAMED_PLACEHOLDER_TOKEN = ":" PROPERTIES_LOCATION = { + exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, diff --git a/sqlglot/parser.py b/sqlglot/parser.py index f900f17e..93f67460 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -306,22 +306,23 @@ class Parser(metaclass=_Parser): DB_CREATABLES = { TokenType.DATABASE, - TokenType.SCHEMA, - TokenType.TABLE, - TokenType.VIEW, - TokenType.MODEL, TokenType.DICTIONARY, + TokenType.MODEL, + TokenType.SCHEMA, TokenType.SEQUENCE, TokenType.STORAGE_INTEGRATION, + TokenType.TABLE, + TokenType.TAG, + TokenType.VIEW, } CREATABLES = { TokenType.COLUMN, TokenType.CONSTRAINT, + TokenType.FOREIGN_KEY, TokenType.FUNCTION, TokenType.INDEX, TokenType.PROCEDURE, - TokenType.FOREIGN_KEY, *DB_CREATABLES, } @@ -741,6 +742,9 @@ class Parser(metaclass=_Parser): } PROPERTY_PARSERS: t.Dict[str, t.Callable] = { + "ALLOWED_VALUES": lambda self: self.expression( + exp.AllowedValuesProperty, expressions=self._parse_csv(self._parse_primary) + ), "ALGORITHM": lambda self: self._parse_property_assignment(exp.AlgorithmProperty), "AUTO": lambda self: self._parse_auto_property(), "AUTO_INCREMENT": lambda self: self._parse_property_assignment(exp.AutoIncrementProperty), diff --git a/sqlglot/tokens.py b/sqlglot/tokens.py index 96fc433c..adb18136 100644 --- a/sqlglot/tokens.py +++ b/sqlglot/tokens.py @@ -358,6 +358,7 @@ class TokenType(AutoName): STORAGE_INTEGRATION = auto() STRUCT = auto() TABLE_SAMPLE = auto() + TAG = auto() TEMPORARY = auto() TOP = auto() THEN = auto()
Parse CREATE TAG (Snowflake) Currently parsed as a Command: ``` CREATE TAG cost_center COMMENT = 'cost_center tag'; ``` Would be great to be parsed so the identifier, and comment, can be located. https://docs.snowflake.com/en/sql-reference/sql/create-tag
tobymao/sqlglot
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py index 6e532bec..58eece32 100644 --- a/tests/dialects/test_snowflake.py +++ b/tests/dialects/test_snowflake.py @@ -1210,6 +1210,10 @@ WHERE self.validate_identity("CREATE SCHEMA mytestschema_clone CLONE testschema") self.validate_identity("CREATE TABLE IDENTIFIER('foo') (COLUMN1 VARCHAR, COLUMN2 VARCHAR)") self.validate_identity("CREATE TABLE IDENTIFIER($foo) (col1 VARCHAR, col2 VARCHAR)") + self.validate_identity("CREATE TAG cost_center ALLOWED_VALUES 'a', 'b'") + self.validate_identity( + "CREATE OR REPLACE TAG IF NOT EXISTS cost_center COMMENT='cost_center tag'" + ).this.assert_is(exp.Identifier) self.validate_identity( "DROP FUNCTION my_udf (OBJECT(city VARCHAR, zipcode DECIMAL, val ARRAY(BOOLEAN)))" )
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 5 }
23.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 coverage==7.8.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@3bc1fbed40d9d0d05f189ca60fdc7af19b815e8b#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - coverage==7.8.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl" ]
[]
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_copy", "tests/dialects/test_snowflake.py::TestSnowflake::test_describe_table", "tests/dialects/test_snowflake.py::TestSnowflake::test_flatten", "tests/dialects/test_snowflake.py::TestSnowflake::test_historical_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_snowflake.py::TestSnowflake::test_minus", "tests/dialects/test_snowflake.py::TestSnowflake::test_null_treatment", "tests/dialects/test_snowflake.py::TestSnowflake::test_parse_like_any", "tests/dialects/test_snowflake.py::TestSnowflake::test_querying_semi_structured_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_replace", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_substr", "tests/dialects/test_snowflake.py::TestSnowflake::test_sample", "tests/dialects/test_snowflake.py::TestSnowflake::test_semi_structured_types", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_columns", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_imported_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_objects", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_primary_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_schemas", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_sequences", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_tables", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_unique_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_users", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_views", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_snowflake.py::TestSnowflake::test_staged_files", "tests/dialects/test_snowflake.py::TestSnowflake::test_storage_integration", "tests/dialects/test_snowflake.py::TestSnowflake::test_stored_procedures", "tests/dialects/test_snowflake.py::TestSnowflake::test_swap", "tests/dialects/test_snowflake.py::TestSnowflake::test_table_literal", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/dialects/test_snowflake.py::TestSnowflake::test_try_cast", "tests/dialects/test_snowflake.py::TestSnowflake::test_user_defined_functions", "tests/dialects/test_snowflake.py::TestSnowflake::test_values" ]
[]
MIT License
18,425
1,213
[ "sqlglot/dialects/snowflake.py", "sqlglot/expressions.py", "sqlglot/generator.py", "sqlglot/parser.py", "sqlglot/tokens.py" ]
tobymao__sqlglot-3477
846d5cd2fe85f836f5ad888e783fedfa2108d579
2024-05-14 20:24:16
b7ce9c3018661f7b375bfe9d354d01728e0d37cc
diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py index 5837d2ff..f7559854 100644 --- a/sqlglot/dialects/duckdb.py +++ b/sqlglot/dialects/duckdb.py @@ -5,6 +5,7 @@ import typing as t from sqlglot import exp, generator, parser, tokens, transforms from sqlglot.dialects.dialect import ( Dialect, + JSON_EXTRACT_TYPE, NormalizationStrategy, approx_count_distinct_sql, arg_max_or_min_no_count, @@ -156,6 +157,13 @@ def _unix_to_time_sql(self: DuckDB.Generator, expression: exp.UnixToTime) -> str return self.func("TO_TIMESTAMP", exp.Div(this=timestamp, expression=exp.func("POW", 10, scale))) +def _arrow_json_extract_sql(self: DuckDB.Generator, expression: JSON_EXTRACT_TYPE) -> str: + arrow_sql = arrow_json_extract_sql(self, expression) + if not expression.same_parent and isinstance(expression.parent, exp.Binary): + arrow_sql = self.wrap(arrow_sql) + return arrow_sql + + class DuckDB(Dialect): NULL_ORDERING = "nulls_are_last" SUPPORTS_USER_DEFINED_TYPES = False @@ -367,6 +375,7 @@ class DuckDB(Dialect): CAN_IMPLEMENT_ARRAY_ANY = True SUPPORTS_TO_NUMBER = False COPY_HAS_INTO_KEYWORD = False + STAR_EXCEPT = "EXCLUDE" TRANSFORMS = { **generator.Generator.TRANSFORMS, @@ -405,8 +414,8 @@ class DuckDB(Dialect): exp.IntDiv: lambda self, e: self.binary(e, "//"), exp.IsInf: rename_func("ISINF"), exp.IsNan: rename_func("ISNAN"), - exp.JSONExtract: arrow_json_extract_sql, - exp.JSONExtractScalar: arrow_json_extract_sql, + exp.JSONExtract: _arrow_json_extract_sql, + exp.JSONExtractScalar: _arrow_json_extract_sql, exp.JSONFormat: _json_format_sql, exp.LogicalOr: rename_func("BOOL_OR"), exp.LogicalAnd: rename_func("BOOL_AND"), @@ -498,8 +507,6 @@ class DuckDB(Dialect): exp.DataType.Type.TIMESTAMP_NS: "TIMESTAMP_NS", } - STAR_MAPPING = {**generator.Generator.STAR_MAPPING, "except": "EXCLUDE"} - UNWRAPPED_INTERVAL_VALUES = (exp.Literal, exp.Paren) # DuckDB doesn't generally support CREATE TABLE .. properties diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py index 84bf8a4c..9625faad 100644 --- a/sqlglot/dialects/snowflake.py +++ b/sqlglot/dialects/snowflake.py @@ -737,7 +737,6 @@ class Snowflake(Dialect): "NCHAR VARYING": TokenType.VARCHAR, "PUT": TokenType.COMMAND, "REMOVE": TokenType.COMMAND, - "RENAME": TokenType.REPLACE, "RM": TokenType.COMMAND, "SAMPLE": TokenType.TABLE_SAMPLE, "SQL_DOUBLE": TokenType.DOUBLE, @@ -773,6 +772,7 @@ class Snowflake(Dialect): STRUCT_DELIMITER = ("(", ")") COPY_PARAMS_ARE_WRAPPED = False COPY_PARAMS_EQ_REQUIRED = True + STAR_EXCEPT = "EXCLUDE" TRANSFORMS = { **generator.Generator.TRANSFORMS, @@ -875,11 +875,6 @@ class Snowflake(Dialect): exp.DataType.Type.STRUCT: "OBJECT", } - STAR_MAPPING = { - "except": "EXCLUDE", - "replace": "RENAME", - } - PROPERTIES_LOCATION = { **generator.Generator.PROPERTIES_LOCATION, exp.SetProperty: exp.Properties.Location.UNSUPPORTED, diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index b3cd4ceb..cf4be6e1 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -3820,7 +3820,7 @@ class Where(Expression): class Star(Expression): - arg_types = {"except": False, "replace": False} + arg_types = {"except": False, "replace": False, "rename": False} @property def name(self) -> str: diff --git a/sqlglot/generator.py b/sqlglot/generator.py index 66eb23a0..418f093b 100644 --- a/sqlglot/generator.py +++ b/sqlglot/generator.py @@ -353,6 +353,9 @@ class Generator(metaclass=_Generator): # Whether the conditional TRY(expression) function is supported TRY_SUPPORTED = True + # The keyword to use when generating a star projection with excluded columns + STAR_EXCEPT = "EXCEPT" + TYPE_MAPPING = { exp.DataType.Type.NCHAR: "CHAR", exp.DataType.Type.NVARCHAR: "VARCHAR", @@ -366,11 +369,6 @@ class Generator(metaclass=_Generator): exp.DataType.Type.ROWVERSION: "VARBINARY", } - STAR_MAPPING = { - "except": "EXCEPT", - "replace": "REPLACE", - } - TIME_PART_SINGULARS = { "MICROSECONDS": "MICROSECOND", "SECONDS": "SECOND", @@ -2308,10 +2306,12 @@ class Generator(metaclass=_Generator): def star_sql(self, expression: exp.Star) -> str: except_ = self.expressions(expression, key="except", flat=True) - except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else "" + except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" replace = self.expressions(expression, key="replace", flat=True) - replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else "" - return f"*{except_}{replace}" + replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" + rename = self.expressions(expression, key="rename", flat=True) + rename = f"{self.seg('RENAME')} ({rename})" if rename else "" + return f"*{except_}{replace}{rename}" def parameter_sql(self, expression: exp.Parameter) -> str: this = self.sql(expression, "this") diff --git a/sqlglot/parser.py b/sqlglot/parser.py index e243fc93..8e227d07 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -713,7 +713,12 @@ class Parser(metaclass=_Parser): TokenType.FALSE: lambda self, _: self.expression(exp.Boolean, this=False), TokenType.SESSION_PARAMETER: lambda self, _: self._parse_session_parameter(), TokenType.STAR: lambda self, _: self.expression( - exp.Star, **{"except": self._parse_except(), "replace": self._parse_replace()} + exp.Star, + **{ + "except": self._parse_star_op("EXCEPT", "EXCLUDE"), + "replace": self._parse_star_op("REPLACE"), + "rename": self._parse_star_op("RENAME"), + }, ), } @@ -5677,23 +5682,14 @@ class Parser(metaclass=_Parser): self._advance(-1) return None - def _parse_except(self) -> t.Optional[t.List[exp.Expression]]: - if not self._match(TokenType.EXCEPT): - return None - if self._match(TokenType.L_PAREN, advance=False): - return self._parse_wrapped_csv(self._parse_column) - - except_column = self._parse_column() - return [except_column] if except_column else None - - def _parse_replace(self) -> t.Optional[t.List[exp.Expression]]: - if not self._match(TokenType.REPLACE): + def _parse_star_op(self, *keywords: str) -> t.Optional[t.List[exp.Expression]]: + if not self._match_texts(keywords): return None if self._match(TokenType.L_PAREN, advance=False): return self._parse_wrapped_csv(self._parse_expression) - replace_expression = self._parse_expression() - return [replace_expression] if replace_expression else None + expression = self._parse_expression() + return [expression] if expression else None def _parse_csv( self, parse_method: t.Callable, sep: TokenType = TokenType.COMMA
Incorrect conversion of SELECT with REPLACE to RENAME for Snowflake **Problem** sqlglot changes `SELECT * REPLACE` to `SELECT * RENAME` for Snowflake. They have very different meanings: `rename` renames columns for output, while `replace` replaces an existing column with an expression. Also, the query fails on Snowflake, because `rename` expects only `name as name` while `replace` is given in form `expr as name`. **Fully reproducible code snippet** ``` >>> import sqlglot >>> sqlglot.parse_one("SELECT * REPLACE (CAST(col AS TEXT) AS scol) FROM (SELECT 1 AS col, '2' as scol)", read="snowflake").sql("snowflake") "SELECT * RENAME (CAST(col AS TEXT) AS scol) FROM (SELECT 1 AS col, '2' AS scol)" ``` This query fails on Snowflake with errors `Syntax error: unexpected '('` and `syntax error line 1 at position 35 unexpected 'AS'.` **Official Documentation** https://docs.snowflake.com/en/sql-reference/sql/select
tobymao/sqlglot
diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py index c4417783..6eb23939 100644 --- a/tests/dialects/test_duckdb.py +++ b/tests/dialects/test_duckdb.py @@ -271,6 +271,14 @@ class TestDuckDB(Validator): self.validate_identity( "SELECT * FROM x LEFT JOIN UNNEST(y)", "SELECT * FROM x LEFT JOIN UNNEST(y) ON TRUE" ) + self.validate_identity( + "SELECT JSON_EXTRACT_STRING(c, '$.k1') = 'v1'", + "SELECT (c ->> '$.k1') = 'v1'", + ) + self.validate_identity( + "SELECT JSON_EXTRACT(c, '$.k1') = 'v1'", + "SELECT (c -> '$.k1') = 'v1'", + ) self.validate_identity( """SELECT '{"foo": [1, 2, 3]}' -> 'foo' -> 0""", """SELECT '{"foo": [1, 2, 3]}' -> '$.foo' -> '$[0]'""", diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py index 11d26fd9..2d1a1302 100644 --- a/tests/dialects/test_snowflake.py +++ b/tests/dialects/test_snowflake.py @@ -90,6 +90,7 @@ WHERE self.validate_identity("SELECT CONVERT_TIMEZONE('UTC', 'America/Los_Angeles', col)") self.validate_identity("ALTER TABLE a SWAP WITH b") self.validate_identity("SELECT MATCH_CONDITION") + self.validate_identity("SELECT * REPLACE (CAST(col AS TEXT) AS scol) FROM t") self.validate_identity( "MERGE INTO my_db AS ids USING (SELECT new_id FROM my_model WHERE NOT col IS NULL) AS new_ids ON ids.type = new_ids.type AND ids.source = new_ids.source WHEN NOT MATCHED THEN INSERT VALUES (new_ids.new_id)" ) @@ -230,6 +231,38 @@ WHERE "CAST(x AS NCHAR VARYING)", "CAST(x AS VARCHAR)", ) + self.validate_identity( + "CREATE OR REPLACE TEMPORARY TABLE x (y NUMBER IDENTITY(0, 1))", + "CREATE OR REPLACE TEMPORARY TABLE x (y DECIMAL(38, 0) AUTOINCREMENT START 0 INCREMENT 1)", + ) + self.validate_identity( + "CREATE TEMPORARY TABLE x (y NUMBER AUTOINCREMENT(0, 1))", + "CREATE TEMPORARY TABLE x (y DECIMAL(38, 0) AUTOINCREMENT START 0 INCREMENT 1)", + ) + self.validate_identity( + "CREATE TABLE x (y NUMBER IDENTITY START 0 INCREMENT 1)", + "CREATE TABLE x (y DECIMAL(38, 0) AUTOINCREMENT START 0 INCREMENT 1)", + ) + self.validate_identity( + "ALTER TABLE foo ADD COLUMN id INT identity(1, 1)", + "ALTER TABLE foo ADD COLUMN id INT AUTOINCREMENT START 1 INCREMENT 1", + ) + self.validate_identity( + "SELECT DAYOFWEEK('2016-01-02T23:39:20.123-07:00'::TIMESTAMP)", + "SELECT DAYOFWEEK(CAST('2016-01-02T23:39:20.123-07:00' AS TIMESTAMP))", + ) + self.validate_identity( + "SELECT * FROM xxx WHERE col ilike '%Don''t%'", + "SELECT * FROM xxx WHERE col ILIKE '%Don\\'t%'", + ) + self.validate_identity( + "SELECT * EXCLUDE a, b FROM xxx", + "SELECT * EXCLUDE (a), b FROM xxx", + ) + self.validate_identity( + "SELECT * RENAME a AS b, c AS d FROM xxx", + "SELECT * RENAME (a AS b), c AS d FROM xxx", + ) self.validate_all( "OBJECT_CONSTRUCT_KEEP_NULL('key_1', 'one', 'key_2', NULL)", @@ -550,60 +583,12 @@ WHERE }, ) self.validate_all( - "CREATE OR REPLACE TEMPORARY TABLE x (y NUMBER IDENTITY(0, 1))", - write={ - "snowflake": "CREATE OR REPLACE TEMPORARY TABLE x (y DECIMAL(38, 0) AUTOINCREMENT START 0 INCREMENT 1)", - }, - ) - self.validate_all( - "CREATE TEMPORARY TABLE x (y NUMBER AUTOINCREMENT(0, 1))", - write={ - "snowflake": "CREATE TEMPORARY TABLE x (y DECIMAL(38, 0) AUTOINCREMENT START 0 INCREMENT 1)", - }, - ) - self.validate_all( - "CREATE TABLE x (y NUMBER IDENTITY START 0 INCREMENT 1)", - write={ - "snowflake": "CREATE TABLE x (y DECIMAL(38, 0) AUTOINCREMENT START 0 INCREMENT 1)", - }, - ) - self.validate_all( - "ALTER TABLE foo ADD COLUMN id INT identity(1, 1)", - write={ - "snowflake": "ALTER TABLE foo ADD COLUMN id INT AUTOINCREMENT START 1 INCREMENT 1", - }, - ) - self.validate_all( - "SELECT DAYOFWEEK('2016-01-02T23:39:20.123-07:00'::TIMESTAMP)", - write={ - "snowflake": "SELECT DAYOFWEEK(CAST('2016-01-02T23:39:20.123-07:00' AS TIMESTAMP))", - }, - ) - self.validate_all( - "SELECT * FROM xxx WHERE col ilike '%Don''t%'", - write={ - "snowflake": "SELECT * FROM xxx WHERE col ILIKE '%Don\\'t%'", - }, - ) - self.validate_all( - "SELECT * EXCLUDE a, b FROM xxx", - write={ - "snowflake": "SELECT * EXCLUDE (a), b FROM xxx", - }, - ) - self.validate_all( - "SELECT * RENAME a AS b, c AS d FROM xxx", - write={ - "snowflake": "SELECT * RENAME (a AS b), c AS d FROM xxx", - }, - ) - self.validate_all( - "SELECT * EXCLUDE (a, b) RENAME (c AS d, E AS F) FROM xxx", + "SELECT * EXCLUDE (a, b) REPLACE (c AS d, E AS F) FROM xxx", read={ "duckdb": "SELECT * EXCLUDE (a, b) REPLACE (c AS d, E AS F) FROM xxx", }, write={ - "snowflake": "SELECT * EXCLUDE (a, b) RENAME (c AS d, E AS F) FROM xxx", + "snowflake": "SELECT * EXCLUDE (a, b) REPLACE (c AS d, E AS F) FROM xxx", "duckdb": "SELECT * EXCLUDE (a, b) REPLACE (c AS d, E AS F) FROM xxx", }, )
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 5 }
23.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@846d5cd2fe85f836f5ad888e783fedfa2108d579#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake" ]
[]
[ "tests/dialects/test_duckdb.py::TestDuckDB::test_array", "tests/dialects/test_duckdb.py::TestDuckDB::test_array_index", "tests/dialects/test_duckdb.py::TestDuckDB::test_bool_or", "tests/dialects/test_duckdb.py::TestDuckDB::test_cast", "tests/dialects/test_duckdb.py::TestDuckDB::test_encode_decode", "tests/dialects/test_duckdb.py::TestDuckDB::test_isinf", "tests/dialects/test_duckdb.py::TestDuckDB::test_isnan", "tests/dialects/test_duckdb.py::TestDuckDB::test_parameter_token", "tests/dialects/test_duckdb.py::TestDuckDB::test_rename_table", "tests/dialects/test_duckdb.py::TestDuckDB::test_sample", "tests/dialects/test_duckdb.py::TestDuckDB::test_time", "tests/dialects/test_duckdb.py::TestDuckDB::test_timestamps_with_units", "tests/dialects/test_snowflake.py::TestSnowflake::test_copy", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_describe_table", "tests/dialects/test_snowflake.py::TestSnowflake::test_flatten", "tests/dialects/test_snowflake.py::TestSnowflake::test_historical_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_snowflake.py::TestSnowflake::test_minus", "tests/dialects/test_snowflake.py::TestSnowflake::test_null_treatment", "tests/dialects/test_snowflake.py::TestSnowflake::test_parse_like_any", "tests/dialects/test_snowflake.py::TestSnowflake::test_querying_semi_structured_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_replace", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_substr", "tests/dialects/test_snowflake.py::TestSnowflake::test_sample", "tests/dialects/test_snowflake.py::TestSnowflake::test_semi_structured_types", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_columns", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_imported_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_objects", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_primary_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_schemas", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_sequences", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_tables", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_unique_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_users", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_views", "tests/dialects/test_snowflake.py::TestSnowflake::test_staged_files", "tests/dialects/test_snowflake.py::TestSnowflake::test_storage_integration", "tests/dialects/test_snowflake.py::TestSnowflake::test_stored_procedures", "tests/dialects/test_snowflake.py::TestSnowflake::test_swap", "tests/dialects/test_snowflake.py::TestSnowflake::test_table_literal", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/dialects/test_snowflake.py::TestSnowflake::test_try_cast", "tests/dialects/test_snowflake.py::TestSnowflake::test_user_defined_functions", "tests/dialects/test_snowflake.py::TestSnowflake::test_values" ]
[]
MIT License
18,431
2,076
[ "sqlglot/dialects/duckdb.py", "sqlglot/dialects/snowflake.py", "sqlglot/expressions.py", "sqlglot/generator.py", "sqlglot/parser.py" ]
tobymao__sqlglot-3478
846d5cd2fe85f836f5ad888e783fedfa2108d579
2024-05-14 20:38:07
b7ce9c3018661f7b375bfe9d354d01728e0d37cc
diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py index 5837d2ff..b7f372d6 100644 --- a/sqlglot/dialects/duckdb.py +++ b/sqlglot/dialects/duckdb.py @@ -5,6 +5,7 @@ import typing as t from sqlglot import exp, generator, parser, tokens, transforms from sqlglot.dialects.dialect import ( Dialect, + JSON_EXTRACT_TYPE, NormalizationStrategy, approx_count_distinct_sql, arg_max_or_min_no_count, @@ -156,6 +157,13 @@ def _unix_to_time_sql(self: DuckDB.Generator, expression: exp.UnixToTime) -> str return self.func("TO_TIMESTAMP", exp.Div(this=timestamp, expression=exp.func("POW", 10, scale))) +def _arrow_json_extract_sql(self: DuckDB.Generator, expression: JSON_EXTRACT_TYPE) -> str: + arrow_sql = arrow_json_extract_sql(self, expression) + if not expression.same_parent and isinstance(expression.parent, exp.Binary): + arrow_sql = self.wrap(arrow_sql) + return arrow_sql + + class DuckDB(Dialect): NULL_ORDERING = "nulls_are_last" SUPPORTS_USER_DEFINED_TYPES = False @@ -405,8 +413,8 @@ class DuckDB(Dialect): exp.IntDiv: lambda self, e: self.binary(e, "//"), exp.IsInf: rename_func("ISINF"), exp.IsNan: rename_func("ISNAN"), - exp.JSONExtract: arrow_json_extract_sql, - exp.JSONExtractScalar: arrow_json_extract_sql, + exp.JSONExtract: _arrow_json_extract_sql, + exp.JSONExtractScalar: _arrow_json_extract_sql, exp.JSONFormat: _json_format_sql, exp.LogicalOr: rename_func("BOOL_OR"), exp.LogicalAnd: rename_func("BOOL_AND"),
Inconsistent conversion of JSON functions for DuckDB **Problem** Based on [the official DuckDB documentation](https://duckdb.org/docs/extensions/json.html#json-extraction-functions): > Note that the equality comparison operator (`=`) has a higher precedence than the `->` JSON extract operator. Therefore, surround the uses of the `->` operator with parentheses when making equality comparisons. That means `json_extract` (`->`) and `json_extract_string` (`->>`) can not be converted as is if they are surrounded by a higher priority operation. **Fully reproducible code snippet** ``` import sqlglot >>> print(sqlglot.parse_one("""select (json_extract_string(c, '$.k1') = 'v1') and (json_extract_string(c, '$.k2') = 'v2') from (select '{"k1": "v1", "k2": "v2"}' as c);""", read="duckdb").sql("duckdb")) SELECT (c ->> '$.k1' = 'v1') AND (c ->> '$.k2' = 'v2') FROM (SELECT '{"k1": "v1", "k2": "v2"}' AS c) >>> print(sqlglot.parse_one("""select json_extract_string(c, '$.k1') = 'v1' and json_extract_string(c, '$.k2') = 'v2' from (select '{"k1": "v1", "k2": "v2"}' as c);""", read="duckdb").sql("duckdb")) SELECT c ->> '$.k1' = 'v1' AND c ->> '$.k2' = 'v2' FROM (SELECT '{"k1": "v1", "k2": "v2"}' AS c) ``` DuckDB: ``` D SELECT (c ->> '$.k1' = 'v1') AND (c ->> '$.k2' = 'v2') FROM (SELECT '{"k1": "v1", "k2": "v2"}' AS c); ┌───────────────────────────────────────────────────────┐ │ (((c ->> '$.k1') = 'v1') AND ((c ->> '$.k2') = 'v2')) │ │ boolean │ ├───────────────────────────────────────────────────────┤ │ true │ └───────────────────────────────────────────────────────┘ D SELECT c ->> '$.k1' = 'v1' AND c ->> '$.k2' = 'v2' FROM (SELECT '{"k1": "v1", "k2": "v2"}' AS c); Error: Conversion Error: Could not convert string '{"k1": "v1", "k2": "v2"}' to BOOL ``` **Official Documentation** https://duckdb.org/docs/extensions/json.html#json-extraction-functions
tobymao/sqlglot
diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py index c4417783..6eb23939 100644 --- a/tests/dialects/test_duckdb.py +++ b/tests/dialects/test_duckdb.py @@ -271,6 +271,14 @@ class TestDuckDB(Validator): self.validate_identity( "SELECT * FROM x LEFT JOIN UNNEST(y)", "SELECT * FROM x LEFT JOIN UNNEST(y) ON TRUE" ) + self.validate_identity( + "SELECT JSON_EXTRACT_STRING(c, '$.k1') = 'v1'", + "SELECT (c ->> '$.k1') = 'v1'", + ) + self.validate_identity( + "SELECT JSON_EXTRACT(c, '$.k1') = 'v1'", + "SELECT (c -> '$.k1') = 'v1'", + ) self.validate_identity( """SELECT '{"foo": [1, 2, 3]}' -> 'foo' -> 0""", """SELECT '{"foo": [1, 2, 3]}' -> '$.foo' -> '$[0]'""",
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
23.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "ruff", "mypy" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@846d5cd2fe85f836f5ad888e783fedfa2108d579#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb" ]
[]
[ "tests/dialects/test_duckdb.py::TestDuckDB::test_array", "tests/dialects/test_duckdb.py::TestDuckDB::test_array_index", "tests/dialects/test_duckdb.py::TestDuckDB::test_bool_or", "tests/dialects/test_duckdb.py::TestDuckDB::test_cast", "tests/dialects/test_duckdb.py::TestDuckDB::test_encode_decode", "tests/dialects/test_duckdb.py::TestDuckDB::test_isinf", "tests/dialects/test_duckdb.py::TestDuckDB::test_isnan", "tests/dialects/test_duckdb.py::TestDuckDB::test_parameter_token", "tests/dialects/test_duckdb.py::TestDuckDB::test_rename_table", "tests/dialects/test_duckdb.py::TestDuckDB::test_sample", "tests/dialects/test_duckdb.py::TestDuckDB::test_time", "tests/dialects/test_duckdb.py::TestDuckDB::test_timestamps_with_units" ]
[]
MIT License
18,432
457
[ "sqlglot/dialects/duckdb.py" ]
Marker-Inc-Korea__AutoRAG-442
fd066ef4657315f81eca9112c2ede7edaa0c8507
2024-05-15 11:25:47
2d776d5f3af18dda4fe2f384573144328b8b048f
diff --git a/autorag/nodes/passagefilter/threshold_cutoff.py b/autorag/nodes/passagefilter/threshold_cutoff.py index 1369344..3fb4b60 100644 --- a/autorag/nodes/passagefilter/threshold_cutoff.py +++ b/autorag/nodes/passagefilter/threshold_cutoff.py @@ -1,5 +1,7 @@ from typing import List, Tuple +import numpy as np + from autorag.nodes.passagefilter.base import passage_filter_node @@ -43,11 +45,20 @@ def threshold_cutoff_pure(scores_list: List[float], Default is False. :return: Indices to remain at the contents """ - if reverse: - remain_indices = [i for i, score in enumerate(scores_list) if score <= threshold] - default_index = scores_list.index(min(scores_list)) + if isinstance(scores_list, np.ndarray): + if reverse: + remain_indices = np.where(scores_list <= threshold)[0] + default_index = np.argmin(scores_list) + else: + remain_indices = np.where(scores_list >= threshold)[0] + default_index = np.argmax(scores_list) else: - remain_indices = [i for i, score in enumerate(scores_list) if score >= threshold] - default_index = scores_list.index(max(scores_list)) + if reverse: + remain_indices = [i for i, score in enumerate(scores_list) if score <= threshold] + default_index = scores_list.index(min(scores_list)) + else: + remain_indices = [i for i, score in enumerate(scores_list) if score >= threshold] + default_index = scores_list.index(max(scores_list)) - return remain_indices if remain_indices else [default_index] + return remain_indices.tolist() if isinstance(remain_indices, np.ndarray) and remain_indices.size > 0 else \ + remain_indices if remain_indices else [default_index]
[HotFix] [threshold cutoff] Error when the input 'scores_list' is np.ndarray. In the running of AutoRAG, the input of `threshold_cutoff_pure` function's parameter `scores_list` is np.ndarray, it occurs error. ```python def threshold_cutoff_pure(scores_list: List[float], threshold: float, reverse: bool = False) -> List[int]: if reverse: remain_indices = [i for i, score in enumerate(scores_list) if score <= threshold] default_index = scores_list.index(min(scores_list)) # error here else: remain_indices = [i for i, score in enumerate(scores_list) if score >= threshold] default_index = scores_list.index(max(scores_list)) # error here return remain_indices if remain_indices else [default_index] ```
Marker-Inc-Korea/AutoRAG
diff --git a/tests/autorag/nodes/passagefilter/test_threshold_cutoff.py b/tests/autorag/nodes/passagefilter/test_threshold_cutoff.py index 59d1d91..868b827 100644 --- a/tests/autorag/nodes/passagefilter/test_threshold_cutoff.py +++ b/tests/autorag/nodes/passagefilter/test_threshold_cutoff.py @@ -1,3 +1,5 @@ +import numpy as np + from autorag.nodes.passagefilter import threshold_cutoff from tests.autorag.nodes.passagefilter.test_passage_filter_base import queries_example, contents_example, \ scores_example, ids_example, base_passage_filter_test, project_dir, previous_result, base_passage_filter_node_test @@ -19,6 +21,16 @@ def test_threshold_cutoff_reverse(): assert contents[0] == ["NomaDamas is Great Team", "havertz is suck at soccer"] +def test_threshold_cutoff_numpy(): + original_cutoff = threshold_cutoff.__wrapped__ + numpy_scores = np.array([[0.1, 0.8, 0.1, 0.5], [0.1, 0.2, 0.7, 0.3]]) + contents, ids, scores = original_cutoff( + queries_example, contents_example, numpy_scores, ids_example, threshold=0.6) + base_passage_filter_test(contents, ids, scores) + assert scores == [[0.8], [0.7]] + assert contents == [["Paris is the capital of France."], ["Newjeans has 5 members."]] + + def test_threshold_cutoff_node(): result_df = threshold_cutoff( project_dir=project_dir, previous_result=previous_result, threshold=0.9)
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
absl-py==2.2.1 accelerate==1.5.2 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 altair==5.5.0 annotated-types==0.7.0 anyio==4.9.0 appdirs==1.4.4 asgiref==3.8.1 asttokens==3.0.0 async-timeout==4.0.3 attrs==25.3.0 -e git+https://github.com/Marker-Inc-Korea/AutoRAG.git@fd066ef4657315f81eca9112c2ede7edaa0c8507#egg=AutoRAG backoff==2.2.1 banks==2.1.0 bcrypt==4.3.0 beautifulsoup4==4.13.3 bert-score==0.3.13 blinker==1.9.0 bm25s==0.2.10 build==1.2.2.post1 cachetools==5.5.2 cbor==1.0.0 certifi==2025.1.31 charset-normalizer==3.4.1 chroma-hnswlib==0.7.6 chromadb==0.6.3 click==8.1.8 cloudpickle==3.1.1 cohere==5.14.0 colorama==0.4.6 coloredlogs==15.0.1 comm==0.2.2 contourpy==1.3.0 cramjam==2.9.1 cycler==0.12.1 dask==2024.8.0 dask-expr==1.1.10 dataclasses-json==0.6.7 datasets==3.5.0 decorator==5.2.1 Deprecated==1.2.18 dill==0.3.8 dirtyjson==1.0.8 diskcache==5.6.3 distro==1.9.0 durationpy==0.9 eval_type_backport==0.2.2 evaluate==0.4.3 exceptiongroup==1.2.2 executing==2.2.0 fastapi==0.115.12 fastavro==1.10.0 fastparquet==2024.11.0 filelock==3.18.0 filetype==1.2.0 FlagEmbedding==1.3.4 flatbuffers==25.2.10 fonttools==4.56.0 frozenlist==1.5.0 fsspec==2024.12.0 gitdb==4.0.12 GitPython==3.1.44 google-auth==2.38.0 googleapis-common-protos==1.69.2 greenlet==3.1.1 griffe==1.7.1 grpcio==1.71.0 guidance==0.2.1 guidance-stitch==0.1.4 h11==0.14.0 httpcore==1.0.7 httptools==0.6.4 httpx==0.28.1 httpx-sse==0.4.0 huggingface-hub==0.30.0 humanfriendly==10.0 idna==3.10 ijson==3.3.0 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 inscriptis==2.6.0 ipython==8.18.1 ipywidgets==8.1.5 ir_datasets==0.5.10 jedi==0.19.2 Jinja2==3.1.6 jiter==0.9.0 joblib==1.4.2 jsonpatch==1.33 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyterlab_widgets==3.0.13 kiwipiepy==0.20.4 kiwipiepy_model==0.20.0 kiwisolver==1.4.7 kubernetes==32.0.1 langchain==0.3.22 langchain-community==0.3.20 langchain-core==0.3.49 langchain-openai==0.3.11 langchain-text-splitters==0.3.7 langsmith==0.3.19 llama-cloud==0.1.17 llama-cloud-services==0.6.9 llama-index==0.12.27 llama-index-agent-openai==0.4.6 llama-index-cli==0.4.1 llama-index-core==0.12.27 llama-index-embeddings-huggingface==0.5.2 llama-index-embeddings-openai==0.3.1 llama-index-indices-managed-llama-cloud==0.6.9 llama-index-llms-huggingface==0.4.2 llama-index-llms-openai==0.3.29 llama-index-llms-openai-like==0.3.4 llama-index-multi-modal-llms-openai==0.4.3 llama-index-program-openai==0.3.1 llama-index-question-gen-openai==0.3.0 llama-index-readers-file==0.4.7 llama-index-readers-llama-parse==0.4.0 llama-index-retrievers-bm25==0.5.2 llama-parse==0.6.4.post1 llguidance==0.6.31 locket==1.0.0 lxml==5.3.1 lz4==4.4.3 markdown-it-py==3.0.0 MarkupSafe==3.0.2 marshmallow==3.26.1 matplotlib==3.9.4 matplotlib-inline==0.1.7 mdurl==0.1.2 mmh3==5.1.0 monotonic==1.6 mpmath==1.3.0 msgpack==1.1.0 multidict==6.2.0 multiprocess==0.70.16 mypy-extensions==1.0.0 narwhals==1.32.0 nest-asyncio==1.6.0 networkx==3.2.1 nltk==3.9.1 numpy==2.0.2 nvidia-cublas-cu12==12.4.5.8 nvidia-cuda-cupti-cu12==12.4.127 nvidia-cuda-nvrtc-cu12==12.4.127 nvidia-cuda-runtime-cu12==12.4.127 nvidia-cudnn-cu12==9.1.0.70 nvidia-cufft-cu12==11.2.1.3 nvidia-curand-cu12==10.3.5.147 nvidia-cusolver-cu12==11.6.1.9 nvidia-cusparse-cu12==12.3.1.170 nvidia-cusparselt-cu12==0.6.2 nvidia-nccl-cu12==2.21.5 nvidia-nvjitlink-cu12==12.4.127 nvidia-nvtx-cu12==12.4.127 oauthlib==3.2.2 onnxruntime==1.19.2 openai==1.69.0 opentelemetry-api==1.31.1 opentelemetry-exporter-otlp-proto-common==1.31.1 opentelemetry-exporter-otlp-proto-grpc==1.31.1 opentelemetry-instrumentation==0.52b1 opentelemetry-instrumentation-asgi==0.52b1 opentelemetry-instrumentation-fastapi==0.52b1 opentelemetry-proto==1.31.1 opentelemetry-sdk==1.31.1 opentelemetry-semantic-conventions==0.52b1 opentelemetry-util-http==0.52b1 ordered-set==4.1.0 orjson==3.10.16 overrides==7.7.0 packaging==24.2 pandas==2.2.3 parso==0.8.4 partd==1.4.2 peft==0.15.1 pexpect==4.9.0 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 portalocker==3.1.1 posthog==3.23.0 prompt_toolkit==3.0.50 propcache==0.3.1 protobuf==5.29.4 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 pydantic==2.11.1 pydantic-settings==2.8.1 pydantic_core==2.33.0 pydeck==0.9.1 Pygments==2.19.1 pyparsing==3.2.3 pypdf==5.4.0 PyPika==0.48.9 pyproject_hooks==1.2.0 PyStemmer==2.2.0.3 pytest==8.3.5 python-dateutil==2.9.0.post0 python-dotenv==1.1.0 pytz==2025.2 PyYAML==6.0.2 ragas==0.2.14 rank-bm25==0.2.2 ray==2.44.1 referencing==0.36.2 regex==2024.11.6 requests==2.32.3 requests-oauthlib==2.0.0 requests-toolbelt==1.0.0 rich==14.0.0 rouge_score==0.1.2 rpds-py==0.24.0 rsa==4.9 sacrebleu==2.5.1 safetensors==0.5.3 scikit-learn==1.6.1 scipy==1.13.1 sentence-transformers==4.0.1 sentencepiece==0.2.0 shellingham==1.5.4 six==1.17.0 smmap==5.0.2 sniffio==1.3.1 soupsieve==2.6 SQLAlchemy==2.0.40 stack-data==0.6.3 starlette==0.46.1 streamlit==1.44.0 striprtf==0.0.26 swifter==1.4.0 sympy==1.13.1 tabulate==0.9.0 tenacity==9.0.0 text-generation==0.7.0 threadpoolctl==3.6.0 tiktoken==0.9.0 tokenizers==0.21.1 tokenlog==0.0.2 toml==0.10.2 tomli==2.2.1 toolz==1.0.0 torch==2.6.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 transformers==4.50.3 trec-car-tools==2.6 triton==3.2.0 typer==0.15.2 types-requests==2.32.0.20250328 typing-inspect==0.9.0 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 unlzw3==0.2.3 urllib3==2.3.0 uvicorn==0.34.0 uvloop==0.21.0 warc3-wet==0.2.5 warc3-wet-clueweb09==0.2.5 watchdog==6.0.0 watchfiles==1.0.4 wcwidth==0.2.13 websocket-client==1.8.0 websockets==15.0.1 widgetsnbextension==4.0.13 wrapt==1.17.2 xxhash==3.5.0 yarl==1.18.3 zipp==3.21.0 zlib-state==0.1.9 zstandard==0.23.0
name: AutoRAG channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - absl-py==2.2.1 - accelerate==1.5.2 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - altair==5.5.0 - annotated-types==0.7.0 - anyio==4.9.0 - appdirs==1.4.4 - asgiref==3.8.1 - asttokens==3.0.0 - async-timeout==4.0.3 - attrs==25.3.0 - autorag==0.1.11 - backoff==2.2.1 - banks==2.1.0 - bcrypt==4.3.0 - beautifulsoup4==4.13.3 - bert-score==0.3.13 - blinker==1.9.0 - bm25s==0.2.10 - build==1.2.2.post1 - cachetools==5.5.2 - cbor==1.0.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - chroma-hnswlib==0.7.6 - chromadb==0.6.3 - click==8.1.8 - cloudpickle==3.1.1 - cohere==5.14.0 - colorama==0.4.6 - coloredlogs==15.0.1 - comm==0.2.2 - contourpy==1.3.0 - cramjam==2.9.1 - cycler==0.12.1 - dask==2024.8.0 - dask-expr==1.1.10 - dataclasses-json==0.6.7 - datasets==3.5.0 - decorator==5.2.1 - deprecated==1.2.18 - dill==0.3.8 - dirtyjson==1.0.8 - diskcache==5.6.3 - distro==1.9.0 - durationpy==0.9 - eval-type-backport==0.2.2 - evaluate==0.4.3 - exceptiongroup==1.2.2 - executing==2.2.0 - fastapi==0.115.12 - fastavro==1.10.0 - fastparquet==2024.11.0 - filelock==3.18.0 - filetype==1.2.0 - flagembedding==1.3.4 - flatbuffers==25.2.10 - fonttools==4.56.0 - frozenlist==1.5.0 - fsspec==2024.12.0 - gitdb==4.0.12 - gitpython==3.1.44 - google-auth==2.38.0 - googleapis-common-protos==1.69.2 - greenlet==3.1.1 - griffe==1.7.1 - grpcio==1.71.0 - guidance==0.2.1 - guidance-stitch==0.1.4 - h11==0.14.0 - httpcore==1.0.7 - httptools==0.6.4 - httpx==0.28.1 - httpx-sse==0.4.0 - huggingface-hub==0.30.0 - humanfriendly==10.0 - idna==3.10 - ijson==3.3.0 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - inscriptis==2.6.0 - ipython==8.18.1 - ipywidgets==8.1.5 - ir-datasets==0.5.10 - jedi==0.19.2 - jinja2==3.1.6 - jiter==0.9.0 - joblib==1.4.2 - jsonpatch==1.33 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyterlab-widgets==3.0.13 - kiwipiepy==0.20.4 - kiwipiepy-model==0.20.0 - kiwisolver==1.4.7 - kubernetes==32.0.1 - langchain==0.3.22 - langchain-community==0.3.20 - langchain-core==0.3.49 - langchain-openai==0.3.11 - langchain-text-splitters==0.3.7 - langsmith==0.3.19 - llama-cloud==0.1.17 - llama-cloud-services==0.6.9 - llama-index==0.12.27 - llama-index-agent-openai==0.4.6 - llama-index-cli==0.4.1 - llama-index-core==0.12.27 - llama-index-embeddings-huggingface==0.5.2 - llama-index-embeddings-openai==0.3.1 - llama-index-indices-managed-llama-cloud==0.6.9 - llama-index-llms-huggingface==0.4.2 - llama-index-llms-openai==0.3.29 - llama-index-llms-openai-like==0.3.4 - llama-index-multi-modal-llms-openai==0.4.3 - llama-index-program-openai==0.3.1 - llama-index-question-gen-openai==0.3.0 - llama-index-readers-file==0.4.7 - llama-index-readers-llama-parse==0.4.0 - llama-index-retrievers-bm25==0.5.2 - llama-parse==0.6.4.post1 - llguidance==0.6.31 - locket==1.0.0 - lxml==5.3.1 - lz4==4.4.3 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - marshmallow==3.26.1 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mdurl==0.1.2 - mmh3==5.1.0 - monotonic==1.6 - mpmath==1.3.0 - msgpack==1.1.0 - multidict==6.2.0 - multiprocess==0.70.16 - mypy-extensions==1.0.0 - narwhals==1.32.0 - nest-asyncio==1.6.0 - networkx==3.2.1 - nltk==3.9.1 - numpy==2.0.2 - nvidia-cublas-cu12==12.4.5.8 - nvidia-cuda-cupti-cu12==12.4.127 - nvidia-cuda-nvrtc-cu12==12.4.127 - nvidia-cuda-runtime-cu12==12.4.127 - nvidia-cudnn-cu12==9.1.0.70 - nvidia-cufft-cu12==11.2.1.3 - nvidia-curand-cu12==10.3.5.147 - nvidia-cusolver-cu12==11.6.1.9 - nvidia-cusparse-cu12==12.3.1.170 - nvidia-cusparselt-cu12==0.6.2 - nvidia-nccl-cu12==2.21.5 - nvidia-nvjitlink-cu12==12.4.127 - nvidia-nvtx-cu12==12.4.127 - oauthlib==3.2.2 - onnxruntime==1.19.2 - openai==1.69.0 - opentelemetry-api==1.31.1 - opentelemetry-exporter-otlp-proto-common==1.31.1 - opentelemetry-exporter-otlp-proto-grpc==1.31.1 - opentelemetry-instrumentation==0.52b1 - opentelemetry-instrumentation-asgi==0.52b1 - opentelemetry-instrumentation-fastapi==0.52b1 - opentelemetry-proto==1.31.1 - opentelemetry-sdk==1.31.1 - opentelemetry-semantic-conventions==0.52b1 - opentelemetry-util-http==0.52b1 - ordered-set==4.1.0 - orjson==3.10.16 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - parso==0.8.4 - partd==1.4.2 - peft==0.15.1 - pexpect==4.9.0 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - portalocker==3.1.1 - posthog==3.23.0 - prompt-toolkit==3.0.50 - propcache==0.3.1 - protobuf==5.29.4 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pydantic==2.11.1 - pydantic-core==2.33.0 - pydantic-settings==2.8.1 - pydeck==0.9.1 - pygments==2.19.1 - pyparsing==3.2.3 - pypdf==5.4.0 - pypika==0.48.9 - pyproject-hooks==1.2.0 - pystemmer==2.2.0.3 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-dotenv==1.1.0 - pytz==2025.2 - pyyaml==6.0.2 - ragas==0.2.14 - rank-bm25==0.2.2 - ray==2.44.1 - referencing==0.36.2 - regex==2024.11.6 - requests==2.32.3 - requests-oauthlib==2.0.0 - requests-toolbelt==1.0.0 - rich==14.0.0 - rouge-score==0.1.2 - rpds-py==0.24.0 - rsa==4.9 - sacrebleu==2.5.1 - safetensors==0.5.3 - scikit-learn==1.6.1 - scipy==1.13.1 - sentence-transformers==4.0.1 - sentencepiece==0.2.0 - shellingham==1.5.4 - six==1.17.0 - smmap==5.0.2 - sniffio==1.3.1 - soupsieve==2.6 - sqlalchemy==2.0.40 - stack-data==0.6.3 - starlette==0.46.1 - streamlit==1.44.0 - striprtf==0.0.26 - swifter==1.4.0 - sympy==1.13.1 - tabulate==0.9.0 - tenacity==9.0.0 - text-generation==0.7.0 - threadpoolctl==3.6.0 - tiktoken==0.9.0 - tokenizers==0.21.1 - tokenlog==0.0.2 - toml==0.10.2 - tomli==2.2.1 - toolz==1.0.0 - torch==2.6.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - transformers==4.50.3 - trec-car-tools==2.6 - triton==3.2.0 - typer==0.15.2 - types-requests==2.32.0.20250328 - typing-extensions==4.13.0 - typing-inspect==0.9.0 - typing-inspection==0.4.0 - tzdata==2025.2 - unlzw3==0.2.3 - urllib3==2.3.0 - uvicorn==0.34.0 - uvloop==0.21.0 - warc3-wet==0.2.5 - warc3-wet-clueweb09==0.2.5 - watchdog==6.0.0 - watchfiles==1.0.4 - wcwidth==0.2.13 - websocket-client==1.8.0 - websockets==15.0.1 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xxhash==3.5.0 - yarl==1.18.3 - zipp==3.21.0 - zlib-state==0.1.9 - zstandard==0.23.0 prefix: /opt/conda/envs/AutoRAG
[ "tests/autorag/nodes/passagefilter/test_threshold_cutoff.py::test_threshold_cutoff_numpy" ]
[]
[ "tests/autorag/nodes/passagefilter/test_threshold_cutoff.py::test_threshold_cutoff", "tests/autorag/nodes/passagefilter/test_threshold_cutoff.py::test_threshold_cutoff_reverse", "tests/autorag/nodes/passagefilter/test_threshold_cutoff.py::test_threshold_cutoff_node" ]
[]
Apache License 2.0
18,434
433
[ "autorag/nodes/passagefilter/threshold_cutoff.py" ]
tobymao__sqlglot-3482
e3ff67b0327a217a0523f82e6a11940feab1a8ac
2024-05-15 12:00:18
b7ce9c3018661f7b375bfe9d354d01728e0d37cc
diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py index 0d2cfc1a..d3845255 100644 --- a/sqlglot/dialects/bigquery.py +++ b/sqlglot/dialects/bigquery.py @@ -156,7 +156,7 @@ def _build_date(args: t.List) -> exp.Date | exp.DateFromParts: def _build_to_hex(args: t.List) -> exp.Hex | exp.MD5: # TO_HEX(MD5(..)) is common in BigQuery, so it's parsed into MD5 to simplify its transpilation arg = seq_get(args, 0) - return exp.MD5(this=arg.this) if isinstance(arg, exp.MD5Digest) else exp.Hex(this=arg) + return exp.MD5(this=arg.this) if isinstance(arg, exp.MD5Digest) else exp.LowerHex(this=arg) def _array_contains_sql(self: BigQuery.Generator, expression: exp.ArrayContains) -> str: @@ -245,6 +245,8 @@ class BigQuery(Dialect): # https://cloud.google.com/bigquery/docs/querying-partitioned-tables#query_an_ingestion-time_partitioned_table PSEUDOCOLUMNS = {"_PARTITIONTIME", "_PARTITIONDATE"} + HEX_LOWERCASE = True + def normalize_identifier(self, expression: E) -> E: if isinstance(expression, exp.Identifier): parent = expression.parent @@ -603,7 +605,8 @@ class BigQuery(Dialect): ), exp.GenerateSeries: rename_func("GENERATE_ARRAY"), exp.GroupConcat: rename_func("STRING_AGG"), - exp.Hex: rename_func("TO_HEX"), + exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))), + exp.LowerHex: rename_func("TO_HEX"), exp.If: if_sql(false_value="NULL"), exp.ILike: no_ilike_sql, exp.IntDiv: rename_func("DIV"), diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py index 1a2b0976..7fb3be82 100644 --- a/sqlglot/dialects/dialect.py +++ b/sqlglot/dialects/dialect.py @@ -290,6 +290,22 @@ class Dialect(metaclass=_Dialect): ) SELECT c FROM y; """ + HEX_LOWERCASE = False + """ + Different dialect, `HEX` function will producing a different string, some are in + lowercase, other are in uppercase. HEX_LOWERCASE property can determine the case + of the string which current dialect use. `HEX` can be wrapped by an additional + lower or upper function to convert the output to exact dialect. + For example, + `SELECT TO_HEX(x)`; + in Bigquery will be rewritten as the following one in Presto and Trino + `SELECT LOWER(TO_HEX(x))`; + In another example, + `SELECT TO_HEX(x)`; + in Presto will be rewritten as the following one in Bigquery + `SELECT UPPER(TO_HEX(x))`; + """ + # --- Autofilled --- tokenizer_class = Tokenizer diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py index 66daba15..f18f8de9 100644 --- a/sqlglot/dialects/mysql.py +++ b/sqlglot/dialects/mysql.py @@ -805,6 +805,9 @@ class MySQL(Dialect): exp.DataType.Type.TIMESTAMPLTZ, } + def dpipe_sql(self, expression: exp.DPipe) -> str: + return self.func("CONCAT", *expression.flatten()) + def extract_sql(self, expression: exp.Extract) -> str: unit = expression.name if unit and unit.lower() == "epoch": diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py index b6e44cb9..63f6c034 100644 --- a/sqlglot/dialects/presto.py +++ b/sqlglot/dialects/presto.py @@ -385,6 +385,9 @@ class Presto(Dialect): "ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator") ), exp.Hex: rename_func("TO_HEX"), + exp.LowerHex: lambda self, e: self.func( + "LOWER", self.func("TO_HEX", self.sql(e, "this")) + ), exp.If: if_sql(), exp.ILike: no_ilike_sql, exp.Initcap: _initcap_sql, diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index cf4be6e1..8fc8b41f 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -5197,6 +5197,10 @@ class Hex(Func): pass +class LowerHex(Hex): + pass + + class Xor(Connector, Func): arg_types = {"this": False, "expression": False, "expressions": False} diff --git a/sqlglot/generator.py b/sqlglot/generator.py index 418f093b..e21e16ee 100644 --- a/sqlglot/generator.py +++ b/sqlglot/generator.py @@ -1302,6 +1302,19 @@ class Generator(metaclass=_Generator): text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}" return text + def hex_sql(self, expression: exp.Hex) -> str: + text = self.func("HEX", self.sql(expression, "this")) + if self.dialect.HEX_LOWERCASE: + text = self.func("LOWER", text) + + return text + + def lowerhex_sql(self, expression: exp.LowerHex) -> str: + text = self.func("HEX", self.sql(expression, "this")) + if not self.dialect.HEX_LOWERCASE: + text = self.func("LOWER", text) + return text + def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: input_format = self.sql(expression, "input_format") input_format = f"INPUTFORMAT {input_format}" if input_format else "" diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 8e227d07..1729ac47 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -61,6 +61,23 @@ def build_logarithm(args: t.List, dialect: Dialect) -> exp.Func: return (exp.Ln if dialect.parser_class.LOG_DEFAULTS_TO_LN else exp.Log)(this=this) +def build_hex(args: t.List, dialect: Dialect) -> exp.Hex | exp.LowerHex: + arg = seq_get(args, 0) + return exp.LowerHex(this=arg) if dialect.HEX_LOWERCASE else exp.Hex(this=arg) + + +def build_lower(args: t.List) -> exp.Lower | exp.Hex: + # LOWER(HEX(..)) can be simplified to LowerHex to simplify its transpilation + arg = seq_get(args, 0) + return exp.LowerHex(this=arg.this) if isinstance(arg, exp.Hex) else exp.Lower(this=arg) + + +def build_upper(args: t.List) -> exp.Upper | exp.Hex: + # UPPER(HEX(..)) can be simplified to Hex to simplify its transpilation + arg = seq_get(args, 0) + return exp.Hex(this=arg.this) if isinstance(arg, exp.Hex) else exp.Upper(this=arg) + + def build_extract_json_with_path(expr_type: t.Type[E]) -> t.Callable[[t.List, Dialect], E]: def _builder(args: t.List, dialect: Dialect) -> E: expression = expr_type( @@ -148,6 +165,9 @@ class Parser(metaclass=_Parser): length=exp.Literal.number(10), ), "VAR_MAP": build_var_map, + "LOWER": build_lower, + "UPPER": build_upper, + "HEX": build_hex, } NO_PAREN_FUNCTIONS = {
[bug] pgsql to mysql special character || Semantic mismatch **Before you file an issue** - Make sure you specify the "read" dialect eg. `parse_one(sql, read="spark")` - Make sure you specify the "write" dialect eg. `ast.sql(dialect="duckdb")` - Check if the issue still exists on main **Fully reproducible code snippet** Please include a fully reproducible code snippet or the input sql, dialect, and expected output. **Official Documentation** Please include links to official SQL documentation related to your issue.
tobymao/sqlglot
diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py index 9df897c1..c5a7bad3 100644 --- a/tests/dialects/test_bigquery.py +++ b/tests/dialects/test_bigquery.py @@ -631,6 +631,58 @@ LANGUAGE js AS "mysql": "SELECT DATE_SUB(TIMESTAMP('2008-12-25 15:30:00+00'), INTERVAL 10 MINUTE)", }, ) + self.validate_all( + "LOWER(TO_HEX(x))", + write={ + "": "LOWER(HEX(x))", + "bigquery": "TO_HEX(x)", + "presto": "LOWER(TO_HEX(x))", + "trino": "LOWER(TO_HEX(x))", + "clickhouse": "LOWER(HEX(x))", + "hive": "LOWER(HEX(x))", + "spark": "LOWER(HEX(x))", + }, + ) + self.validate_all( + "TO_HEX(x)", + read={ + "": "LOWER(HEX(x))", + "presto": "LOWER(TO_HEX(x))", + "trino": "LOWER(TO_HEX(x))", + "clickhouse": "LOWER(HEX(x))", + "hive": "LOWER(HEX(x))", + "spark": "LOWER(HEX(x))", + }, + write={ + "": "LOWER(HEX(x))", + "bigquery": "TO_HEX(x)", + "presto": "LOWER(TO_HEX(x))", + "trino": "LOWER(TO_HEX(x))", + "clickhouse": "LOWER(HEX(x))", + "hive": "LOWER(HEX(x))", + "spark": "LOWER(HEX(x))", + }, + ) + self.validate_all( + "UPPER(TO_HEX(x))", + read={ + "": "HEX(x)", + "presto": "TO_HEX(x)", + "trino": "TO_HEX(x)", + "clickhouse": "HEX(x)", + "hive": "HEX(x)", + "spark": "HEX(x)", + }, + write={ + "": "HEX(x)", + "bigquery": "UPPER(TO_HEX(x))", + "presto": "TO_HEX(x)", + "trino": "TO_HEX(x)", + "clickhouse": "HEX(x)", + "hive": "HEX(x)", + "spark": "HEX(x)", + }, + ) self.validate_all( "MD5(x)", read={ @@ -653,6 +705,9 @@ LANGUAGE js AS read={ "duckdb": "SELECT MD5(some_string)", "spark": "SELECT MD5(some_string)", + "clickhouse": "SELECT LOWER(HEX(MD5(some_string)))", + "presto": "SELECT LOWER(TO_HEX(MD5(some_string)))", + "trino": "SELECT LOWER(TO_HEX(MD5(some_string)))", }, write={ "": "SELECT MD5(some_string)", diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py index 7bd17290..84fb3c27 100644 --- a/tests/dialects/test_mysql.py +++ b/tests/dialects/test_mysql.py @@ -610,6 +610,16 @@ class TestMySQL(Validator): ) def test_mysql(self): + self.validate_all( + "SELECT CONCAT('11', '22')", + read={ + "postgres": "SELECT '11' || '22'", + }, + write={ + "mysql": "SELECT CONCAT('11', '22')", + "postgres": "SELECT CONCAT('11', '22')", + }, + ) self.validate_all( "SELECT department, GROUP_CONCAT(name) AS employee_names FROM data GROUP BY department", read={ diff --git a/tests/test_expressions.py b/tests/test_expressions.py index 550f1fc2..1395b24e 100644 --- a/tests/test_expressions.py +++ b/tests/test_expressions.py @@ -674,7 +674,9 @@ class TestExpressions(unittest.TestCase): self.assertIsInstance(parse_one("STANDARD_HASH('hello', 'sha256')"), exp.StandardHash) self.assertIsInstance(parse_one("DATE(foo)"), exp.Date) self.assertIsInstance(parse_one("HEX(foo)"), exp.Hex) - self.assertIsInstance(parse_one("TO_HEX(foo)", read="bigquery"), exp.Hex) + self.assertIsInstance(parse_one("LOWER(HEX(foo))"), exp.LowerHex) + self.assertIsInstance(parse_one("TO_HEX(foo)", read="bigquery"), exp.LowerHex) + self.assertIsInstance(parse_one("UPPER(TO_HEX(foo))", read="bigquery"), exp.Hex) self.assertIsInstance(parse_one("TO_HEX(MD5(foo))", read="bigquery"), exp.MD5) self.assertIsInstance(parse_one("TRANSFORM(a, b)", read="spark"), exp.Transform) self.assertIsInstance(parse_one("ADD_MONTHS(a, b)"), exp.AddMonths)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 7 }
23.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 py4j==0.10.9.7 Pygments==2.19.1 pyspark==3.5.5 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@e3ff67b0327a217a0523f82e6a11940feab1a8ac#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - py4j==0.10.9.7 - pygments==2.19.1 - pyspark==3.5.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery", "tests/dialects/test_mysql.py::TestMySQL::test_mysql", "tests/test_expressions.py::TestExpressions::test_functions" ]
[]
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_errors", "tests/dialects/test_bigquery.py::TestBigQuery::test_group_concat", "tests/dialects/test_bigquery.py::TestBigQuery::test_json_object", "tests/dialects/test_bigquery.py::TestBigQuery::test_merge", "tests/dialects/test_bigquery.py::TestBigQuery::test_mod", "tests/dialects/test_bigquery.py::TestBigQuery::test_models", "tests/dialects/test_bigquery.py::TestBigQuery::test_pushdown_cte_column_names", "tests/dialects/test_bigquery.py::TestBigQuery::test_remove_precision_parameterized_types", "tests/dialects/test_bigquery.py::TestBigQuery::test_rename_table", "tests/dialects/test_bigquery.py::TestBigQuery::test_user_defined_functions", "tests/dialects/test_bigquery.py::TestBigQuery::test_warnings", "tests/dialects/test_mysql.py::TestMySQL::test_bits_literal", "tests/dialects/test_mysql.py::TestMySQL::test_canonical_functions", "tests/dialects/test_mysql.py::TestMySQL::test_convert", "tests/dialects/test_mysql.py::TestMySQL::test_date_format", "tests/dialects/test_mysql.py::TestMySQL::test_ddl", "tests/dialects/test_mysql.py::TestMySQL::test_escape", "tests/dialects/test_mysql.py::TestMySQL::test_hexadecimal_literal", "tests/dialects/test_mysql.py::TestMySQL::test_identity", "tests/dialects/test_mysql.py::TestMySQL::test_introducers", "tests/dialects/test_mysql.py::TestMySQL::test_is_null", "tests/dialects/test_mysql.py::TestMySQL::test_json_object", "tests/dialects/test_mysql.py::TestMySQL::test_match_against", "tests/dialects/test_mysql.py::TestMySQL::test_monthname", "tests/dialects/test_mysql.py::TestMySQL::test_mysql_time", "tests/dialects/test_mysql.py::TestMySQL::test_safe_div", "tests/dialects/test_mysql.py::TestMySQL::test_set_variable", "tests/dialects/test_mysql.py::TestMySQL::test_show_columns", "tests/dialects/test_mysql.py::TestMySQL::test_show_db_like_or_where_sql", "tests/dialects/test_mysql.py::TestMySQL::test_show_engine", "tests/dialects/test_mysql.py::TestMySQL::test_show_errors", "tests/dialects/test_mysql.py::TestMySQL::test_show_events", "tests/dialects/test_mysql.py::TestMySQL::test_show_grants", "tests/dialects/test_mysql.py::TestMySQL::test_show_index", "tests/dialects/test_mysql.py::TestMySQL::test_show_like_or_where", "tests/dialects/test_mysql.py::TestMySQL::test_show_name", "tests/dialects/test_mysql.py::TestMySQL::test_show_processlist", "tests/dialects/test_mysql.py::TestMySQL::test_show_profile", "tests/dialects/test_mysql.py::TestMySQL::test_show_replica_status", "tests/dialects/test_mysql.py::TestMySQL::test_show_simple", "tests/dialects/test_mysql.py::TestMySQL::test_show_tables", "tests/dialects/test_mysql.py::TestMySQL::test_string_literals", "tests/dialects/test_mysql.py::TestMySQL::test_timestamp_trunc", "tests/dialects/test_mysql.py::TestMySQL::test_types", "tests/test_expressions.py::TestExpressions::test_alias", "tests/test_expressions.py::TestExpressions::test_alias_column_names", "tests/test_expressions.py::TestExpressions::test_alias_or_name", "tests/test_expressions.py::TestExpressions::test_arg_deletion", "tests/test_expressions.py::TestExpressions::test_arg_key", "tests/test_expressions.py::TestExpressions::test_assert_is", "tests/test_expressions.py::TestExpressions::test_column", "tests/test_expressions.py::TestExpressions::test_comment_alias", "tests/test_expressions.py::TestExpressions::test_convert", "tests/test_expressions.py::TestExpressions::test_ctes", "tests/test_expressions.py::TestExpressions::test_data_type_builder", "tests/test_expressions.py::TestExpressions::test_depth", "tests/test_expressions.py::TestExpressions::test_eq", "tests/test_expressions.py::TestExpressions::test_expand", "tests/test_expressions.py::TestExpressions::test_find", "tests/test_expressions.py::TestExpressions::test_find_all", "tests/test_expressions.py::TestExpressions::test_find_ancestor", "tests/test_expressions.py::TestExpressions::test_function_building", "tests/test_expressions.py::TestExpressions::test_function_normalizer", "tests/test_expressions.py::TestExpressions::test_hash", "tests/test_expressions.py::TestExpressions::test_identifier", "tests/test_expressions.py::TestExpressions::test_is_negative", "tests/test_expressions.py::TestExpressions::test_is_star", "tests/test_expressions.py::TestExpressions::test_is_type", "tests/test_expressions.py::TestExpressions::test_iter", "tests/test_expressions.py::TestExpressions::test_named_selects", "tests/test_expressions.py::TestExpressions::test_properties_from_dict", "tests/test_expressions.py::TestExpressions::test_rename_table", "tests/test_expressions.py::TestExpressions::test_replace", "tests/test_expressions.py::TestExpressions::test_replace_placeholders", "tests/test_expressions.py::TestExpressions::test_replace_tables", "tests/test_expressions.py::TestExpressions::test_root", "tests/test_expressions.py::TestExpressions::test_selects", "tests/test_expressions.py::TestExpressions::test_set_meta", "tests/test_expressions.py::TestExpressions::test_set_metadata", "tests/test_expressions.py::TestExpressions::test_sql", "tests/test_expressions.py::TestExpressions::test_table", "tests/test_expressions.py::TestExpressions::test_table_name", "tests/test_expressions.py::TestExpressions::test_text", "tests/test_expressions.py::TestExpressions::test_to_column", "tests/test_expressions.py::TestExpressions::test_to_dot", "tests/test_expressions.py::TestExpressions::test_to_interval", "tests/test_expressions.py::TestExpressions::test_to_table", "tests/test_expressions.py::TestExpressions::test_transform_multiple_children", "tests/test_expressions.py::TestExpressions::test_transform_no_infinite_recursion", "tests/test_expressions.py::TestExpressions::test_transform_node_removal", "tests/test_expressions.py::TestExpressions::test_transform_simple", "tests/test_expressions.py::TestExpressions::test_transform_with_arguments", "tests/test_expressions.py::TestExpressions::test_transform_with_parent_mutation", "tests/test_expressions.py::TestExpressions::test_union", "tests/test_expressions.py::TestExpressions::test_unit", "tests/test_expressions.py::TestExpressions::test_unnest", "tests/test_expressions.py::TestExpressions::test_values", "tests/test_expressions.py::TestExpressions::test_walk" ]
[]
MIT License
18,435
2,008
[ "sqlglot/dialects/bigquery.py", "sqlglot/dialects/dialect.py", "sqlglot/dialects/mysql.py", "sqlglot/dialects/presto.py", "sqlglot/expressions.py", "sqlglot/generator.py", "sqlglot/parser.py" ]
nilearn__nilearn-4414
2c0452e5267cedabf035569c27753473372e16ea
2024-05-16 21:54:11
c39ca5ec29463a262b635a47aadfb5dfc19cafb6
github-actions[bot]: 👋 @michellewang Thanks for creating a PR! Until this PR is ready for review, you can include the [WIP] tag in its title, or leave it as a github draft. Please make sure it is compliant with our [contributing guidelines](https://nilearn.github.io/stable/development.html#contribution-guidelines). In particular, be sure it checks the boxes listed below. - [ ] PR has an interpretable title. - [ ] PR links to Github issue with mention `Closes #XXXX` (see our documentation on [PR structure](https://nilearn.github.io/stable/development.html#pr-structure)) - [ ] Code is PEP8-compliant (see our documentation on [coding style](https://nilearn.github.io/stable/development.html#coding-style)) - [ ] Changelog or what's new entry in `doc/changes/latest.rst` (see our documentation on [PR structure](https://nilearn.github.io/stable/development.html#pr-structure)) For new features: - [ ] There is at least one unit test per new function / class (see our documentation on [testing](https://nilearn.github.io/stable/development.html#tests)) - [ ] The new feature is demoed in at least one relevant example. For bug fixes: - [ ] There is at least one test that would fail under the original bug conditions. We will review it as quick as possible, feel free to ping us with questions if needed. codecov[bot]: ## [Codecov](https://app.codecov.io/gh/nilearn/nilearn/pull/4414?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 68.73%. Comparing base [(`abb80ff`)](https://app.codecov.io/gh/nilearn/nilearn/commit/abb80ffb7aab132d096c2a8bc987e75040bacbfc?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn) to head [(`612a901`)](https://app.codecov.io/gh/nilearn/nilearn/pull/4414?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn). > Report is 70 commits behind head on main. <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #4414 +/- ## =========================================== - Coverage 91.85% 68.73% -23.12% =========================================== Files 144 143 -1 Lines 16419 16641 +222 Branches 3434 3222 -212 =========================================== - Hits 15082 11439 -3643 - Misses 792 4753 +3961 + Partials 545 449 -96 ``` | [Flag](https://app.codecov.io/gh/nilearn/nilearn/pull/4414/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn) | Coverage Δ | | |---|---|---| | [macos-latest_3.11_test_plotting](https://app.codecov.io/gh/nilearn/nilearn/pull/4414/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn) | `?` | | | [ubuntu-latest_3.10_test_plotting](https://app.codecov.io/gh/nilearn/nilearn/pull/4414/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn) | `?` | | | [ubuntu-latest_3.8_test_min](https://app.codecov.io/gh/nilearn/nilearn/pull/4414/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn) | `68.73% <100.00%> (?)` | | Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn#carryforward-flags-in-the-pull-request-comment) to find out more. </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/nilearn/nilearn/pull/4414?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=nilearn). michellewang: @man-shu it is now!
diff --git a/nilearn/glm/first_level/first_level.py b/nilearn/glm/first_level/first_level.py index b70d5f8e0..1b27ce2b3 100644 --- a/nilearn/glm/first_level/first_level.py +++ b/nilearn/glm/first_level/first_level.py @@ -1292,7 +1292,15 @@ def first_level_from_bids( dataset_path = Path(dataset_path).absolute() - kwargs_load_confounds = _check_kwargs_load_confounds(**kwargs) + kwargs_load_confounds, remaining_kwargs = _check_kwargs_load_confounds( + **kwargs + ) + + if len(remaining_kwargs) > 0: + raise RuntimeError( + "Unknown keyword arguments. Keyword arguments should start with " + f"`confounds_` prefix: {remaining_kwargs}" + ) if drift_model is not None and kwargs_load_confounds is not None: if "high_pass" in kwargs_load_confounds.get("strategy"): @@ -1903,18 +1911,18 @@ def _check_kwargs_load_confounds(**kwargs): } if kwargs.get("confounds_strategy") is None: - return None - - kwargs_load_confounds = { - key: ( - defaults[key] - if f"confounds_{key}" not in kwargs - else kwargs[f"confounds_{key}"] - ) - for key in defaults - } + return None, kwargs + + remaining_kwargs = kwargs.copy() + kwargs_load_confounds = {} + for key in defaults: + confounds_key = f"confounds_{key}" + if confounds_key in kwargs: + kwargs_load_confounds[key] = remaining_kwargs.pop(confounds_key) + else: + kwargs_load_confounds[key] = defaults[key] - return kwargs_load_confounds + return kwargs_load_confounds, remaining_kwargs def _make_bids_files_filter(
[ENH] Throw error when extra kwargs are given to `glm.first_level.first_level_from_bids` ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe your proposed enhancement in detail. `nilearn.glm.first_level.first_level_from_bids` takes kwargs, and passes kwargs that have the `confounds_` prefix to another function. However, the remaining kwargs are not checked and nothing happens if for example the confound kwargs are not given correctly (e.g. with typo `confound_` instead of `confounds_`). I think it would be nice/useful to throw a runtime error or something when that happens (first mentioned in PR #4352). Would be happy to work on this too. ### Benefits to the change Better debugging when invalid/unknown kwargs are given. ### Pseudocode for the new behavior, if applicable _No response_
nilearn/nilearn
diff --git a/doc/changes/latest.rst b/doc/changes/latest.rst index 308946c1b..4f65a8636 100644 --- a/doc/changes/latest.rst +++ b/doc/changes/latest.rst @@ -28,3 +28,5 @@ Changes - :bdg-dark:`Code` Implement argument ``sample_mask`` for :meth:`nilearn.maskers.MultiNiftiMasker.transform_imgs` (:gh:`4273` by `Rémi Gau`_). - :bdg-dark:`Code` Remove the unused arguments ``upper_cutoff`` and ``exclude_zeros`` for :func:`nilearn.masking.compute_multi_background_mask` (:gh:`4273` by `Rémi Gau`_). + +- :bdg-dark:`Code` Throw error in :func:`nilearn.glm.first_level.first_level_from_bids` if unknown ``kwargs`` are passed (:gh:`4414` by `Michelle Wang`_). diff --git a/nilearn/glm/tests/test_first_level.py b/nilearn/glm/tests/test_first_level.py index 1b4702499..6310e39be 100644 --- a/nilearn/glm/tests/test_first_level.py +++ b/nilearn/glm/tests/test_first_level.py @@ -1958,6 +1958,23 @@ def test_first_level_from_bids_no_subject(tmp_path): ) +def test_first_level_from_bids_unused_kwargs(tmp_path): + """Check that unused kwargs are properly handled.""" + bids_path = create_fake_bids_dataset( + base_dir=tmp_path, n_sub=1, n_ses=1, tasks=["main"], n_runs=[2] + ) + with pytest.raises(RuntimeError, match="Unknown keyword arguments"): + # wrong kwarg name `confound_strategy` (wrong) + # instead of `confounds_strategy` (correct) + first_level_from_bids( + dataset_path=bids_path, + task_label="main", + space_label="MNI", + slice_time_ref=None, + confound_strategy="motion", + ) + + def test_check_run_tables_errors(): # check high level wrapper keeps behavior with pytest.raises(ValueError, match="len.* does not match len.*"):
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 astor==0.8.1 babel==2.17.0 beautifulsoup4==4.13.3 black==25.1.0 blacken-docs==1.19.1 cachetools==5.5.2 certifi==2025.1.31 cfgv==3.4.0 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 codespell==2.4.1 colorama==0.4.6 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 flake8==7.2.0 flake8-docstrings==1.7.0 flake8-functions==0.0.8 flake8-use-fstring==1.4 flynt==1.0.2 fonttools==4.56.0 furo==2024.8.6 identify==2.6.9 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 isort==6.0.1 Jinja2==3.1.6 joblib==1.4.2 kaleido==0.2.1 kiwisolver==1.4.7 latexcodec==3.0.0 lxml==5.3.1 markdown-it-py==3.0.0 MarkupSafe==3.0.2 matplotlib==3.9.4 mccabe==0.7.0 mdit-py-plugins==0.4.2 mdurl==0.1.2 memory-profiler==0.61.0 mr-proper==0.0.7 mypy-extensions==1.0.0 myst-parser==3.0.1 narwhals==1.32.0 nibabel==5.3.2 -e git+https://github.com/nilearn/nilearn.git@2c0452e5267cedabf035569c27753473372e16ea#egg=nilearn nodeenv==1.9.1 numpy==2.0.2 numpydoc==1.8.0 packaging==24.2 pandas==2.2.3 pathspec==0.12.1 pillow==11.1.0 platformdirs==4.3.7 plotly==6.0.1 pluggy==1.5.0 pre_commit==4.2.0 psutil==7.0.0 pybtex==0.24.0 pybtex-docutils==1.0.3 pycodestyle==2.13.0 pydocstyle==6.3.0 pyflakes==3.3.1 Pygments==2.19.1 pyparsing==3.2.3 pyproject-api==1.9.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 requests==2.32.3 ruamel.yaml==0.18.10 ruamel.yaml.clib==0.2.12 scikit-learn==1.6.1 scipy==1.13.1 six==1.17.0 snowballstemmer==2.2.0 soupsieve==2.6 Sphinx==7.4.7 sphinx-basic-ng==1.0.0b2 sphinx-copybutton==0.5.2 sphinx-gallery==0.19.0 sphinx_design==0.6.1 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-bibtex==2.6.3 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 sphinxext-opengraph==0.9.1 stdlib-list==0.11.1 tabulate==0.9.0 threadpoolctl==3.6.0 tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 virtualenv==20.29.3 zipp==3.21.0
name: nilearn channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - astor==0.8.1 - babel==2.17.0 - beautifulsoup4==4.13.3 - black==25.1.0 - blacken-docs==1.19.1 - cachetools==5.5.2 - certifi==2025.1.31 - cfgv==3.4.0 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - codespell==2.4.1 - colorama==0.4.6 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - flake8==7.2.0 - flake8-docstrings==1.7.0 - flake8-functions==0.0.8 - flake8-use-fstring==1.4 - flynt==1.0.2 - fonttools==4.56.0 - furo==2024.8.6 - identify==2.6.9 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - isort==6.0.1 - jinja2==3.1.6 - joblib==1.4.2 - kaleido==0.2.1 - kiwisolver==1.4.7 - latexcodec==3.0.0 - lxml==5.3.1 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - matplotlib==3.9.4 - mccabe==0.7.0 - mdit-py-plugins==0.4.2 - mdurl==0.1.2 - memory-profiler==0.61.0 - mr-proper==0.0.7 - mypy-extensions==1.0.0 - myst-parser==3.0.1 - narwhals==1.32.0 - nibabel==5.3.2 - nilearn==0.10.5.dev24+g2c0452e52 - nodeenv==1.9.1 - numpy==2.0.2 - numpydoc==1.8.0 - packaging==24.2 - pandas==2.2.3 - pathspec==0.12.1 - pillow==11.1.0 - platformdirs==4.3.7 - plotly==6.0.1 - pluggy==1.5.0 - pre-commit==4.2.0 - psutil==7.0.0 - pybtex==0.24.0 - pybtex-docutils==1.0.3 - pycodestyle==2.13.0 - pydocstyle==6.3.0 - pyflakes==3.3.1 - pygments==2.19.1 - pyparsing==3.2.3 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - requests==2.32.3 - ruamel-yaml==0.18.10 - ruamel-yaml-clib==0.2.12 - scikit-learn==1.6.1 - scipy==1.13.1 - six==1.17.0 - snowballstemmer==2.2.0 - soupsieve==2.6 - sphinx==7.4.7 - sphinx-basic-ng==1.0.0b2 - sphinx-copybutton==0.5.2 - sphinx-design==0.6.1 - sphinx-gallery==0.19.0 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-bibtex==2.6.3 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - sphinxext-opengraph==0.9.1 - stdlib-list==0.11.1 - tabulate==0.9.0 - threadpoolctl==3.6.0 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - virtualenv==20.29.3 - zipp==3.21.0 prefix: /opt/conda/envs/nilearn
[ "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_unused_kwargs" ]
[]
[ "nilearn/glm/tests/test_first_level.py::test_high_level_glm_one_run", "nilearn/glm/tests/test_first_level.py::test_explicit_fixed_effects", "nilearn/glm/tests/test_first_level.py::test_explicit_fixed_effects_without_mask", "nilearn/glm/tests/test_first_level.py::test_high_level_glm_with_data", "nilearn/glm/tests/test_first_level.py::test_high_level_glm_with_data_with_mask", "nilearn/glm/tests/test_first_level.py::test_high_level_glm_with_paths", "nilearn/glm/tests/test_first_level.py::test_high_level_glm_null_contrasts", "nilearn/glm/tests/test_first_level.py::test_high_level_glm_different_design_matrices", "nilearn/glm/tests/test_first_level.py::test_high_level_glm_different_design_matrices_formulas", "nilearn/glm/tests/test_first_level.py::test_compute_contrast_num_contrasts", "nilearn/glm/tests/test_first_level.py::test_run_glm_ols", "nilearn/glm/tests/test_first_level.py::test_run_glm_ar1", "nilearn/glm/tests/test_first_level.py::test_run_glm_ar3", "nilearn/glm/tests/test_first_level.py::test_run_glm_errors", "nilearn/glm/tests/test_first_level.py::test_glm_AR_estimates[ar_vals0]", "nilearn/glm/tests/test_first_level.py::test_glm_AR_estimates[ar_vals1]", "nilearn/glm/tests/test_first_level.py::test_glm_AR_estimates[ar_vals2]", "nilearn/glm/tests/test_first_level.py::test_glm_AR_estimates_errors", "nilearn/glm/tests/test_first_level.py::test_glm_random_state[3]", "nilearn/glm/tests/test_first_level.py::test_glm_random_state[random_state1]", "nilearn/glm/tests/test_first_level.py::test_scaling", "nilearn/glm/tests/test_first_level.py::test_fmri_inputs", "nilearn/glm/tests/test_first_level.py::test_fmri_inputs_errors", "nilearn/glm/tests/test_first_level.py::test_first_level_design_creation", "nilearn/glm/tests/test_first_level.py::test_first_level_glm_computation", "nilearn/glm/tests/test_first_level.py::test_first_level_glm_computation_with_memory_caching", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_set_repetition_time_warnings", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_set_repetition_time_errors[not", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_set_repetition_time_errors[-1-ValueError-positive]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_set_slice_timing_ref_warnings", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_set_slice_timing_ref_errors[not", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_set_slice_timing_ref_errors[2-ValueError-between", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_get_metadata_from_derivatives", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_get_RepetitionTime_from_derivatives", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_get_StartTime_from_derivatives", "nilearn/glm/tests/test_first_level.py::test_first_level_contrast_computation", "nilearn/glm/tests/test_first_level.py::test_first_level_contrast_computation_errors", "nilearn/glm/tests/test_first_level.py::test_first_level_with_scaling", "nilearn/glm/tests/test_first_level.py::test_first_level_with_no_signal_scaling", "nilearn/glm/tests/test_first_level.py::test_first_level_residuals", "nilearn/glm/tests/test_first_level.py::test_first_level_residuals_errors", "nilearn/glm/tests/test_first_level.py::test_get_voxelwise_attributes_should_return_as_many_as_design_matrices[shapes0]", "nilearn/glm/tests/test_first_level.py::test_get_voxelwise_attributes_should_return_as_many_as_design_matrices[shapes1]", "nilearn/glm/tests/test_first_level.py::test_first_level_predictions_r_square", "nilearn/glm/tests/test_first_level.py::test_first_level_hrf_model[False-spm]", "nilearn/glm/tests/test_first_level.py::test_first_level_hrf_model[False-spm", "nilearn/glm/tests/test_first_level.py::test_first_level_hrf_model[False-glover]", "nilearn/glm/tests/test_first_level.py::test_first_level_hrf_model[False-<lambda>]", "nilearn/glm/tests/test_first_level.py::test_first_level_hrf_model[True-spm]", "nilearn/glm/tests/test_first_level.py::test_first_level_hrf_model[True-spm", "nilearn/glm/tests/test_first_level.py::test_first_level_hrf_model[True-glover]", "nilearn/glm/tests/test_first_level.py::test_first_level_hrf_model[True-<lambda>]", "nilearn/glm/tests/test_first_level.py::test_glm_sample_mask", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-0-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-0-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-0-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-1-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-1-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-1-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-2-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-2-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-0-2-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-0-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-0-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-0-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-1-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-1-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-1-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-2-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-2-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[MNI-1-2-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-0-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-0-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-0-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-1-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-1-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-1-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-2-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-2-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-0-2-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-0-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-0-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-0-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-1-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-1-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-1-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-2-n_runs0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-2-n_runs1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids[T1w-1-2-n_runs2]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_select_one_run_per_session", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_select_all_runs_of_one_session", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_smoke_test_for_verbose_argument[0]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_smoke_test_for_verbose_argument[1]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_several_labels_per_entity[acq]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_several_labels_per_entity[ce]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_several_labels_per_entity[dir]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_several_labels_per_entity[rec]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_several_labels_per_entity[echo]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_several_labels_per_entity[res]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_several_labels_per_entity[den]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_with_subject_labels", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_no_duplicate_sub_labels", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_input_dataset_path", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_task_label[42-TypeError]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_task_label[$$$-ValueError]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_sub_labels[42-TypeError-must", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_sub_labels[sub_labels1-TypeError-must", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_sub_labels[sub_labels2-TypeError-must", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_space_label[42-TypeError]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_space_label[$$$-ValueError]", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_img_filter[foo-TypeError-'img_filters'", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_img_filter[img_filters1-TypeError-Filters", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_img_filter[img_filters2-ValueError-bids", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_validation_img_filter[img_filters3-ValueError-is", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_too_many_bold_files", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_with_missing_events", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_no_tr", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_no_bold_file", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_with_one_events_missing", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_one_confound_missing", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_all_confounds_missing", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_no_derivatives", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_no_session", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_mismatch_run_index", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_deprecated_slice_time_default", "nilearn/glm/tests/test_first_level.py::test_slice_time_ref_warning_only_when_not_provided", "nilearn/glm/tests/test_first_level.py::test_check_trial_type_warning", "nilearn/glm/tests/test_first_level.py::test_missing_trial_type_column_warning", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_load_confounds", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_load_confounds_warnings", "nilearn/glm/tests/test_first_level.py::test_first_level_from_bids_no_subject", "nilearn/glm/tests/test_first_level.py::test_check_run_tables_errors", "nilearn/glm/tests/test_first_level.py::test_img_table_checks" ]
[]
New BSD License
18,449
464
[ "nilearn/glm/first_level/first_level.py" ]
getsentry__responses-717
83f2e287768de4bdd37ec1c144f56aafe38e29de
2024-05-18 00:49:00
284e7c39cd397e962d36eca491c8d32a3a048365
diff --git a/responses/matchers.py b/responses/matchers.py index c9f7a63..79148e8 100644 --- a/responses/matchers.py +++ b/responses/matchers.py @@ -31,6 +31,21 @@ def _filter_dict_recursively( return filtered_dict +def body_matcher(params: str, *, allow_blank: bool = False) -> Callable[..., Any]: + def match(request: PreparedRequest) -> Tuple[bool, str]: + reason = "" + if isinstance(request.body, bytes): + request_body = request.body.decode("utf-8") + else: + request_body = request.body + valid = True if request_body == params else False + if not valid: + reason = f"request.body doesn't match {params} doesn't match {request_body}" + return valid, reason + + return match + + def urlencoded_params_matcher( params: Optional[Mapping[str, str]], *, allow_blank: bool = False ) -> Callable[..., Any]:
Add capability for matching non json request bodies At work I use responses for mocking api responses for the applications I develop. One of the APIs my application is interacting with does not take input in json format. A call to this api looks like this '''Curl api.company.com/v1/id --data '12345' ''' I would like to create a matcher for non json in the body. I am pretty new to open source and only have some bug fixes and documentation fixes so I would like to contribute this feature back to responses. I think I can code this up from looking at the source. But would responses accept this feature?
getsentry/responses
diff --git a/responses/tests/test_matchers.py b/responses/tests/test_matchers.py index 67d8e83..2775fff 100644 --- a/responses/tests/test_matchers.py +++ b/responses/tests/test_matchers.py @@ -14,6 +14,40 @@ from responses.tests.test_responses import assert_reset from responses.tests.test_responses import assert_response +def test_body_match_get(): + @responses.activate + def run(): + url = "http://example.com" + responses.add( + responses.GET, + url, + body=b"test", + match=[matchers.body_matcher("123456")], + ) + resp = requests.get("http://example.com", data="123456") + assert_response(resp, "test") + + run() + assert_reset() + + +def test_body_match_post(): + @responses.activate + def run(): + url = "http://example.com" + responses.add( + responses.POST, + url, + body=b"test", + match=[matchers.body_matcher("123456")], + ) + resp = requests.post("http://example.com", data="123456") + assert_response(resp, "test") + + run() + assert_reset() + + def test_query_string_matcher(): @responses.activate def run():
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
0.25
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[tests]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup==1.2.2 flake8==7.2.0 idna==3.10 iniconfig==2.1.0 MarkupSafe==3.0.2 mccabe==0.7.0 mypy==1.15.0 mypy-extensions==1.0.0 packaging==24.2 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.2 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest_httpserver==1.1.2 PyYAML==6.0.2 requests==2.32.3 -e git+https://github.com/getsentry/responses.git@83f2e287768de4bdd37ec1c144f56aafe38e29de#egg=responses tomli==2.2.1 tomli_w==1.2.0 types-PyYAML==6.0.12.20250326 types-requests==2.32.0.20250328 typing_extensions==4.13.0 urllib3==2.3.0 Werkzeug==3.1.3
name: responses channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - exceptiongroup==1.2.2 - flake8==7.2.0 - idna==3.10 - iniconfig==2.1.0 - markupsafe==3.0.2 - mccabe==0.7.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-httpserver==1.1.2 - pyyaml==6.0.2 - requests==2.32.3 - tomli==2.2.1 - tomli-w==1.2.0 - types-pyyaml==6.0.12.20250326 - types-requests==2.32.0.20250328 - typing-extensions==4.13.0 - urllib3==2.3.0 - werkzeug==3.1.3 prefix: /opt/conda/envs/responses
[ "responses/tests/test_matchers.py::test_body_match_get", "responses/tests/test_matchers.py::test_body_match_post" ]
[]
[ "responses/tests/test_matchers.py::test_query_string_matcher", "responses/tests/test_matchers.py::test_request_matches_post_params", "responses/tests/test_matchers.py::test_json_params_matcher_not_strict", "responses/tests/test_matchers.py::test_json_params_matcher_not_strict_diff_values", "responses/tests/test_matchers.py::test_failed_matchers_dont_modify_inputs_order_in_error_message", "responses/tests/test_matchers.py::test_json_params_matcher_json_list", "responses/tests/test_matchers.py::test_json_params_matcher_json_list_empty", "responses/tests/test_matchers.py::test_json_params_matcher_body_is_gzipped", "responses/tests/test_matchers.py::test_urlencoded_params_matcher_blank", "responses/tests/test_matchers.py::test_query_params_numbers", "responses/tests/test_matchers.py::test_query_param_matcher_loose", "responses/tests/test_matchers.py::test_query_param_matcher_loose_fail", "responses/tests/test_matchers.py::test_request_matches_empty_body", "responses/tests/test_matchers.py::test_request_matches_params", "responses/tests/test_matchers.py::test_fail_matchers_error", "responses/tests/test_matchers.py::test_multipart_matcher[Old", "responses/tests/test_matchers.py::test_multipart_matcher[\\xacHello", "responses/tests/test_matchers.py::test_multipart_matcher_fail", "responses/tests/test_matchers.py::test_query_string_matcher_raises", "responses/tests/test_matchers.py::test_request_matches_headers", "responses/tests/test_matchers.py::test_request_header_value_mismatch_raises", "responses/tests/test_matchers.py::test_request_headers_missing_raises", "responses/tests/test_matchers.py::test_request_matches_headers_strict_match", "responses/tests/test_matchers.py::test_fragment_identifier_matcher", "responses/tests/test_matchers.py::test_fragment_identifier_matcher_error", "responses/tests/test_matchers.py::test_fragment_identifier_matcher_and_match_querystring", "responses/tests/test_matchers.py::TestHeaderWithRegex::test_request_matches_headers_regex", "responses/tests/test_matchers.py::TestHeaderWithRegex::test_request_matches_headers_regex_strict_match_regex_failed", "responses/tests/test_matchers.py::TestHeaderWithRegex::test_request_matches_headers_regex_strict_match_mismatched_field", "responses/tests/test_matchers.py::TestHeaderWithRegex::test_request_matches_headers_regex_strict_match_mismatched_number", "responses/tests/test_matchers.py::TestHeaderWithRegex::test_request_matches_headers_regex_strict_match_positive" ]
[]
Apache License 2.0
18,458
249
[ "responses/matchers.py" ]
fastavro__fastavro-773
7410c5d75578d7379e133b69c40d19fa3a37d94f
2024-05-21 12:59:57
7410c5d75578d7379e133b69c40d19fa3a37d94f
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/fastavro/fastavro/pull/773?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=fastavro) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 55.05%. Comparing base [(`530c81b`)](https://app.codecov.io/gh/fastavro/fastavro/commit/530c81b33398cb1062f848e0ab296b6efcae9972?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=fastavro) to head [(`68ab16a`)](https://app.codecov.io/gh/fastavro/fastavro/pull/773?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=fastavro). > Report is 2 commits behind head on master. <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## master #773 +/- ## =========================================== - Coverage 98.51% 55.05% -43.47% =========================================== Files 32 32 Lines 2292 2305 +13 =========================================== - Hits 2258 1269 -989 - Misses 34 1036 +1002 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/fastavro/fastavro/pull/773?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=fastavro). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=fastavro). scottbelden: Thanks. Will try to take a look soon
diff --git a/fastavro/io/parser.py b/fastavro/io/parser.py index d518170..a918871 100644 --- a/fastavro/io/parser.py +++ b/fastavro/io/parser.py @@ -35,6 +35,7 @@ from ..schema import extract_record_type class Parser: def __init__(self, schema, named_schemas, action_function): self.schema = schema + self._processed_records = [] self.named_schemas = named_schemas self.action_function = action_function self.stack = self.parse() @@ -45,20 +46,45 @@ class Parser: root.production.insert(0, root) return [root, symbol] + def _process_record(self, schema, default, schema_name=None): + production = [] + + production.append(RecordStart(default=default)) + for field in schema["fields"]: + field_name = field["name"] + production.insert(0, FieldStart(field_name)) + + if schema_name is not None and schema_name in field["type"]: + # this meanns a recursive relationship, so we force a `null` + internal_record = Sequence( + Alternative([Null()], ["null"], default=None), Union() + ) + else: + + internal_record = self._parse( + field["type"], field.get("default", NO_DEFAULT) + ) + + production.insert(0, internal_record) + production.insert(0, FieldEnd()) + production.insert(0, RecordEnd()) + + return production + def _parse(self, schema, default=NO_DEFAULT): record_type = extract_record_type(schema) if record_type == "record": production = [] + schema_name = schema["name"] - production.append(RecordStart(default=default)) - for field in schema["fields"]: - production.insert(0, FieldStart(field["name"])) - production.insert( - 0, self._parse(field["type"], field.get("default", NO_DEFAULT)) + if schema_name not in self._processed_records: + self._processed_records.append(schema_name) + production = self._process_record(schema, default) + else: + production = self._process_record( + schema, default, schema_name=schema_name ) - production.insert(0, FieldEnd()) - production.insert(0, RecordEnd()) seq = Sequence(*production) return seq
RecursionError: maximum recursion depth exceeded when trying to serialize payload with a schema that has recurse relationships using avro json It is not possible to `serialize` payloads with a schema that have recursive relationships using `avro-json`. When using `avro binary` it works as expected. - python version: `all` - fastavro: `1.9.4` To reproduce we use a schema with a recursive relationship: ```python schema = { 'type': 'record', 'name': 'User', 'fields': [ {'name': 'name', 'type': 'string'}, {'name': 'age', 'type': 'long'}, {'name': 'friend', 'type': ['null', 'User'], 'default': None} ] } fastavro.parse_schema(schema=schema) # This works as expected!! data = { "name": "juan", "age": 20, "friend": { "name": "john", "age": 20, }, } ``` Then when trying to serialize: ```python import io import typing import fastavro # Helpers from fastavro def serialize(*, payload: typing.Dict, schema: typing.Dict) -> bytes: file_like_output = io.StringIO() fastavro.json_writer(file_like_output, schema, [payload]) value = file_like_output.getvalue().encode("utf-8") file_like_output.flush() return value serialize(payload=data, schema=schema) ... File "/Users/Projects/.venv/lib/python3.10/site-packages/fastavro/io/parser.py", line 70, in _parse symbols.append(self._parse(candidate_schema)) File "/Users/Projects/.venv/lib/python3.10/site-packages/fastavro/io/parser.py", line 120, in _parse return self._parse(self.named_schemas[record_type]) File "/Users/Projects/.venv/lib/python3.10/site-packages/fastavro/io/parser.py", line 58, in _parse 0, self._parse(field["type"], field.get("default", NO_DEFAULT)) File "/Users/Projects/.venv/lib/python3.10/site-packages/fastavro/io/parser.py", line 106, in _parse return String(default=default) RecursionError: maximum recursion depth exceeded ``` If we try `avro binary` then it works as expected: ```python import io import typing import fastavro def serialize(*, payload: typing.Dict, schema: typing.Dict) -> bytes: file_like_output = io.BytesIO() fastavro.schemaless_writer(file_like_output, schema, payload) value = file_like_output.getvalue() file_like_output.flush() return value print(serialize(payload=data, schema=schema)) >>> b'\x08juan(\x02\x08john(\x00 ```
fastavro/fastavro
diff --git a/tests/test_json.py b/tests/test_json.py index 7680ffe..90bc09d 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -425,6 +425,103 @@ def test_with_dependent_schema(): assert records == new_records +def test_self_one_to_one_relationship(): + """Tests a schema with self dependent schema + https://github.com/fastavro/fastavro/issues/765""" + + schema = { + "type": "record", + "name": "User", + "fields": [ + {"name": "name", "type": "string"}, + {"name": "age", "type": "long"}, + {"name": "friend", "type": ["null", "User"], "default": None}, + ], + } + + records = [ + { + "name": "juan", + "age": 20, + "friend": { + "name": "john", + "age": 30, + "friend": None, + }, + } + ] + + new_records = roundtrip(schema, records) + assert records == new_records + + +def test_multiple_self_one_to_one_relationship(): + """Tests a schema with self dependent schema + https://github.com/fastavro/fastavro/issues/765""" + + schema = { + "type": "record", + "name": "User", + "fields": [ + {"name": "name", "type": "string"}, + {"name": "age", "type": "long"}, + {"name": "friend", "type": ["null", "User"], "default": None}, + {"name": "colleague", "type": ["null", "User"], "default": None}, + ], + } + + records = [ + { + "name": "juan", + "age": 20, + "friend": { + "name": "john", + "age": 30, + "friend": None, + "colleague": None, + }, + "colleague": { + "name": "marcos", + "age": 35, + "friend": None, + "colleague": None, + }, + } + ] + + new_records = roundtrip(schema, records) + assert records == new_records + + +def test_self_one_to_one_relationship_null_required(): + """Tests a schema with self dependent schema without `null` + https://github.com/fastavro/fastavro/issues/765""" + + schema = { + "type": "record", + "name": "User", + "fields": [ + {"name": "name", "type": "string"}, + {"name": "age", "type": "long"}, + {"name": "friend", "type": "User"}, # `null` is required + ], + } + + records = [ + { + "name": "juan", + "age": 20, + "friend": { + "name": "john", + "age": 30, + }, + } + ] + + with pytest.raises(ValueError, match="no value and no default for friend"): + roundtrip(schema, records) + + def test_enum_named_type(): """https://github.com/fastavro/fastavro/issues/450""" schema = {
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
1.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "developer_requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
backports.tarfile==1.2.0 black==25.1.0 build==1.2.2.post1 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 check-manifest==0.50 click==8.1.8 coverage==7.8.0 cramjam==2.9.1 cryptography==44.0.2 Cython==3.0.12 docutils==0.21.2 exceptiongroup==1.2.2 -e git+https://github.com/fastavro/fastavro.git@7410c5d75578d7379e133b69c40d19fa3a37d94f#egg=fastavro flake8==7.2.0 id==1.5.0 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jeepney==0.9.0 keyring==25.6.0 lz4==4.4.3 markdown-it-py==3.0.0 mccabe==0.7.0 mdurl==0.1.2 more-itertools==10.6.0 mypy==1.15.0 mypy-extensions==1.0.0 nh3==0.2.21 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pathspec==0.12.1 platformdirs==4.3.7 pluggy==1.5.0 pycodestyle==2.13.0 pycparser==2.22 pyflakes==3.3.2 Pygments==2.19.1 pyproject_hooks==1.2.0 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 readme_renderer==44.0 requests==2.32.3 requests-toolbelt==1.0.0 rfc3986==2.0.0 rich==14.0.0 SecretStorage==3.3.3 six==1.17.0 tomli==2.2.1 twine==6.1.0 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 zipp==3.21.0 zlib-ng==0.5.1 zstandard==0.23.0
name: fastavro channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - backports-tarfile==1.2.0 - black==25.1.0 - build==1.2.2.post1 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - check-manifest==0.50 - click==8.1.8 - coverage==7.8.0 - cramjam==2.9.1 - cryptography==44.0.2 - cython==3.0.12 - docutils==0.21.2 - exceptiongroup==1.2.2 - fastavro==1.9.4 - flake8==7.2.0 - id==1.5.0 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jeepney==0.9.0 - keyring==25.6.0 - lz4==4.4.3 - markdown-it-py==3.0.0 - mccabe==0.7.0 - mdurl==0.1.2 - more-itertools==10.6.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - nh3==0.2.21 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pathspec==0.12.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pycodestyle==2.13.0 - pycparser==2.22 - pyflakes==3.3.2 - pygments==2.19.1 - pyproject-hooks==1.2.0 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - readme-renderer==44.0 - requests==2.32.3 - requests-toolbelt==1.0.0 - rfc3986==2.0.0 - rich==14.0.0 - secretstorage==3.3.3 - six==1.17.0 - tomli==2.2.1 - twine==6.1.0 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - zipp==3.21.0 - zlib-ng==0.5.1 - zstandard==0.23.0 prefix: /opt/conda/envs/fastavro
[ "tests/test_json.py::test_self_one_to_one_relationship", "tests/test_json.py::test_multiple_self_one_to_one_relationship", "tests/test_json.py::test_self_one_to_one_relationship_null_required" ]
[]
[ "tests/test_json.py::test_json", "tests/test_json.py::test_more_than_one_record", "tests/test_json.py::test_encoded_union_output", "tests/test_json.py::test_union_output_without_type", "tests/test_json.py::test_union_string_and_bytes", "tests/test_json.py::test_simple_type", "tests/test_json.py::test_array_type_simple", "tests/test_json.py::test_array_type_records", "tests/test_json.py::test_empty_maps", "tests/test_json.py::test_empty_arrays", "tests/test_json.py::test_union_in_array", "tests/test_json.py::test_union_in_array2", "tests/test_json.py::test_union_in_map", "tests/test_json.py::test_with_dependent_schema", "tests/test_json.py::test_enum_named_type", "tests/test_json.py::test_fixed_named_type", "tests/test_json.py::test_record_named_type", "tests/test_json.py::test_default_union_values", "tests/test_json.py::test_all_default_values", "tests/test_json.py::test_default_value_missing", "tests/test_json.py::test_map_of_union_of_array_and_map", "tests/test_json.py::test_json_writer_with_validation", "tests/test_json.py::test_custom_encoder_and_decoder", "tests/test_json.py::test_strict_option", "tests/test_json.py::test_strict_allow_default_option", "tests/test_json.py::test_json_with_map", "tests/test_json.py::test_disable_tuple_notation_option", "tests/test_json.py::test_strict_allow_default_bug", "tests/test_json.py::test_json_aliases" ]
[]
MIT License
18,473
557
[ "fastavro/io/parser.py" ]
showyourwork__showyourwork-456
b7a5984495cf45bb1c163b85d7de47eb3cc6ae5a
2024-05-21 14:13:19
fa173ebb1fb05ee215cdfdf29f42cbba8299fc6e
diff --git a/src/showyourwork/cli/commands/clean.py b/src/showyourwork/cli/commands/clean.py index ee58dfe..1427bfa 100644 --- a/src/showyourwork/cli/commands/clean.py +++ b/src/showyourwork/cli/commands/clean.py @@ -1,3 +1,4 @@ +import os import shutil from ... import paths @@ -31,12 +32,18 @@ def clean(force, deep, snakemake_args=(), cores=1, conda_frontend="conda"): if paths.user().temp.exists(): shutil.rmtree(paths.user().temp) if force: - for file in paths.user().figures.rglob("*.*"): - if file.name != ".gitignore": - file.unlink() - for file in paths.user().data.rglob("*.*"): - if file.name != ".gitignore": - file.unlink() + for root, dirs, files in os.walk(paths.user().data, topdown=False): + for name in files: + if name != ".gitignore": + os.remove(os.path.join(root, name)) + for name in dirs: + os.rmdir(os.path.join(root, name)) + for root, dirs, files in os.walk(paths.user().figures, topdown=False): + for name in files: + if name != ".gitignore": + os.remove(os.path.join(root, name)) + for name in dirs: + os.rmdir(os.path.join(root, name)) if deep: if (paths.user().repo / ".snakemake").exists(): shutil.rmtree(paths.user().repo / ".snakemake")
Force clean removes only files When cleaning the data directory I would expect everything but the `.gitignore` files from the template to be removed. In my workflow, I noticed that data or figure _files_ are indeed removed, but not all of the (sub) directories that are created. To do this, the subcommand needs to be updated with `Path.rmdir()` after the calls to `Path.unlink()`
showyourwork/showyourwork
diff --git a/tests/integration/test_clean.py b/tests/integration/test_clean.py new file mode 100644 index 0000000..919be9f --- /dev/null +++ b/tests/integration/test_clean.py @@ -0,0 +1,68 @@ +from helpers import TemporaryShowyourworkRepository +from yaml import safe_dump, safe_load + +from showyourwork.subproc import get_stdout + +new_directory_script = r""" + +import paths + +newdir = paths.data / "newdir" + +newdir.mkdir(exist_ok=True) + +with open(newdir / "newfile.txt", "w") as f: + f.write("This is a new file") +""" + + +class TestCleanForce(TemporaryShowyourworkRepository): + """Test that when calling clean with the -f option a subdirectory is removed.""" + + local_build_only = True + + def customize(self): + """Create and edit all the necessary files for the workflow.""" + # Create the script + print(f"[{self.repo}] Creating new stuff") + with open(self.cwd / "src" / "scripts" / "new_data.py", "w") as f: + print(new_directory_script, file=f) + + # Make the manuscript depend on this new file + with open(self.cwd / "showyourwork.yml") as config: + original_cfg = safe_load(config) + with open(self.cwd / "showyourwork.yml", mode="w") as config: + original_cfg["dependencies"] = { + "src/tex/ms.tex": ["src/data/newdir/newfile.txt"] + } + safe_dump(original_cfg, config) + + # Add a Snakemake rule to run the script + with open(self.cwd / "Snakefile") as f: + contents = f.read() + with open(self.cwd / "Snakefile", "w") as f: + print(contents, file=f) + print("\n", file=f) + print( + "\n".join( + [ + "rule make_new_data:", + " output:", + " 'src/data/newdir/newfile.txt'", + " script:", + " 'src/scripts/new_data.py'", + ] + ), + file=f, + ) + + def check_build(self): + """Check that the new directory and file were created.""" + assert (self.cwd / "src" / "data" / "newdir").exists() + assert (self.cwd / "src" / "data" / "newdir" / "newfile.txt").exists() + + # Run the clean command with the -f option + get_stdout("showyourwork clean -f", shell=True, cwd=self.cwd) + + # Check that the new directory was removed + assert not (self.cwd / "src" / "data" / "newdir").exists()
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest>=7.0.0", "pytest-asyncio-cooperative>=0.28.0" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
appdirs==1.4.4 arrow==1.3.0 attrs==25.3.0 binaryornot==0.4.4 certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 ConfigArgParse==1.7 connection_pool==0.0.3 cookiecutter==2.6.0 datrie==0.8.2 docutils==0.21.2 dpath==2.2.0 exceptiongroup==1.2.2 fastjsonschema==2.21.1 gitdb==4.0.12 GitPython==3.1.44 graphviz==0.20.3 idna==3.10 iniconfig==2.1.0 Jinja2==3.1.6 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter_core==5.7.2 markdown-it-py==3.0.0 MarkupSafe==3.0.2 mdurl==0.1.2 nbformat==5.10.4 packaging==24.2 plac==1.4.3 platformdirs==4.3.7 pluggy==1.5.0 psutil==7.0.0 PuLP==2.7.0 Pygments==2.19.1 pytest==8.3.5 pytest-asyncio-cooperative==0.37.0 python-dateutil==2.9.0.post0 python-slugify==8.0.4 PyYAML==6.0.2 ratelimiter==1.2.0.post0 referencing==0.36.2 requests==2.32.3 reretry==0.11.8 rich==14.0.0 rpds-py==0.24.0 -e git+https://github.com/showyourwork/showyourwork.git@b7a5984495cf45bb1c163b85d7de47eb3cc6ae5a#egg=showyourwork six==1.17.0 smart-open==7.1.0 smmap==5.0.2 snakemake==7.15.2 stopit==1.1.2 tabulate==0.9.0 text-unidecode==1.3 tomli==2.2.1 toposort==1.10 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.1 urllib3==2.3.0 wrapt==1.17.2 yte==1.7.0
name: showyourwork channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - appdirs==1.4.4 - arrow==1.3.0 - attrs==25.3.0 - binaryornot==0.4.4 - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - configargparse==1.7 - connection-pool==0.0.3 - cookiecutter==2.6.0 - datrie==0.8.2 - docutils==0.21.2 - dpath==2.2.0 - exceptiongroup==1.2.2 - fastjsonschema==2.21.1 - gitdb==4.0.12 - gitpython==3.1.44 - graphviz==0.20.3 - idna==3.10 - iniconfig==2.1.0 - jinja2==3.1.6 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-core==5.7.2 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - mdurl==0.1.2 - nbformat==5.10.4 - packaging==24.2 - plac==1.4.3 - platformdirs==4.3.7 - pluggy==1.5.0 - psutil==7.0.0 - pulp==2.7.0 - pygments==2.19.1 - pytest==8.3.5 - pytest-asyncio-cooperative==0.37.0 - python-dateutil==2.9.0.post0 - python-slugify==8.0.4 - pyyaml==6.0.2 - ratelimiter==1.2.0.post0 - referencing==0.36.2 - requests==2.32.3 - reretry==0.11.8 - rich==14.0.0 - rpds-py==0.24.0 - showyourwork==0.4.4.dev86+gb7a5984 - six==1.17.0 - smart-open==7.1.0 - smmap==5.0.2 - snakemake==7.15.2 - stopit==1.1.2 - tabulate==0.9.0 - text-unidecode==1.3 - tomli==2.2.1 - toposort==1.10 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.1 - urllib3==2.3.0 - wrapt==1.17.2 - yte==1.7.0 prefix: /opt/conda/envs/showyourwork
[ "tests/integration/test_clean.py::TestCleanForce::test_local" ]
[]
[]
[]
MIT License
18,475
376
[ "src/showyourwork/cli/commands/clean.py" ]
caronc__apprise-1128
286a4374c0988eb996c469557617b8b0c3d885d5
2024-05-21 23:23:45
286a4374c0988eb996c469557617b8b0c3d885d5
caronc: Thank you for this pr!🙏
diff --git a/apprise/plugins/matrix.py b/apprise/plugins/matrix.py index c1401f2..70a4098 100644 --- a/apprise/plugins/matrix.py +++ b/apprise/plugins/matrix.py @@ -293,6 +293,9 @@ class NotifyMatrix(NotifyBase): # This gets initialized after a login/registration self.access_token = None + # This gets incremented for each request made against the v3 API + self.transaction_id = 0 + # Place an image inline with the message body self.include_image = include_image @@ -612,8 +615,10 @@ class NotifyMatrix(NotifyBase): # Build our path if self.version == MatrixVersion.V3: - path = '/rooms/{}/send/m.room.message/0'.format( - NotifyMatrix.quote(room_id)) + path = '/rooms/{}/send/m.room.message/{}'.format( + NotifyMatrix.quote(room_id), + self.transaction_id, + ) else: path = '/rooms/{}/send/m.room.message'.format( @@ -685,6 +690,12 @@ class NotifyMatrix(NotifyBase): method = 'PUT' if self.version == MatrixVersion.V3 else 'POST' postokay, response = self._fetch( path, payload=payload, method=method) + + # Increment the transaction ID to avoid future messages being + # recognized as retransmissions and ignored + if self.version == MatrixVersion.V3: + self.transaction_id += 1 + if not postokay: # Notify our user self.logger.warning(
Matrix v3 messages are rejected as duplicates when the login session is reused :mega: **Notification Service(s) Impacted** Matrix :lady_beetle: **Describe the bug** In Matrix's v3 API [when a client sends a message](https://spec.matrix.org/unstable/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid) the last URL segment is the [Transaction Identifier](https://spec.matrix.org/unstable/client-server-api/#transaction-identifiers). Summing up the docs _(this is not the official wording!)_: > The purpose of the transaction ID is to allow the homeserver to distinguish a new request from a retransmission. > The client should change the transaction ID value for each request (how is not specified; a monotonically increasing integer is recommended). > The homeserver identifies a request as a retransmission if the transaction ID and HTTP path are the same as a previous request. > The scope of a transaction ID is for a single device. If a client logs out and back in between two requests using the same transaction ID, they are considered distinct because logging in creates a new device [...]. If a client re-uses a transaction ID for the same endpoint after refreshing an access token, it will be assumed to be a duplicate request and ignored. Apprise [currently always uses a transaction ID of `0`](https://github.com/caronc/apprise/blob/286a4374c0988eb996c469557617b8b0c3d885d5/apprise/plugins/matrix.py#L615), and thus when the login session is retained (through [`_login()`](https://github.com/caronc/apprise/blob/286a4374c0988eb996c469557617b8b0c3d885d5/apprise/plugins/matrix.py#L810)) only the first message that gets sent is actually accepted by the Matrix homeserver. All the subsequent ones are ignored and the homeserver replies with the internal event ID of the first message, since it believes that these new requests are indeed retransmissions. Terminating and restarting the Python application that uses Apprise solves the problem because a new login session (and thus a new device, in Matrix terms) is created and the transaction ID of 0 is now valid for a (single) new request. The Apprise CLI client is thus immune from this issue since it (always, I presume?) starts from scratch without an estabilished session. :bulb: **Screenshots and Logs** N/A :computer: **Your System Details:** - OS: Debian 11 (Bullseye) - Python Version: Python 3.9.2 - Apprise Version: 1.7.0 :crystal_ball: **Additional context** + Synapse version: 1.107.0
caronc/apprise
diff --git a/test/test_plugin_matrix.py b/test/test_plugin_matrix.py index df7e4dc..a9916ad 100644 --- a/test/test_plugin_matrix.py +++ b/test/test_plugin_matrix.py @@ -1137,3 +1137,58 @@ def test_plugin_matrix_attachments_api_v2(mock_post, mock_get): # Force __del__() call del obj + + [email protected]('requests.put') [email protected]('requests.get') [email protected]('requests.post') +def test_plugin_matrix_transaction_ids_api_v3(mock_post, mock_get, mock_put): + """ + NotifyMatrix() Transaction ID Checks (v3) + + """ + + # Prepare a good response + response = mock.Mock() + response.status_code = requests.codes.ok + response.content = MATRIX_GOOD_RESPONSE.encode('utf-8') + + # Prepare a bad response + bad_response = mock.Mock() + bad_response.status_code = requests.codes.internal_server_error + + # Prepare Mock return object + mock_post.return_value = response + mock_get.return_value = response + mock_put.return_value = response + + notifications_to_send = [10, 1] + mock_post_offset = mock_put_counter = 0 + + for logins, notifications in enumerate(notifications_to_send, start=1): + # Instantiate our object + obj = Apprise.instantiate('matrix://user:pass@localhost/#general?v=3') + + for txnId in range(notifications): + assert obj.notify( + body='body', title='title', notify_type=NotifyType.INFO + ) is True + + # Test our call count + assert mock_put.call_count == mock_put_counter + 1 + # Login & join must happen only once per session + assert mock_post.call_count == mock_post_offset + (2 * logins) + assert mock_post.call_args_list[0][0][0] == \ + 'http://localhost/_matrix/client/v3/login' + assert mock_post.call_args_list[1][0][0] == \ + 'http://localhost/_matrix/client/v3/join/' + \ + '%23general%3Alocalhost' + assert mock_put.call_args_list[txnId][0][0] == \ + 'http://localhost/_matrix/client/v3/rooms/' + \ + f'%21abc123%3Alocalhost/send/m.room.message/{txnId}' + + mock_put_counter = mock_put.call_count + + # Force a object removal (thus a logout call) + del obj + mock_post_offset += 1
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc libdbus-1-dev" ], "python": "3.10", "reqs_path": [ "requirements.txt", "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/caronc/apprise.git@286a4374c0988eb996c469557617b8b0c3d885d5#egg=apprise babel==2.17.0 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 coverage==7.8.0 exceptiongroup==1.2.2 execnet==2.1.1 flake8==7.2.0 idna==3.10 iniconfig==2.1.0 Markdown==3.7 mccabe==0.7.0 oauthlib==3.2.2 packaging==24.2 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.2 pytest==8.3.5 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 PyYAML==6.0.2 requests==2.32.3 requests-oauthlib==2.0.0 tomli==2.2.1 urllib3==2.3.0
name: apprise channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py310h06a4308_0 - python=3.10.16=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py310h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py310h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - babel==2.17.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - coverage==7.8.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - flake8==7.2.0 - idna==3.10 - iniconfig==2.1.0 - markdown==3.7 - mccabe==0.7.0 - oauthlib==3.2.2 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - pyyaml==6.0.2 - requests==2.32.3 - requests-oauthlib==2.0.0 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/apprise
[ "test/test_plugin_matrix.py::test_plugin_matrix_transaction_ids_api_v3" ]
[]
[ "test/test_plugin_matrix.py::test_plugin_matrix_urls", "test/test_plugin_matrix.py::test_plugin_matrix_general", "test/test_plugin_matrix.py::test_plugin_matrix_fetch", "test/test_plugin_matrix.py::test_plugin_matrix_auth", "test/test_plugin_matrix.py::test_plugin_matrix_rooms", "test/test_plugin_matrix.py::test_plugin_matrix_url_parsing", "test/test_plugin_matrix.py::test_plugin_matrix_image_errors", "test/test_plugin_matrix.py::test_plugin_matrix_attachments_api_v3", "test/test_plugin_matrix.py::test_plugin_matrix_attachments_api_v2" ]
[]
BSD 2-Clause "Simplified" License
18,481
380
[ "apprise/plugins/matrix.py" ]
econ-ark__HARK-1432
3eb9a09337fbbb2fabf0dcab08931e03dc9e827c
2024-05-22 15:18:11
3eb9a09337fbbb2fabf0dcab08931e03dc9e827c
diff --git a/HARK/distribution.py b/HARK/distribution.py index 40c88c93..d26ecec8 100644 --- a/HARK/distribution.py +++ b/HARK/distribution.py @@ -769,6 +769,10 @@ class Bernoulli(DiscreteFrozenDistribution): # Set up the RNG super().__init__(stats.bernoulli, p=self.p, seed=seed) + self.pmv = [1 - self.p, self.p] + self.atoms = [0, 1] + self.limit = {"dist": self} + class DiscreteDistribution(Distribution): """
Cannot make a DiscreteDistributionLabeled from a Bernoulli variable ``` foo = Bernoulli(.4) DiscreteDistributionLabeled.from_unlabeled( foo, var_names = ['foo'] ) ``` ``` File ~/projects/HARK/HARK/distribution.py:1087, in DiscreteDistributionLabeled.from_unlabeled(cls, dist, name, attrs, var_names, var_attrs) 1077 @classmethod 1078 def from_unlabeled( 1079 cls, (...) 1084 var_attrs=None, 1085 ): 1086 ldd = cls( -> 1087 dist.pmv, 1088 dist.atoms, 1089 seed=dist.seed, 1090 limit=dist.limit, 1091 name=name, 1092 attrs=attrs, 1093 var_names=var_names, 1094 var_attrs=var_attrs, 1095 ) 1097 return ldd AttributeError: 'Bernoulli' object has no attribute 'pmv' ```
econ-ark/HARK
diff --git a/HARK/tests/test_distribution.py b/HARK/tests/test_distribution.py index c9f292f3..cc1c5b58 100644 --- a/HARK/tests/test_distribution.py +++ b/HARK/tests/test_distribution.py @@ -607,6 +607,12 @@ class DiscreteDistributionLabeledTests(unittest.TestCase): ) ) + def test_Bernoulli_to_labeled(self): + p = 0.4 + foo = Bernoulli(p) + bern = DiscreteDistributionLabeled.from_unlabeled(foo, var_names=["foo"]) + self.assertTrue(np.allclose(bern.expected(), p)) + class labeled_transition_tests(unittest.TestCase): def setUp(self) -> None:
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.14
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.10", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.7.0 asttokens==3.0.0 attrs==25.3.0 certifi==2025.1.31 cfgv==3.4.0 charset-normalizer==3.4.1 cloudpickle==3.1.1 comm==0.2.2 contourpy==1.3.1 coverage==7.8.0 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 distlib==0.3.9 -e git+https://github.com/econ-ark/HARK.git@3eb9a09337fbbb2fabf0dcab08931e03dc9e827c#egg=econ_ark estimagic==0.5.1 exceptiongroup==1.2.2 execnet==2.1.1 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 greenlet==3.1.1 identify==2.6.9 idna==3.10 iniconfig==2.1.0 interpolation==2.2.7 ipykernel==6.29.5 ipython==8.34.0 jedi==0.19.2 joblib==1.4.2 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter_client==8.6.3 jupyter_core==5.7.2 kiwisolver==1.4.8 llvmlite==0.44.0 matplotlib==3.10.1 matplotlib-inline==0.1.7 mpmath==1.3.0 narwhals==1.32.0 nbformat==5.10.4 nbval==0.11.0 nest-asyncio==1.6.0 networkx==3.4.2 nodeenv==1.9.1 numba==0.61.0 numpy==2.1.3 packaging==24.2 pandas==2.2.3 parso==0.8.4 pexpect==4.9.0 pillow==11.1.0 platformdirs==4.3.7 plotly==6.0.1 pluggy==1.5.0 pre_commit==4.2.0 prompt_toolkit==3.0.50 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pybaum==0.1.3 Pygments==2.19.1 pyparsing==3.2.3 pytest==8.3.5 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 quantecon==0.8.0 referencing==0.36.2 requests==2.32.3 rpds-py==0.24.0 ruff==0.11.2 scipy==1.15.2 seaborn==0.13.2 six==1.17.0 SQLAlchemy==2.0.40 stack-data==0.6.3 sympy==1.13.3 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 xarray==2025.3.1
name: HARK channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py310h06a4308_0 - python=3.10.16=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py310h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py310h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.7.0 - asttokens==3.0.0 - attrs==25.3.0 - certifi==2025.1.31 - cfgv==3.4.0 - charset-normalizer==3.4.1 - cloudpickle==3.1.1 - comm==0.2.2 - contourpy==1.3.1 - coverage==7.8.0 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - distlib==0.3.9 - econ-ark==0.14.1 - estimagic==0.5.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - greenlet==3.1.1 - identify==2.6.9 - idna==3.10 - iniconfig==2.1.0 - interpolation==2.2.7 - ipykernel==6.29.5 - ipython==8.34.0 - jedi==0.19.2 - joblib==1.4.2 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - kiwisolver==1.4.8 - llvmlite==0.44.0 - matplotlib==3.10.1 - matplotlib-inline==0.1.7 - mpmath==1.3.0 - narwhals==1.32.0 - nbformat==5.10.4 - nbval==0.11.0 - nest-asyncio==1.6.0 - networkx==3.4.2 - nodeenv==1.9.1 - numba==0.61.0 - numpy==2.1.3 - packaging==24.2 - pandas==2.2.3 - parso==0.8.4 - pexpect==4.9.0 - pillow==11.1.0 - platformdirs==4.3.7 - plotly==6.0.1 - pluggy==1.5.0 - pre-commit==4.2.0 - prompt-toolkit==3.0.50 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pybaum==0.1.3 - pygments==2.19.1 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - quantecon==0.8.0 - referencing==0.36.2 - requests==2.32.3 - rpds-py==0.24.0 - ruff==0.11.2 - scipy==1.15.2 - seaborn==0.13.2 - six==1.17.0 - sqlalchemy==2.0.40 - stack-data==0.6.3 - sympy==1.13.3 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - xarray==2025.3.1 prefix: /opt/conda/envs/HARK
[ "HARK/tests/test_distribution.py::DiscreteDistributionLabeledTests::test_Bernoulli_to_labeled" ]
[]
[ "HARK/tests/test_distribution.py::DiscreteDistributionTests::test_calc_expectation", "HARK/tests/test_distribution.py::DiscreteDistributionTests::test_distr_of_function", "HARK/tests/test_distribution.py::DiscreteDistributionTests::test_draw", "HARK/tests/test_distribution.py::DiscreteDistributionTests::test_self_dist_of_func", "HARK/tests/test_distribution.py::DiscreteDistributionTests::test_self_expected_value", "HARK/tests/test_distribution.py::MatrixDiscreteDistributionTests::test_distr_of_fun", "HARK/tests/test_distribution.py::MatrixDiscreteDistributionTests::test_draw", "HARK/tests/test_distribution.py::MatrixDiscreteDistributionTests::test_expected", "HARK/tests/test_distribution.py::DistributionClassTests::test_Bernoulli", "HARK/tests/test_distribution.py::DistributionClassTests::test_Lognormal", "HARK/tests/test_distribution.py::DistributionClassTests::test_MVNormal", "HARK/tests/test_distribution.py::DistributionClassTests::test_Normal", "HARK/tests/test_distribution.py::DistributionClassTests::test_Uniform", "HARK/tests/test_distribution.py::DistributionClassTests::test_Weibull", "HARK/tests/test_distribution.py::DistributionClassTests::test_drawMeanOneLognormal", "HARK/tests/test_distribution.py::IndexDistributionClassTests::test_IndexDistribution", "HARK/tests/test_distribution.py::IndexDistributionClassTests::test_IndexDistribution_approx", "HARK/tests/test_distribution.py::IndexDistributionClassTests::test_IndexDistribution_seeds", "HARK/tests/test_distribution.py::MarkovProcessTests::test_draw", "HARK/tests/test_distribution.py::LogNormalToNormalTests::test_lognorm_to_norm", "HARK/tests/test_distribution.py::LogNormalToNormalTests::test_norm_to_lognorm", "HARK/tests/test_distribution.py::NormalDistTest::test_approx_equiprobable", "HARK/tests/test_distribution.py::DiscreteDistributionLabeledTests::test_combine_labeled_dist", "HARK/tests/test_distribution.py::DiscreteDistributionLabeledTests::test_draw", "HARK/tests/test_distribution.py::DiscreteDistributionLabeledTests::test_getters_setters", "HARK/tests/test_distribution.py::DiscreteDistributionLabeledTests::test_self_dist_of_func", "HARK/tests/test_distribution.py::DiscreteDistributionLabeledTests::test_self_expected_value", "HARK/tests/test_distribution.py::labeled_transition_tests::test_expectation_transformation" ]
[]
Apache License 2.0
18,486
157
[ "HARK/distribution.py" ]
tobymao__sqlglot-3533
a2556101c8d04907ae49252def84c55d2daf78b2
2024-05-22 15:20:11
1e1dc3fea8c5fc1f86fefe6af384e38c8531f2d2
diff --git a/sqlglot/dialects/hive.py b/sqlglot/dialects/hive.py index be733b18..48e032d5 100644 --- a/sqlglot/dialects/hive.py +++ b/sqlglot/dialects/hive.py @@ -573,6 +573,9 @@ class Hive(Dialect): exp.OnProperty: lambda *_: "", exp.PrimaryKeyColumnConstraint: lambda *_: "PRIMARY KEY", exp.ParseJSON: lambda self, e: self.sql(e.this), + exp.WeekOfYear: rename_func("WEEKOFYEAR"), + exp.DayOfMonth: rename_func("DAYOFMONTH"), + exp.DayOfWeek: rename_func("DAYOFWEEK"), } PROPERTIES_LOCATION = {
The three functions WEEKOFYEAR, DAYOFMONTH, and DAYOFWEEK were incorrectly converted in Hive. ### Code to reproduce an issue ```py import sqlglot sqlglot.parse_one("SELECT WEEKOFYEAR('2024-05-22'), DAYOFMONTH('2024-05-22'), DAYOFWEEK('2024-05-22')", read='hive').sql(dialect='hive') ``` ### as-is: The return value in the current issue situation ``` "SELECT WEEK_OF_YEAR('2024-05-22'), DAY_OF_MONTH('2024-05-22'), DAY_OF_WEEK('2024-05-22')" ``` ### to-be: The correct return value ``` "SELECT WEEKOFYEAR('2024-05-22'), DAYOFMONTH('2024-05-22'), DAYOFWEEK('2024-05-22')" ```
tobymao/sqlglot
diff --git a/tests/dialects/test_hive.py b/tests/dialects/test_hive.py index dfce446d..3ebaded0 100644 --- a/tests/dialects/test_hive.py +++ b/tests/dialects/test_hive.py @@ -406,7 +406,9 @@ class TestHive(Validator): self.validate_identity("(VALUES (1 AS a, 2 AS b, 3))") self.validate_identity("SELECT * FROM my_table TIMESTAMP AS OF DATE_ADD(CURRENT_DATE, -1)") self.validate_identity("SELECT * FROM my_table VERSION AS OF DATE_ADD(CURRENT_DATE, -1)") - + self.validate_identity( + "SELECT WEEKOFYEAR('2024-05-22'), DAYOFMONTH('2024-05-22'), DAYOFWEEK('2024-05-22')" + ) self.validate_identity( "SELECT ROW() OVER (DISTRIBUTE BY x SORT BY y)", "SELECT ROW() OVER (PARTITION BY x ORDER BY y)",
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
24.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio", "ruff", "mypy", "pdoc" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 coverage==7.8.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 Pygments==2.19.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@a2556101c8d04907ae49252def84c55d2daf78b2#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - coverage==7.8.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pygments==2.19.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_hive.py::TestHive::test_hive" ]
[]
[ "tests/dialects/test_hive.py::TestHive::test_bits", "tests/dialects/test_hive.py::TestHive::test_cast", "tests/dialects/test_hive.py::TestHive::test_data_type", "tests/dialects/test_hive.py::TestHive::test_ddl", "tests/dialects/test_hive.py::TestHive::test_escapes", "tests/dialects/test_hive.py::TestHive::test_lateral_view", "tests/dialects/test_hive.py::TestHive::test_order_by", "tests/dialects/test_hive.py::TestHive::test_quotes", "tests/dialects/test_hive.py::TestHive::test_regex", "tests/dialects/test_hive.py::TestHive::test_time" ]
[]
MIT License
18,487
180
[ "sqlglot/dialects/hive.py" ]
TeamGraphix__graphix-154
dd15e5d65fac5ba2a1fac7b4a5ac6ec943abc613
2024-05-22 22:45:53
90c943374b3b2c9f3b6881ecf866ddff6dacb249
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/TeamGraphix/graphix/pull/154?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TeamGraphix) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 71.84%. Comparing base [(`dd15e5d`)](https://app.codecov.io/gh/TeamGraphix/graphix/commit/dd15e5d65fac5ba2a1fac7b4a5ac6ec943abc613?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TeamGraphix) to head [(`2c77573`)](https://app.codecov.io/gh/TeamGraphix/graphix/pull/154?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TeamGraphix). <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## master #154 +/- ## ========================================== + Coverage 71.75% 71.84% +0.08% ========================================== Files 30 30 Lines 5353 5359 +6 ========================================== + Hits 3841 3850 +9 + Misses 1512 1509 -3 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TeamGraphix/graphix/pull/154?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TeamGraphix). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TeamGraphix).
diff --git a/graphix/pattern.py b/graphix/pattern.py index 0c700c6..fc4efc4 100644 --- a/graphix/pattern.py +++ b/graphix/pattern.py @@ -954,8 +954,14 @@ class Pattern: ind = self._find_op_to_be_moved("M") if ind == "end": return [] - while self.__seq[ind][0] == "M": - meas_cmds.append(self.__seq[ind]) + while True: + try: + cmd = self.__seq[ind] + except IndexError: + break + if cmd[0] != "M": + break + meas_cmds.append(cmd) ind += 1 return meas_cmds
[Bug]: "list index out of range" in `pattern.get_measurement_commands` **Describe the bug** The method `pattern.get_measurement_commands` may raise `IndexError: list index out of range` if measure commands are the last commands in the pattern. **To Reproduce** The following code raises `IndexError`: ```python import graphix p = graphix.pattern.Pattern(input_nodes=[0]) p.add(["N", 1]) p.add(["M", 1, "XY", 0, [], []]) p.perform_pauli_measurements() ``` **Expected behavior** No exception should be raised and pauli measurements should be done. **Environment (please complete the following information):** - OS: macOS 14.4.1 (23E224) - Python version: 3.11.8 - Related module versions if applicable:
TeamGraphix/graphix
diff --git a/tests/test_pattern.py b/tests/test_pattern.py index dd9784d..067bd23 100644 --- a/tests/test_pattern.py +++ b/tests/test_pattern.py @@ -507,6 +507,13 @@ class TestLocalPattern: assert not result1 assert result2 + def test_pauli_measurement_end_with_measure(self) -> None: + # https://github.com/TeamGraphix/graphix/issues/153 + p = Pattern(input_nodes=[0]) + p.add(["N", 1]) + p.add(["M", 1, "XY", 0, [], []]) + p.perform_pauli_measurements() + def assert_equal_edge(edge: Sequence[int], ref: Sequence[int]) -> bool: ans = True
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "black==24.4.0", "isort==5.13.2", "pytest", "matplotlib" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.7.0 autoray==0.7.1 black==24.4.0 cachetools==5.5.2 chardet==5.2.0 click==8.1.8 colorama==0.4.6 contourpy==1.3.0 cotengra==0.7.1 cycler==0.12.1 cytoolz==1.0.1 dill==0.3.9 distlib==0.3.9 exceptiongroup==1.2.2 filelock==3.18.0 fonttools==4.56.0 galois==0.4.4 -e git+https://github.com/TeamGraphix/graphix.git@dd15e5d65fac5ba2a1fac7b4a5ac6ec943abc613#egg=graphix importlib_resources==6.5.2 iniconfig==2.1.0 isort==5.13.2 kiwisolver==1.4.7 llvmlite==0.43.0 matplotlib==3.9.4 mpmath==1.3.0 mypy-extensions==1.0.0 networkx==3.2.1 numba==0.60.0 numpy==1.25.2 opt_einsum==3.4.0 packaging==24.2 parameterized==0.9.0 pathspec==0.12.1 pbr==6.1.1 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 psutil==7.0.0 pydantic==2.11.1 pydantic_core==2.33.0 pyparsing==3.2.3 pyproject-api==1.9.0 pytest==8.3.5 python-dateutil==2.9.0.post0 qiskit==1.4.2 qiskit-aer==0.17.0 quimb==1.10.0 rustworkx==0.16.0 scipy==1.13.1 six==1.17.0 stevedore==5.4.1 symengine==0.13.0 sympy==1.13.3 tomli==2.2.1 toolz==1.0.0 tox==4.25.0 tqdm==4.67.1 typing-inspection==0.4.0 typing_extensions==4.13.0 virtualenv==20.29.3 zipp==3.21.0
name: graphix channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.7.0 - autoray==0.7.1 - black==24.4.0 - cachetools==5.5.2 - chardet==5.2.0 - click==8.1.8 - colorama==0.4.6 - contourpy==1.3.0 - cotengra==0.7.1 - cycler==0.12.1 - cytoolz==1.0.1 - dill==0.3.9 - distlib==0.3.9 - exceptiongroup==1.2.2 - filelock==3.18.0 - fonttools==4.56.0 - galois==0.4.4 - graphix==0.2.14 - importlib-resources==6.5.2 - iniconfig==2.1.0 - isort==5.13.2 - kiwisolver==1.4.7 - llvmlite==0.43.0 - matplotlib==3.9.4 - mpmath==1.3.0 - mypy-extensions==1.0.0 - networkx==3.2.1 - numba==0.60.0 - numpy==1.25.2 - opt-einsum==3.4.0 - packaging==24.2 - parameterized==0.9.0 - pathspec==0.12.1 - pbr==6.1.1 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - psutil==7.0.0 - pydantic==2.11.1 - pydantic-core==2.33.0 - pyparsing==3.2.3 - pyproject-api==1.9.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - qiskit==1.4.2 - qiskit-aer==0.17.0 - quimb==1.10.0 - rustworkx==0.16.0 - scipy==1.13.1 - six==1.17.0 - stevedore==5.4.1 - symengine==0.13.0 - sympy==1.13.3 - tomli==2.2.1 - toolz==1.0.0 - tox==4.25.0 - tqdm==4.67.1 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - virtualenv==20.29.3 - zipp==3.21.0 prefix: /opt/conda/envs/graphix
[ "tests/test_pattern.py::TestLocalPattern::test_pauli_measurement_end_with_measure" ]
[]
[ "tests/test_pattern.py::TestPattern::test_manual_generation", "tests/test_pattern.py::TestPattern::test_standardize", "tests/test_pattern.py::TestPattern::test_minimize_space", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[1]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[2]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[3]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[4]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[5]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[6]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[7]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[8]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[9]", "tests/test_pattern.py::TestPattern::test_minimize_space_with_gflow[10]", "tests/test_pattern.py::TestPattern::test_empty_output_nodes[statevector]", "tests/test_pattern.py::TestPattern::test_empty_output_nodes[densitymatrix]", "tests/test_pattern.py::TestPattern::test_empty_output_nodes[tensornetwork]", "tests/test_pattern.py::TestPattern::test_minimize_space_graph_maxspace_with_flow", "tests/test_pattern.py::TestPattern::test_parallelize_pattern", "tests/test_pattern.py::TestPattern::test_shift_signals[1]", "tests/test_pattern.py::TestPattern::test_shift_signals[2]", "tests/test_pattern.py::TestPattern::test_shift_signals[3]", "tests/test_pattern.py::TestPattern::test_shift_signals[4]", "tests/test_pattern.py::TestPattern::test_shift_signals[5]", "tests/test_pattern.py::TestPattern::test_shift_signals[6]", "tests/test_pattern.py::TestPattern::test_shift_signals[7]", "tests/test_pattern.py::TestPattern::test_shift_signals[8]", "tests/test_pattern.py::TestPattern::test_shift_signals[9]", "tests/test_pattern.py::TestPattern::test_shift_signals[10]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[1]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[2]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[3]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[4]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[5]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[6]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[7]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[8]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[9]", "tests/test_pattern.py::TestPattern::test_pauli_measurment[10]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[1]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[2]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[3]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[4]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[5]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[6]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[7]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[8]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[9]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_leave_input[10]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[1]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[2]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[3]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[4]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[5]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[6]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[7]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[8]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[9]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate[10]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[1]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[2]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[3]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[4]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[5]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[6]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[7]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[8]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[9]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler[10]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[1]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[2]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[3]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[4]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[5]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[6]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[7]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[8]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[9]", "tests/test_pattern.py::TestPattern::test_pauli_measurment_opt_gate_transpiler_without_signalshift[10]", "tests/test_pattern.py::TestPattern::test_pauli_measurement[False]", "tests/test_pattern.py::TestPattern::test_pauli_measurement[True]", "tests/test_pattern.py::TestPattern::test_pauli_measurement_leave_input[False]", "tests/test_pattern.py::TestPattern::test_pauli_measurement_leave_input[True]", "tests/test_pattern.py::TestPattern::test_get_meas_plane", "tests/test_pattern.py::TestLocalPattern::test_assert_equal_edge[test0]", "tests/test_pattern.py::TestLocalPattern::test_assert_equal_edge[test1]", "tests/test_pattern.py::TestLocalPattern::test_assert_equal_edge[test2]", "tests/test_pattern.py::TestLocalPattern::test_assert_equal_edge[test3]", "tests/test_pattern.py::TestLocalPattern::test_assert_equal_edge[test4]", "tests/test_pattern.py::TestLocalPattern::test_no_gate", "tests/test_pattern.py::TestLocalPattern::test_get_graph", "tests/test_pattern.py::TestLocalPattern::test_standardize[1]", "tests/test_pattern.py::TestLocalPattern::test_standardize[2]", "tests/test_pattern.py::TestLocalPattern::test_standardize[3]", "tests/test_pattern.py::TestLocalPattern::test_standardize[4]", "tests/test_pattern.py::TestLocalPattern::test_standardize[5]", "tests/test_pattern.py::TestLocalPattern::test_standardize[6]", "tests/test_pattern.py::TestLocalPattern::test_standardize[7]", "tests/test_pattern.py::TestLocalPattern::test_standardize[8]", "tests/test_pattern.py::TestLocalPattern::test_standardize[9]", "tests/test_pattern.py::TestLocalPattern::test_standardize[10]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[1]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[2]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[3]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[4]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[5]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[6]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[7]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[8]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[9]", "tests/test_pattern.py::TestLocalPattern::test_shift_signals[10]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[1]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[2]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[3]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[4]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[5]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[6]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[7]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[8]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[9]", "tests/test_pattern.py::TestLocalPattern::test_standardize_and_shift_signals[10]", "tests/test_pattern.py::TestLocalPattern::test_mixed_pattern_operations[1]", "tests/test_pattern.py::TestLocalPattern::test_mixed_pattern_operations[2]", "tests/test_pattern.py::TestLocalPattern::test_mixed_pattern_operations[3]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[1]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[2]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[3]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[4]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[5]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[6]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[7]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[8]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[9]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_standardize[10]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[1]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[2]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[3]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[4]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[5]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[6]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[7]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[8]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[9]", "tests/test_pattern.py::TestLocalPattern::test_opt_transpile_shift_signals[10]", "tests/test_pattern.py::TestLocalPattern::test_node_is_standardized[test0]", "tests/test_pattern.py::TestLocalPattern::test_node_is_standardized[test1]", "tests/test_pattern.py::TestLocalPattern::test_node_is_standardized[test2]", "tests/test_pattern.py::TestLocalPattern::test_node_is_standardized[test3]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[1]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[2]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[3]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[4]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[5]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[6]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[7]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[8]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[9]", "tests/test_pattern.py::TestLocalPattern::test_localpattern_is_standard[10]" ]
[]
Apache License 2.0
18,490
181
[ "graphix/pattern.py" ]
Informasjonsforvaltning__fdk-rdf-parser-306
6f2ba3bef2611d35b28a1e26831f58dfeb456325
2024-05-23 12:07:32
0a72edaddfd8858b4fe4830a24875fc1cc1be7fb
github-actions[bot]: ``` Warning: poetry-plugin-export will not be installed by default in a future version of Poetry. In order to avoid a breaking change and make your automation forward-compatible, please install poetry-plugin-export explicitly. See https://python-poetry.org/docs/plugins/#using-plugins for details on how to install a plugin. To disable this warning run 'poetry config warnings.export false'. The `--dev` option is deprecated, use the `--with dev` notation instead. +==============================================================================+ /$$$$$$ /$$ /$$__ $$ | $$ /$$$$$$$ /$$$$$$ | $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$_____/ |____ $$| $$$$ /$$__ $$|_ $$_/ | $$ | $$ | $$$$$$ /$$$$$$$| $$_/ | $$$$$$$$ | $$ | $$ | $$ \____ $$ /$$__ $$| $$ | $$_____/ | $$ /$$| $$ | $$ /$$$$$$$/| $$$$$$$| $$ | $$$$$$$ | $$$$/| $$$$$$$ |_______/ \_______/|__/ \_______/ \___/ \____ $$ /$$ | $$ | $$$$$$/ by safetycli.com \______/ +==============================================================================+ REPORT Safety is using PyUp's free open-source vulnerability database. This data is 30 days old and limited. For real-time enhanced vulnerability data, fix recommendations, severity reporting, cybersecurity support, team and project policy management and more sign up at https://pyup.io or email [email protected] Safety v3.1.0 is scanning for Vulnerabilities... Scanning dependencies in your files: -> /tmp/tmpmoxvqdlv Using open-source vulnerability database Found and scanned 72 packages Timestamp 2024-05-23 12:08:11 0 vulnerabilities reported 0 vulnerabilities ignored +==============================================================================+ No known security vulnerabilities found. +==============================================================================+ Safety is using PyUp's free open-source vulnerability database. This data is 30 days old and limited. For real-time enhanced vulnerability data, fix recommendations, severity reporting, cybersecurity support, team and project policy management and more sign up at https://pyup.io or email [email protected] +==============================================================================+ ``` <!-- Sticky Pull Request CommentSafety result -->
diff --git a/src/fdk_rdf_parser/parse_functions/concept.py b/src/fdk_rdf_parser/parse_functions/concept.py index c20652a..cb07846 100644 --- a/src/fdk_rdf_parser/parse_functions/concept.py +++ b/src/fdk_rdf_parser/parse_functions/concept.py @@ -260,7 +260,9 @@ def parse_associative_relation( description=value_translations( graph, associative_relation_ref, skosno_uri("relationRole") ), - related=object_value(graph, associative_relation_ref, SKOS.related), + related=object_value( + graph, associative_relation_ref, skosno_uri("hasToConcept") + ), ) @@ -268,16 +270,18 @@ def extract_associative_relations( graph: Graph, concept_uri: URIRef ) -> Optional[List[AssociativeRelation]]: associative_relations = [] - for associative_relation_ref in graph.objects( - concept_uri, skosno_uri("assosiativRelasjon") - ): - if has_value_on_predicate( - graph, associative_relation_ref, skosno_uri("relationRole") + + if has_value_on_predicate(graph, concept_uri, skosno_uri("isFromConceptIn")): + for associative_relation_ref in graph.objects( + concept_uri, skosno_uri("isFromConceptIn") ): associative_relations.append( parse_associative_relation(graph, associative_relation_ref) ) - else: + else: + for associative_relation_ref in graph.objects( + concept_uri, skosno_uri("assosiativRelasjon") + ): associative_relations.append( parse_associative_relation_deprecated(graph, associative_relation_ref) )
ny assosiativ relasjon fra skos-ap-no v2.0.3 ref https://data.norge.no/specification/skos-ap-no-begrep#Begrep-er-fra-begrep-i og https://data.norge.no/specification/skos-ap-no-begrep#Assosiativ-begrepsrelasjon - predikat for angivelse av assosiativ relasjon endres fra `skosno:assosiativRelasjon` til `skosno:isFromConceptIn` - type endres fra `skosno:AssosiativRelasjon` til `skosno:AssociativeConceptRelation` (har ikke effekt i parse-kode) - predikat for assosiert begrep endres fra `skos:related` til `skosno:hasToConcept` - predikat for tilhørende tekst endres fra `dct:description` til `skosno:relationRole` (løst av https://github.com/Informasjonsforvaltning/fdk-rdf-parser/pull/292) ```` <etBegrep> a skos:Concept ; skosno:isFromConceptIn [ a skosno:AssociativeConceptRelation ; skosno:relationRole "årsak-virkning"@nb ; skosno:hasToConcept <etAnnetBegrep> ; ] . ```` er ekvivalent med dette fra gammel skos-ap-no: ```` <etBegrep> a skos:Concept ; skosno:assosiativRelasjon [ a skosno:AssosiativRelasjon ; dct:description "årsak-virkning"@nb ; skos:related <etAnnetBegrep> ; ] . ```` tldr: det er to ting som må endres: - predikat for angivelse av assosiert relasjon må støtte både `skosno:assosiativRelasjon` og `skosno:isFromConceptIn` - predikat for angivelse av det relaterte begrepet skal være `skos:related` for gammel skos og `skosno:hasToConcept` for ny skos
Informasjonsforvaltning/fdk-rdf-parser
diff --git a/tests/test_concept.py b/tests/test_concept.py index 7b4dc47..0d0466a 100644 --- a/tests/test_concept.py +++ b/tests/test_concept.py @@ -81,13 +81,9 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: skosxl:prefLabel [ a skosxl:Label ; skosxl:literalForm "to"@nb ] ; - skosno:assosiativRelasjon [ rdf:type skosno:AssosiativRelasjon ; + skosno:isFromConceptIn [ rdf:type skosno:AssociativeConceptRelation ; skosno:relationRole "RelationRole"@nb ; - skos:related <http://begrepskatalogen/begrep/organisasjon> - ] ; - skosno:assosiativRelasjon [ rdf:type skosno:AssosiativRelasjon ; - dct:description "Beskrivelse"@nb ; - skos:related <http://begrepskatalogen/begrep/virksomhet> + skosno:hasToConcept <http://begrepskatalogen/begrep/organisasjon> ] ; skosno:partitivRelasjon [ rdf:type skosno:PartitivRelasjon ; dct:description "Inndelingskriterium"@nb ; @@ -123,6 +119,9 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: dct:modified "2020-09-08"^^xsd:date ; dct:publisher <https://data.brreg.no/enhetsregisteret/api/enheter/910258028> ; dct:subject [ ] ; + skosno:assosiativRelasjon [ rdf:type skosno:AssosiativRelasjon ; + dct:description "Beskrivelse"@nb ; + skos:related <http://begrepskatalogen/begrep/virksomhet> ] ; euvoc:status "status nb" , "status en"@en ; skosxl:altLabel [ a skosxl:Label ; skosxl:literalForm "stabilisator"@nb @@ -302,6 +301,11 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ], ), definitions=[ + Definition( + text={"nb": "def-2"}, + targetGroup="https://data.norge.no/vocabulary/audience-type#public", + sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", + ), Definition( text={"nb": "def-1"}, sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", @@ -311,21 +315,12 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ) ], ), - Definition( - text={"nb": "def-2"}, - targetGroup="https://data.norge.no/vocabulary/audience-type#public", - sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", - ), ], associativeRelation=[ AssociativeRelation( description={"nb": "RelationRole"}, related="http://begrepskatalogen/begrep/organisasjon", - ), - AssociativeRelation( - description={"nb": "Beskrivelse"}, - related="http://begrepskatalogen/begrep/virksomhet", - ), + ) ], partitiveRelation=[ PartitiveRelation( @@ -369,6 +364,12 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ), prefLabel={"nb": "midtbaneanker"}, status={"nb": "status nb", "en": "status en"}, + associativeRelation=[ + AssociativeRelation( + description={"nb": "Beskrivelse"}, + related="http://begrepskatalogen/begrep/virksomhet", + ), + ], altLabel=[{"nb": "stabilisator"}], definition=Definition(text={"nb": "ugyldig-audience-og-forholdtilkilde"}), definitions=[ @@ -501,10 +502,10 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ) ], seeAlso={ - "http://begrepskatalogen/begrep/be5d8b8b-c3fb-11e9-8d53-005056825ca0", "http://begrepskatalogen/begrep/20b2e2ab-9fe1-11e5-a9f8-e4115b280940", - "https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/3609b02d-72c5-47e0-a6b8-df0a503cf190", "http://begrepskatalogen/begrep/20b2e2aa-9fe1-11e5-a9f8-e4115b280940", + "http://begrepskatalogen/begrep/be5d8b8b-c3fb-11e9-8d53-005056825ca0", + "https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/3609b02d-72c5-47e0-a6b8-df0a503cf190", }, isReplacedBy={ "http://begrepskatalogen/begrep/be5d8b8b-c3fb-11e9-8d53-005056825ca0"
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
2.7
{ "env_vars": null, "env_yml_path": null, "install": "poetry install", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "poetry", "pip_packages": [ "pytest", "pytest-cov", "pytest-mock" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.6.0 argcomplete==3.3.0 attrs==23.2.0 Authlib==1.3.0 bandit==1.7.8 black==24.4.2 Brotli @ file:///croot/brotli-split_1736182456865/work build @ file:///croot/python-build_1679596508056/work CacheControl @ file:///croot/cachecontrol-split_1676365553644/work certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 cleo @ file:///croot/cleo_1705431334181/work click==8.1.7 codecov==2.1.13 colorlog==6.8.2 coverage==7.5.0 crashtest @ file:///croot/crashtest_1679422372509/work cryptography==42.0.5 distlib==0.3.8 dparse==0.6.4b0 dulwich @ file:///croot/dulwich_1679420040193/work exceptiongroup==1.2.1 -e git+https://github.com/Informasjonsforvaltning/fdk-rdf-parser.git@6f2ba3bef2611d35b28a1e26831f58dfeb456325#egg=fdk_rdf_parser filelock==3.13.4 flake8==7.0.0 flake8-annotations==3.0.1 flake8-bandit==4.1.1 flake8-black==0.3.6 flake8-bugbear==24.4.26 flake8-import-order==0.18.2 html5lib @ file:///Users/ktietz/demo/mc3/conda-bld/html5lib_1629144453894/work idna==3.7 importlib_metadata @ file:///croot/importlib_metadata-suite_1732633488278/work iniconfig==2.0.0 installer @ file:///croot/python-installer_1679432998036/work isodate==0.6.1 jaraco.classes @ file:///tmp/build/80754af9/jaraco.classes_1620983179379/work jeepney @ file:///tmp/build/80754af9/jeepney_1627537048313/work Jinja2==3.1.3 jsonschema @ file:///croot/jsonschema_1728486696720/work jsonschema-specifications @ file:///croot/jsonschema-specifications_1699032386549/work keyring @ file:///croot/keyring_1678999217139/work lockfile==0.12.2 markdown-it-py==3.0.0 MarkupSafe==2.1.5 marshmallow==3.21.1 mccabe==0.7.0 mdurl==0.1.2 more-itertools @ file:///croot/more-itertools_1727185441804/work msgpack @ file:///opt/conda/conda-bld/msgpack-python_1652362659880/work mypy==1.10.0 mypy-extensions==1.0.0 nox==2024.4.15 nox-poetry==1.0.3 numpy @ file:///croot/numpy_and_numpy_base_1725470312869/work/dist/numpy-2.0.1-cp39-cp39-linux_x86_64.whl#sha256=b8c18bbfe185fbdff23024458e4b8ffbe2040e705abd5fb6cda1ef9d20b5974d packaging==24.0 pathspec==0.12.1 pbr==6.0.0 pep8-naming==0.13.3 pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pkginfo @ file:///croot/pkginfo_1743184746806/work platformdirs==4.2.1 pluggy==1.5.0 poetry @ file:///croot/poetry_1680193142998/work poetry-core @ file:///croot/poetry-core_1680018645313/work poetry-plugin-export @ file:///croot/poetry-plugin-export_1680122784541/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl pycodestyle==2.11.1 pycparser==2.22 pydantic==2.7.1 pydantic_core==2.18.2 pyflakes==3.2.0 Pygments==2.17.2 pyOpenSSL @ file:///croot/pyopenssl_1741343803032/work pyparsing==3.1.2 pyproject_hooks @ file:///croot/pyproject_hooks_1679584411881/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305812635/work pytest==8.2.0 pytest-cov==5.0.0 pytest-mock==3.14.0 PyYAML==6.0.1 RapidFuzz @ file:///croot/rapidfuzz_1738592335633/work rdflib==7.0.0 referencing @ file:///croot/referencing_1699012038513/work requests==2.31.0 requests-toolbelt @ file:///Users/ktietz/demo/mc3/conda-bld/requests-toolbelt_1629456163440/work rich==13.7.1 rpds-py @ file:///croot/rpds-py_1736541261634/work ruamel.yaml==0.18.6 ruamel.yaml.clib==0.2.8 safety==3.1.0 safety-schemas==0.0.2 SecretStorage @ file:///croot/secretstorage_1678709481048/work shellingham==1.5.4 six==1.16.0 stevedore==5.2.0 tomli==2.0.1 tomlkit==0.12.4 trove-classifiers @ file:///croot/trove-classifiers_1729277230900/work typer==0.12.3 typing_extensions==4.11.0 urllib3==2.2.1 virtualenv==20.26.0 webencodings==0.5.1 zipp @ file:///croot/zipp_1732630741423/work
name: fdk-rdf-parser channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - blas=1.0=openblas - brotli-python=1.0.9=py39h6a678d5_9 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - cachecontrol=0.12.11=py39h06a4308_1 - charset-normalizer=3.3.2=pyhd3eb1b0_0 - cleo=2.1.0=py39h06a4308_0 - crashtest=0.4.1=py39h06a4308_0 - dbus=1.13.18=hb2f20db_0 - distlib=0.3.8=py39h06a4308_0 - dulwich=0.21.3=py39h5eee18b_0 - expat=2.6.4=h6a678d5_0 - glib=2.78.4=h6a678d5_0 - glib-tools=2.78.4=h6a678d5_0 - html5lib=1.1=pyhd3eb1b0_0 - idna=3.7=py39h06a4308_0 - importlib-metadata=8.5.0=py39h06a4308_0 - importlib_metadata=8.5.0=hd3eb1b0_0 - jaraco.classes=3.2.1=pyhd3eb1b0_0 - jeepney=0.7.1=pyhd3eb1b0_0 - jsonschema=4.23.0=py39h06a4308_0 - jsonschema-specifications=2023.7.1=py39h06a4308_0 - keyring=23.13.1=py39h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=11.2.0=h00389a5_1 - libgfortran5=11.2.0=h1234567_1 - libglib=2.78.4=hdc74915_0 - libgomp=11.2.0=h1234567_1 - libiconv=1.16=h5eee18b_3 - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - lockfile=0.12.2=py39h06a4308_0 - more-itertools=10.3.0=py39h06a4308_0 - msgpack-python=1.0.3=py39hd09550d_0 - ncurses=6.4=h6a678d5_0 - numpy=2.0.1=py39heeff2f4_1 - numpy-base=2.0.1=py39h8a23956_1 - openssl=3.0.16=h5eee18b_0 - pcre2=10.42=hebb0a14_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pip=25.0=py39h06a4308_0 - pkginfo=1.12.0=py39h06a4308_0 - poetry=1.4.0=py39h06a4308_0 - poetry-core=1.5.1=py39h06a4308_0 - poetry-plugin-export=1.3.0=py39h4849bfd_0 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pyopenssl=25.0.0=py39h06a4308_0 - pyproject_hooks=1.0.0=py39h06a4308_0 - pysocks=1.7.1=py39h06a4308_0 - python=3.9.21=he870216_1 - python-build=0.10.0=py39h06a4308_0 - python-installer=0.6.0=py39h06a4308_0 - rapidfuzz=3.12.1=py39h6a678d5_0 - readline=8.2=h5eee18b_0 - referencing=0.30.2=py39h06a4308_0 - requests-toolbelt=0.9.1=pyhd3eb1b0_0 - rpds-py=0.22.3=py39h4aa5aa6_0 - secretstorage=3.3.1=py39h06a4308_1 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - trove-classifiers=2024.10.14=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - webencodings=0.5.1=py39h06a4308_1 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.21.0=py39h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.6.0 - argcomplete==3.3.0 - attrs==23.2.0 - authlib==1.3.0 - bandit==1.7.8 - black==24.4.2 - certifi==2024.2.2 - cffi==1.16.0 - click==8.1.7 - codecov==2.1.13 - colorlog==6.8.2 - coverage==7.5.0 - cryptography==42.0.5 - dparse==0.6.4b0 - exceptiongroup==1.2.1 - fdk-rdf-parser==2.7.2 - filelock==3.13.4 - flake8==7.0.0 - flake8-annotations==3.0.1 - flake8-bandit==4.1.1 - flake8-black==0.3.6 - flake8-bugbear==24.4.26 - flake8-import-order==0.18.2 - iniconfig==2.0.0 - isodate==0.6.1 - jinja2==3.1.3 - markdown-it-py==3.0.0 - markupsafe==2.1.5 - marshmallow==3.21.1 - mccabe==0.7.0 - mdurl==0.1.2 - mypy==1.10.0 - mypy-extensions==1.0.0 - nox==2024.4.15 - nox-poetry==1.0.3 - packaging==24.0 - pathspec==0.12.1 - pbr==6.0.0 - pep8-naming==0.13.3 - platformdirs==4.2.1 - pluggy==1.5.0 - pycodestyle==2.11.1 - pycparser==2.22 - pydantic==2.7.1 - pydantic-core==2.18.2 - pyflakes==3.2.0 - pygments==2.17.2 - pyparsing==3.1.2 - pytest==8.2.0 - pytest-cov==5.0.0 - pytest-mock==3.14.0 - pyyaml==6.0.1 - rdflib==7.0.0 - requests==2.31.0 - rich==13.7.1 - ruamel-yaml==0.18.6 - ruamel-yaml-clib==0.2.8 - safety==3.1.0 - safety-schemas==0.0.2 - setuptools==69.5.1 - shellingham==1.5.4 - stevedore==5.2.0 - tomlkit==0.12.4 - typer==0.12.3 - typing-extensions==4.11.0 - urllib3==2.2.1 - virtualenv==20.26.0 prefix: /opt/conda/envs/fdk-rdf-parser
[ "tests/test_concept.py::test_parse_concepts" ]
[]
[ "tests/test_concept.py::test_parse_concept_handles_wrong_collection_type", "tests/test_concept.py::test_parse_concept" ]
[]
Apache License 2.0
18,495
400
[ "src/fdk_rdf_parser/parse_functions/concept.py" ]
tobymao__sqlglot-3541
ebf5fc70d8936b5e1522a3ae1b9e231cefe49623
2024-05-23 18:06:34
1e1dc3fea8c5fc1f86fefe6af384e38c8531f2d2
diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 3237cd1c..1cd5b79c 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -4060,7 +4060,7 @@ class Parser(metaclass=_Parser): return this return self.expression(exp.Escape, this=this, expression=self._parse_string()) - def _parse_interval(self, match_interval: bool = True) -> t.Optional[exp.Interval]: + def _parse_interval(self, match_interval: bool = True) -> t.Optional[exp.Add | exp.Interval]: index = self._index if not self._match(TokenType.INTERVAL) and match_interval: @@ -4106,7 +4106,19 @@ class Parser(metaclass=_Parser): exp.IntervalSpan, this=unit, expression=self._parse_var(any_token=True, upper=True) ) - return self.expression(exp.Interval, this=this, unit=unit) + interval = self.expression(exp.Interval, this=this, unit=unit) + + index = self._index + self._match(TokenType.PLUS) + + # Convert INTERVAL 'val_1' unit_1 [+] ... [+] 'val_n' unit_n into a sum of intervals + if self._match_set((TokenType.STRING, TokenType.NUMBER), advance=False): + return self.expression( + exp.Add, this=interval, expression=self._parse_interval(match_interval=False) + ) + + self._retreat(index) + return interval def _parse_bitwise(self) -> t.Optional[exp.Expression]: this = self._parse_term() @@ -4173,38 +4185,32 @@ class Parser(metaclass=_Parser): ) -> t.Optional[exp.Expression]: interval = parse_interval and self._parse_interval() if interval: - # Convert INTERVAL 'val_1' unit_1 [+] ... [+] 'val_n' unit_n into a sum of intervals - while True: - index = self._index - self._match(TokenType.PLUS) - - if not self._match_set((TokenType.STRING, TokenType.NUMBER), advance=False): - self._retreat(index) - break - - interval = self.expression( # type: ignore - exp.Add, this=interval, expression=self._parse_interval(match_interval=False) - ) - return interval index = self._index data_type = self._parse_types(check_func=True, allow_identifiers=False) - this = self._parse_column() if data_type: + index2 = self._index + this = self._parse_primary() + if isinstance(this, exp.Literal): parser = self.TYPE_LITERAL_PARSERS.get(data_type.this) if parser: return parser(self, this, data_type) + return self.expression(exp.Cast, this=this, to=data_type) - if not data_type.expressions: - self._retreat(index) - return self._parse_id_var() if fallback_to_identifier else self._parse_column() + if data_type.expressions: + self._retreat(index2) + return self._parse_column_ops(data_type) - return self._parse_column_ops(data_type) + self._retreat(index) + if fallback_to_identifier: + return self._parse_id_var() + + this = self._parse_column() return this and self._parse_column_ops(this) def _parse_type_size(self) -> t.Optional[exp.DataTypeParam]:
Possible regression when parsing complex types with databricks dialect The following code will throw `sqlglot.errors.ParseError: Expecting >`, even though it was previously working. ```python import sqlglot sql = """ CREATE TABLE IF NOT EXISTS db.table ( a ARRAY< STRUCT< b INT COMMENT 'nested comment', c: MAP<STRING,STRING> > > COMMENT 'complex type' ) USING DELTA """ sqlglot.parse_one(sql, read="databricks") ``` This code works until version `23.16.0` and fails starting from version `23.17.0` (and including the latest version, `24.0.0`). #### Additional notes In addition to the behavior described above, version `23.17.0` also changed the result of parsing complex types, even when the parsing does not fail: ```python from sqlglot import exp, parse_one sql = """ CREATE TABLE db.table ( area STRUCT< base: INT COMMENT 'a nested int', height: INT NOT NULL COMMENT 'another nested int' > NOT NULL COMMENT 'a struct column' ) USING DELTA """ parsed_sql = parse_one(sql, read="databricks") exp_schema = parsed_sql.find(exp.Schema, bfs=True) column_def = exp_schema.find(exp.ColumnDef, bfs=True) column_type = column_def.find(exp.DataType, bfs=True) nested_type = column_type.find(exp.ColumnDef, bfs=True) print([type(x) for x in nested_type.iter_expressions()]) ``` Running the above code, the output with version `23.16.0` is ``` [<class 'sqlglot.expressions.Identifier'>, <class 'sqlglot.expressions.DataType'>, <class 'sqlglot.expressions.ColumnConstraint'>] ``` With version `23.17.0` instead, it is ``` [<class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.ColumnConstraint'>] ```
tobymao/sqlglot
diff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py index f050cfa9..4150d32a 100644 --- a/tests/dialects/test_databricks.py +++ b/tests/dialects/test_databricks.py @@ -9,6 +9,7 @@ class TestDatabricks(Validator): def test_databricks(self): self.validate_identity("DESCRIBE HISTORY a.b") self.validate_identity("DESCRIBE history.tbl") + self.validate_identity("CREATE TABLE t (a STRUCT<c: MAP<STRING, STRING>>)") self.validate_identity("CREATE TABLE t (c STRUCT<interval: DOUBLE COMMENT 'aaa'>)") self.validate_identity("CREATE TABLE my_table TBLPROPERTIES (a.b=15)") self.validate_identity("CREATE TABLE my_table TBLPROPERTIES ('a.b'=15)")
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
24.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 filelock==3.18.0 identify==2.6.9 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pre_commit==4.2.0 Pygments==2.19.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@ebf5fc70d8936b5e1522a3ae1b9e231cefe49623#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - pygments==2.19.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_databricks.py::TestDatabricks::test_databricks" ]
[]
[ "tests/dialects/test_databricks.py::TestDatabricks::test_add_date", "tests/dialects/test_databricks.py::TestDatabricks::test_datediff", "tests/dialects/test_databricks.py::TestDatabricks::test_json", "tests/dialects/test_databricks.py::TestDatabricks::test_without_as" ]
[]
MIT License
18,497
805
[ "sqlglot/parser.py" ]
googleapis__python-logging-898
f92c9b832b2644187e7dd6c10c41cf6b666026a0
2024-05-23 18:54:13
a49f78ce7a044bd545508898dc7a6bc81b035cad
diff --git a/google/cloud/logging_v2/client.py b/google/cloud/logging_v2/client.py index 13aca9e..9a4e520 100644 --- a/google/cloud/logging_v2/client.py +++ b/google/cloud/logging_v2/client.py @@ -32,8 +32,14 @@ from google.cloud.logging_v2.handlers import StructuredLogHandler from google.cloud.logging_v2.handlers import setup_logging from google.cloud.logging_v2.handlers.handlers import EXCLUDED_LOGGER_DEFAULTS from google.cloud.logging_v2.resource import Resource -from google.cloud.logging_v2.handlers._monitored_resources import detect_resource - +from google.cloud.logging_v2.handlers._monitored_resources import ( + detect_resource, + _GAE_RESOURCE_TYPE, + _GKE_RESOURCE_TYPE, + _GCF_RESOURCE_TYPE, + _RUN_RESOURCE_TYPE, + _CLOUD_RUN_JOB_RESOURCE_TYPE, +) from google.cloud.logging_v2.logger import Logger from google.cloud.logging_v2.metric import Metric @@ -56,11 +62,6 @@ except ImportError: # pragma: NO COVER _USE_GRPC = _HAVE_GRPC and not _DISABLE_GRPC -_GAE_RESOURCE_TYPE = "gae_app" -_GKE_RESOURCE_TYPE = "k8s_container" -_GCF_RESOURCE_TYPE = "cloud_function" -_RUN_RESOURCE_TYPE = "cloud_run_revision" - class Client(ClientWithProject): """Client to bundle configuration needed for API requests.""" @@ -381,6 +382,7 @@ class Client(ClientWithProject): _GKE_RESOURCE_TYPE, _GCF_RESOURCE_TYPE, _RUN_RESOURCE_TYPE, + _CLOUD_RUN_JOB_RESOURCE_TYPE, ] if ( diff --git a/google/cloud/logging_v2/handlers/_monitored_resources.py b/google/cloud/logging_v2/handlers/_monitored_resources.py index 5240fe7..c15c42d 100644 --- a/google/cloud/logging_v2/handlers/_monitored_resources.py +++ b/google/cloud/logging_v2/handlers/_monitored_resources.py @@ -60,6 +60,9 @@ _ZONE_ID = "instance/zone" _GCE_INSTANCE_ID = "instance/id" """Attribute in metadata server for compute region and instance.""" +_GKE_RESOURCE_TYPE = "k8s_container" +"""Resource type for the GKE environment.""" + _GKE_CLUSTER_NAME = "instance/attributes/cluster-name" """Attribute in metadata server when in GKE environment.""" @@ -72,6 +75,12 @@ _PROJECT_NAME = "project/project-id" _GAE_RESOURCE_TYPE = "gae_app" """Resource type for App Engine environment.""" +_GCF_RESOURCE_TYPE = "cloud_function" +"""Resource type for Cloud Functions environment.""" + +_RUN_RESOURCE_TYPE = "cloud_run_revision" +"""Resource type for Cloud Run environment.""" + _CLOUD_RUN_JOB_RESOURCE_TYPE = "cloud_run_job" """Resource type for Cloud Run Jobs."""
Let Cloud Run Job use `StructuredLogHandler` instead of `ClougLoggingHandler` Thanks for stopping by to let us know something could be better! **PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response. **Is your feature request related to a problem? Please describe.** When using `Client.get_default_handler` `CloudLoggingHandler` is being used automatically for Cloud Run jobs resource. And while https://github.com/googleapis/python-logging/pull/877 fixes the missing labels we're still gonna be using background transport when simplier stdout is doing just fine. **Describe the solution you'd like** If we modify this check https://github.com/googleapis/python-logging/blob/62641075042a3da9bb9c059d963bad14a1586b1c/google/cloud/logging_v2/client.py#L388 and allow `_RUN_RESOURCE_TYPE` OR `_CLOUD_RUN_JOB_RESOURCE_TYPE` resource type then a structured log handler is gonna be used automatically which should be a better default. **Describe alternatives you've considered** Meanwhile I am using `handler = StructuredLogHandler(project_id=client.project)` instead of `handler = client.get_default_handler()` where client is `client = CloudLoggingClient()`
googleapis/python-logging
diff --git a/tests/unit/test_client.py b/tests/unit/test_client.py index dc74009..4bfd984 100644 --- a/tests/unit/test_client.py +++ b/tests/unit/test_client.py @@ -798,6 +798,26 @@ class TestClient(unittest.TestCase): self.assertIsInstance(handler, StructuredLogHandler) + def test_get_default_handler_cloud_run_jobs(self): + import os + from google.cloud._testing import _Monkey + from google.cloud.logging_v2.handlers._monitored_resources import ( + _CLOUD_RUN_JOB_ENV_VARS, + ) + from google.cloud.logging.handlers import StructuredLogHandler + + credentials = _make_credentials() + client = self._make_one( + project=self.PROJECT, credentials=credentials, _use_grpc=False + ) + + cloud_run_job_env_vars = {var: "TRUE" for var in _CLOUD_RUN_JOB_ENV_VARS} + + with _Monkey(os, environ=cloud_run_job_env_vars): + handler = client.get_default_handler() + + self.assertIsInstance(handler, StructuredLogHandler) + def test_get_default_handler_general(self): import io from google.cloud.logging.handlers import CloudLoggingHandler
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
3.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock", "backoff", "flaky" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "samples/snippets/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
backoff==2.2.1 cachetools==5.5.2 certifi==2025.1.31 charset-normalizer==3.4.1 Deprecated==1.2.18 exceptiongroup==1.2.2 flaky==3.8.1 google-api-core==2.24.2 google-auth==2.38.0 google-cloud-appengine-logging==1.6.1 google-cloud-audit-log==0.3.2 google-cloud-bigquery==3.20.1 google-cloud-core==2.4.3 -e git+https://github.com/googleapis/python-logging.git@f92c9b832b2644187e7dd6c10c41cf6b666026a0#egg=google_cloud_logging google-cloud-pubsub==2.21.1 google-cloud-storage==2.16.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 grpc-google-iam-v1==0.14.2 grpcio==1.71.0 grpcio-status==1.63.0rc1 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 mock==5.2.0 opentelemetry-api==1.31.1 packaging==24.2 pluggy==1.5.0 proto-plus==1.26.1 protobuf==4.25.6 pyasn1==0.6.1 pyasn1_modules==0.4.2 pytest==8.3.5 python-dateutil==2.9.0.post0 requests==2.32.3 rsa==4.9 six==1.17.0 tomli==2.2.1 urllib3==2.3.0 wrapt==1.17.2 zipp==3.21.0
name: python-logging channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - backoff==2.2.1 - cachetools==5.5.2 - certifi==2025.1.31 - charset-normalizer==3.4.1 - deprecated==1.2.18 - exceptiongroup==1.2.2 - flaky==3.8.1 - google-api-core==2.24.2 - google-auth==2.38.0 - google-cloud-appengine-logging==1.6.1 - google-cloud-audit-log==0.3.2 - google-cloud-bigquery==3.20.1 - google-cloud-core==2.4.3 - google-cloud-pubsub==2.21.1 - google-cloud-storage==2.16.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - grpc-google-iam-v1==0.14.2 - grpcio==1.71.0 - grpcio-status==1.63.0rc1 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - mock==5.2.0 - opentelemetry-api==1.31.1 - packaging==24.2 - pluggy==1.5.0 - proto-plus==1.26.1 - protobuf==4.25.6 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - requests==2.32.3 - rsa==4.9 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 - wrapt==1.17.2 - zipp==3.21.0 prefix: /opt/conda/envs/python-logging
[ "tests/unit/test_client.py::TestClient::test_get_default_handler_cloud_run_jobs" ]
[]
[ "tests/unit/test_client.py::TestClient::test_ctor_defaults", "tests/unit/test_client.py::TestClient::test_ctor_explicit", "tests/unit/test_client.py::TestClient::test_ctor_w_client_options_dict", "tests/unit/test_client.py::TestClient::test_ctor_w_client_options_object", "tests/unit/test_client.py::TestClient::test_ctor_w_empty_client_options", "tests/unit/test_client.py::TestClient::test_get_default_handler_app_engine", "tests/unit/test_client.py::TestClient::test_get_default_handler_container_engine", "tests/unit/test_client.py::TestClient::test_get_default_handler_general", "tests/unit/test_client.py::TestClient::test_list_entries_defaults", "tests/unit/test_client.py::TestClient::test_list_entries_explicit", "tests/unit/test_client.py::TestClient::test_list_entries_explicit_timestamp", "tests/unit/test_client.py::TestClient::test_list_metrics_no_paging", "tests/unit/test_client.py::TestClient::test_list_metrics_with_paging", "tests/unit/test_client.py::TestClient::test_list_sinks_no_paging", "tests/unit/test_client.py::TestClient::test_list_sinks_with_paging", "tests/unit/test_client.py::TestClient::test_logger", "tests/unit/test_client.py::TestClient::test_logging_api_w_gapic", "tests/unit/test_client.py::TestClient::test_logging_api_wo_gapic", "tests/unit/test_client.py::TestClient::test_metric_defaults", "tests/unit/test_client.py::TestClient::test_metric_explicit", "tests/unit/test_client.py::TestClient::test_metrics_api_w_gapic", "tests/unit/test_client.py::TestClient::test_metrics_api_wo_gapic", "tests/unit/test_client.py::TestClient::test_no_gapic_ctor", "tests/unit/test_client.py::TestClient::test_setup_logging", "tests/unit/test_client.py::TestClient::test_setup_logging_w_extra_kwargs", "tests/unit/test_client.py::TestClient::test_setup_logging_w_extra_kwargs_structured_log", "tests/unit/test_client.py::TestClient::test_sink_defaults", "tests/unit/test_client.py::TestClient::test_sink_explicit", "tests/unit/test_client.py::TestClient::test_sinks_api_w_gapic", "tests/unit/test_client.py::TestClient::test_sinks_api_wo_gapic", "tests/unit/test_client.py::TestClient::test_veneer_grpc_headers", "tests/unit/test_client.py::TestClient::test_veneer_http_headers" ]
[]
Apache License 2.0
18,498
663
[ "google/cloud/logging_v2/client.py", "google/cloud/logging_v2/handlers/_monitored_resources.py" ]
marshmallow-code__marshmallow-2271
c592536b649fab0bbfb4bc3f84b65577a13b8ca2
2024-05-24 12:07:26
c592536b649fab0bbfb4bc3f84b65577a13b8ca2
lafrech: LGTM. Not that it really matters but I think I'd test the whole payload rather than just the length. I mean I see no reason not to. Just a nitpick. We can merge as is. Thanks.
diff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py index 4f2d0c76..99210ce7 100644 --- a/src/marshmallow/schema.py +++ b/src/marshmallow/schema.py @@ -227,6 +227,7 @@ class SchemaOpts: self.dump_only = getattr(meta, "dump_only", ()) self.unknown = validate_unknown_parameter_value(getattr(meta, "unknown", RAISE)) self.register = getattr(meta, "register", True) + self.many = getattr(meta, "many", False) class Schema(base.SchemaABC, metaclass=SchemaMeta): @@ -343,6 +344,7 @@ class Schema(base.SchemaABC, metaclass=SchemaMeta): `OrderedDict`. - ``exclude``: Tuple or list of fields to exclude in the serialized result. Nested fields can be represented with dot delimiters. + - ``many``: Whether the data is a collection by default. - ``dateformat``: Default format for `Date <fields.Date>` fields. - ``datetimeformat``: Default format for `DateTime <fields.DateTime>` fields. - ``timeformat``: Default format for `Time <fields.Time>` fields. @@ -366,7 +368,7 @@ class Schema(base.SchemaABC, metaclass=SchemaMeta): *, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), - many: bool = False, + many: bool | None = None, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), @@ -380,7 +382,7 @@ class Schema(base.SchemaABC, metaclass=SchemaMeta): raise StringNotCollectionError('"exclude" should be a list of strings') # copy declared fields from metaclass self.declared_fields = copy.deepcopy(self._declared_fields) - self.many = many + self.many = self.opts.many if many is None else many self.only = only self.exclude: set[typing.Any] | typing.MutableSet[typing.Any] = set( self.opts.exclude
Setting many=True through Meta - SchemaOpts I would like to propose adding support for setting `many=True` within the `Meta` class of a schema in Marshmallow. This feature would allow developers to configure a schema to always handle lists of objects by default, streamlining schema instantiation (no need to set `many=True` at every instantiation), reducing code redundancy and increasing consistency while reducing errors (the schema always handles lists of objects as intended). It finds its use cases where the instantiation is not always in place, but is first passed e.g. to a decorator that does the instantiation, loading of the schema (etc. other logic). Currently, to achieve this behavior, we must either set `many=True` during schema instantiation or create a custom base schema that enforces this behavior. Some example workaround: ```python class MySchema(Schema): field = fields.String() class Meta: many = True @classmethod def create(cls, many=True, *args, **kwargs): return cls(many=many, *args, **kwargs) schema = MySchema.create() data = schema.load([{"field": "value"}]) schema = MySchema(many=True) data = schema.load([{"field": "value"}]) ``` Example of implemented: ```python from marshmallow import Schema class MySchema(Schema): class Meta: many = True schema = MySchema() data = schema.load([{"field": "value"}]) ``` Throws as expected ValidationError, because this options is not possible to be set through Meta as other options do. With this in place it would be always, if someone wants, giving more control, instead of just at the instance level. If this would be fine to be given a try, I'm happy to try and prepare a PR for that :smiley:
marshmallow-code/marshmallow
diff --git a/tests/test_options.py b/tests/test_options.py index 2b052a31..4200ab90 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -262,3 +262,19 @@ class TestIncludeOption: assert "email" in s._declared_fields.keys() assert "from" in s._declared_fields.keys() assert isinstance(s._declared_fields["from"], fields.Str) + + +class TestManyOption: + class ManySchema(Schema): + foo = fields.Str() + + class Meta: + many = True + + def test_many_by_default(self): + test = self.ManySchema() + assert test.load([{"foo": "bar"}]) == [{"foo": "bar"}] + + def test_explicit_single(self): + test = self.ManySchema(many=False) + assert test.load({"foo": "bar"}) == {"foo": "bar"}
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
3.21
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cachetools==5.5.2 cfgv==3.4.0 chardet==5.2.0 colorama==0.4.6 coverage==7.8.0 distlib==0.3.9 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/marshmallow-code/marshmallow.git@c592536b649fab0bbfb4bc3f84b65577a13b8ca2#egg=marshmallow nodeenv==1.9.1 packaging @ file:///croot/packaging_1734472117206/work platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre-commit==3.8.0 pyproject-api==1.9.0 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 pytz==2025.2 PyYAML==6.0.2 simplejson==3.20.1 tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 virtualenv==20.29.3
name: marshmallow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cachetools==5.5.2 - cfgv==3.4.0 - chardet==5.2.0 - colorama==0.4.6 - coverage==7.8.0 - distlib==0.3.9 - filelock==3.18.0 - identify==2.6.9 - marshmallow==3.21.2 - nodeenv==1.9.1 - platformdirs==4.3.7 - pre-commit==3.8.0 - pyproject-api==1.9.0 - pytest-cov==6.0.0 - pytz==2025.2 - pyyaml==6.0.2 - simplejson==3.20.1 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/marshmallow
[ "tests/test_options.py::TestManyOption::test_many_by_default" ]
[]
[ "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", "tests/test_options.py::TestIncludeOption::test_fields_are_added", "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", "tests/test_options.py::TestManyOption::test_explicit_single" ]
[]
MIT License
18,502
505
[ "src/marshmallow/schema.py" ]
DARMA-tasking__LB-analysis-framework-515
4467b0bef8e783468960f96ad820339f402b9707
2024-05-24 13:28:14
7c811843c9b6cd8ad7732b4a351eb74fc8c6f614
diff --git a/src/lbaf/Applications/LBAF_app.py b/src/lbaf/Applications/LBAF_app.py index 9c00900..167b2ad 100644 --- a/src/lbaf/Applications/LBAF_app.py +++ b/src/lbaf/Applications/LBAF_app.py @@ -121,7 +121,7 @@ class InternalParameters: # Ensure that vttv module was found if not using_vttv: - self.__logger.warning("Visualization enabled but vttv not found. No visualization will be generated.") + raise ModuleNotFoundError("Visualization enabled but vt-tv module not found.") # Retrieve mandatory visualization parameters try: diff --git a/src/lbaf/Applications/MoveCountsViewer.py b/src/lbaf/Applications/MoveCountsViewer.py index 52cc368..cb23723 100644 --- a/src/lbaf/Applications/MoveCountsViewer.py +++ b/src/lbaf/Applications/MoveCountsViewer.py @@ -2,7 +2,11 @@ import os import sys import csv import importlib -import vtk +try: + import vtk + using_vtk = True +except ModuleNotFoundError: + using_vtk = False # pylint:disable=C0413:wrong-import-position # Use lbaf module from source if lbaf package is not installed @@ -333,6 +337,10 @@ class MoveCountsViewer: writer.Write() def run(self): + # Raise error if vtk is not installed + if not using_vtk: + raise ModuleNotFoundError("Could not find vtk module, which is required for the MoveCountsViewer.") + """Run the MoveCountViewer logic.""" # Parse command line arguments self.__parse_args()
Different runtime errors occurring depending on whether vtk package is installed or not ## Steps to repeat Identical as those of #509 ## Observed errors ### If `vtk` package is **not** installed via `pip` ``` (lbaf39) [pppebay@aneto]~/Documents/Git/LB-analysis-framework/src/lbaf/Applications$ pip uninstall vtk Found existing installation: vtk 9.1.0 Uninstalling vtk-9.1.0: Would remove: /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtk-9.1.0.dist-info/* /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtk.py /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/* Proceed (Y/n)? Successfully uninstalled vtk-9.1.0 (lbaf39) [pppebay@aneto]~/Documents/Git/LB-analysis-framework/src/lbaf/Applications$ python LBAF_app.py -c ../../../config/test-vt-tv.yaml Traceback (most recent call last): File "/Users/pppebay/Documents/Git/LB-analysis-framework/src/lbaf/Applications/LBAF_app.py", line 19, in <module> import lbaf.IO.lbsStatistics as lbstats File "/Users/pppebay/Documents/Git/LB-analysis-framework/src/lbaf/__init__.py", line 21, in <module> from lbaf.Applications.MoveCountsViewer import MoveCountsViewer File "/Users/pppebay/Documents/Git/LB-analysis-framework/src/lbaf/Applications/MoveCountsViewer.py", line 5, in <module> import vtk ModuleNotFoundError: No module named 'vtk' ``` ### If `vtk` package installed via `pip` Prior to de-installing it a runtime error occurred, but following uninstallation and re-installation, the following **warning** is issued: ``` [LBAF_app] Executing with Python 3.9.19 objc[51824]: Class vtkCocoaTimer is implemented in both /Users/pppebay/Documents/Build/VTK-9.3.0@Release/lib/libvtkRenderingUI-9.3.9.3.dylib (0x102fa8200) and /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/.dylibs/libvtkRenderingUI-9.3.dylib (0x1203c43e0). One of the two will be used. Which one is undefined. objc[51824]: Class vtkCocoaFullScreenWindow is implemented in both /Users/pppebay/Documents/Build/VTK-9.3.0@Release/lib/libvtkRenderingOpenGL2-9.3.9.3.dylib (0x103fe4ba0) and /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/.dylibs/libvtkRenderingOpenGL2-9.3.dylib (0x153e16068). One of the two will be used. Which one is undefined. objc[51824]: Class vtkCocoaServer is implemented in both /Users/pppebay/Documents/Build/VTK-9.3.0@Release/lib/libvtkRenderingOpenGL2-9.3.9.3.dylib (0x103fe4bc8) and /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/.dylibs/libvtkRenderingOpenGL2-9.3.dylib (0x153e16090). One of the two will be used. Which one is undefined. objc[51824]: Class vtkCocoaGLView is implemented in both /Users/pppebay/Documents/Build/VTK-9.3.0@Release/lib/libvtkRenderingOpenGL2-9.3.9.3.dylib (0x103fe4c18) and /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/.dylibs/libvtkRenderingOpenGL2-9.3.dylib (0x153e160e0). One of the two will be used. Which one is undefined. objc[51825]: Class vtkCocoaTimer is implemented in both /Users/pppebay/Documents/Build/VTK-9.3.0@Release/lib/libvtkRenderingUI-9.3.9.3.dylib (0x10390c200) and /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/.dylibs/libvtkRenderingUI-9.3.dylib (0x111fdc3e0). One of the two will be used. Which one is undefined. objc[51825]: Class vtkCocoaFullScreenWindow is implemented in both /Users/pppebay/Documents/Build/VTK-9.3.0@Release/lib/libvtkRenderingOpenGL2-9.3.9.3.dylib (0x104948ba0) and /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/.dylibs/libvtkRenderingOpenGL2-9.3.dylib (0x166092068). One of the two will be used. Which one is undefined. objc[51825]: Class vtkCocoaServer is implemented in both /Users/pppebay/Documents/Build/VTK-9.3.0@Release/lib/libvtkRenderingOpenGL2-9.3.9.3.dylib (0x104948bc8) and /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/.dylibs/libvtkRenderingOpenGL2-9.3.dylib (0x166092090). One of the two will be used. Which one is undefined. objc[51825]: Class vtkCocoaGLView is implemented in both /Users/pppebay/Documents/Build/VTK-9.3.0@Release/lib/libvtkRenderingOpenGL2-9.3.9.3.dylib (0x104948c18) and /Users/pppebay/miniconda3/envs/lbaf39/lib/python3.9/site-packages/vtkmodules/.dylibs/libvtkRenderingOpenGL2-9.3.dylib (0x1660920e0). One of the two will be used. Which one is undefined. ``` but code runs to completion. It remains concerning to have this warning, e**specially considering the fact that before uninstall/reinstall** it resulted in a segfault as follows: ``` zsh: segmentation fault python LBAF_app.py -c ../../../config/test-vt-tv.yaml ``` ```
DARMA-tasking/LB-analysis-framework
diff --git a/tests/unit/IO/test_lbs_visualizer_deprecation.py b/tests/unit/IO/test_lbs_visualizer_deprecation.py index 563bece..002e2a6 100644 --- a/tests/unit/IO/test_lbs_visualizer_deprecation.py +++ b/tests/unit/IO/test_lbs_visualizer_deprecation.py @@ -22,7 +22,7 @@ class TestVizDeprecation(unittest.TestCase): config_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config", "conf_wrong_visualization.yml") pipes = subprocess.Popen(["python", "src/lbaf", "-c", config_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) std_err = pipes.communicate()[1].decode("utf-8") - assert "Visualization enabled but vttv not found. No visualization will be generated." in std_err + assert "Visualization enabled but vt-tv module not found." in std_err if __name__ == "__main__": unittest.main()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "tox", "coverage", "pylint", "pytest", "anybadge" ], "pre_install": [ "apt-get update", "apt-get install -y git xvfb" ], "python": "3.8", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
anybadge==1.9.0 astroid==2.9.3 attrs==25.3.0 Brotli==1.0.9 build==0.7.0 cachetools==5.5.2 chardet==5.2.0 colorama==0.4.6 contextlib2==21.6.0 coverage==6.3.2 cycler==0.12.1 distlib==0.3.9 docutils==0.19 filelock==3.16.1 fonttools==4.56.0 iniconfig==2.1.0 isort==5.13.2 Jinja2==3.1.2 joblib==1.4.2 kiwisolver==1.4.7 lazy-object-proxy==1.10.0 -e git+https://github.com/DARMA-tasking/LB-analysis-framework.git@4467b0bef8e783468960f96ad820339f402b9707#egg=lbaf MarkupSafe==2.1.5 matplotlib==3.5.3 mccabe==0.6.1 numpy==1.22.3 packaging==24.2 pep517==0.13.1 pillow==10.4.0 platformdirs==4.3.6 pluggy==1.5.0 py==1.11.0 Pygments==2.15.0 pylint==2.12.2 pyparsing==3.1.4 pyproject-api==1.8.0 pytest==7.1.1 python-dateutil==2.9.0.post0 PyYAML==6.0 schema==0.7.5 scikit-learn==1.0.2 scipy==1.10.1 six==1.17.0 threadpoolctl==3.5.0 toml==0.10.2 tomli==2.2.1 tox==4.6.0 typing_extensions==4.13.0 virtualenv==20.29.3 vtk==9.0.1 wrapt==1.13.3
name: LB-analysis-framework channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=24.2=py38h06a4308_0 - python=3.8.20=he870216_0 - readline=8.2=h5eee18b_0 - setuptools=75.1.0=py38h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.44.0=py38h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - anybadge==1.9.0 - astroid==2.9.3 - attrs==25.3.0 - brotli==1.0.9 - build==0.7.0 - cachetools==5.5.2 - chardet==5.2.0 - colorama==0.4.6 - contextlib2==21.6.0 - coverage==6.3.2 - cycler==0.12.1 - distlib==0.3.9 - docutils==0.19 - filelock==3.16.1 - fonttools==4.56.0 - iniconfig==2.1.0 - isort==5.13.2 - jinja2==3.1.2 - joblib==1.4.2 - kiwisolver==1.4.7 - lazy-object-proxy==1.10.0 - lbaf==1.0.2 - markupsafe==2.1.5 - matplotlib==3.5.3 - mccabe==0.6.1 - numpy==1.22.3 - packaging==24.2 - pep517==0.13.1 - pillow==10.4.0 - platformdirs==4.3.6 - pluggy==1.5.0 - py==1.11.0 - pygments==2.15.0 - pylint==2.12.2 - pyparsing==3.1.4 - pyproject-api==1.8.0 - pytest==7.1.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0 - schema==0.7.5 - scikit-learn==1.0.2 - scipy==1.10.1 - six==1.17.0 - threadpoolctl==3.5.0 - toml==0.10.2 - tomli==2.2.1 - tox==4.6.0 - typing-extensions==4.13.0 - virtualenv==20.29.3 - vtk==9.0.1 - wrapt==1.13.3 prefix: /opt/conda/envs/LB-analysis-framework
[ "tests/unit/IO/test_lbs_visualizer_deprecation.py::TestVizDeprecation::test_lbs_visualizer_config" ]
[]
[ "tests/unit/IO/test_lbs_visualizer_deprecation.py::TestVizDeprecation::test_lbs_visualizer_deprecation" ]
[]
BSD-3-Clause
18,504
423
[ "src/lbaf/Applications/LBAF_app.py", "src/lbaf/Applications/MoveCountsViewer.py" ]
Informasjonsforvaltning__fdk-rdf-parser-307
e2ff215db4d333aa5a7b2f6068aebc94261c9a16
2024-05-24 13:55:14
0a72edaddfd8858b4fe4830a24875fc1cc1be7fb
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/307?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 100.00%. Comparing base [(`e2ff215`)](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/commit/e2ff215db4d333aa5a7b2f6068aebc94261c9a16?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning) to head [(`936eb81`)](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/307?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning). <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #307 +/- ## ========================================= Coverage 100.00% 100.00% ========================================= Files 89 89 Lines 2372 2376 +4 Branches 265 266 +1 ========================================= + Hits 2372 2376 +4 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/307?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning). github-actions[bot]: ``` Warning: poetry-plugin-export will not be installed by default in a future version of Poetry. In order to avoid a breaking change and make your automation forward-compatible, please install poetry-plugin-export explicitly. See https://python-poetry.org/docs/plugins/#using-plugins for details on how to install a plugin. To disable this warning run 'poetry config warnings.export false'. The `--dev` option is deprecated, use the `--with dev` notation instead. +==============================================================================+ /$$$$$$ /$$ /$$__ $$ | $$ /$$$$$$$ /$$$$$$ | $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$_____/ |____ $$| $$$$ /$$__ $$|_ $$_/ | $$ | $$ | $$$$$$ /$$$$$$$| $$_/ | $$$$$$$$ | $$ | $$ | $$ \____ $$ /$$__ $$| $$ | $$_____/ | $$ /$$| $$ | $$ /$$$$$$$/| $$$$$$$| $$ | $$$$$$$ | $$$$/| $$$$$$$ |_______/ \_______/|__/ \_______/ \___/ \____ $$ /$$ | $$ | $$$$$$/ by safetycli.com \______/ +==============================================================================+ REPORT Safety is using PyUp's free open-source vulnerability database. This data is 30 days old and limited. For real-time enhanced vulnerability data, fix recommendations, severity reporting, cybersecurity support, team and project policy management and more sign up at https://pyup.io or email [email protected] Safety v3.1.0 is scanning for Vulnerabilities... Scanning dependencies in your files: -> /tmp/tmpillnwrxr Using open-source vulnerability database Found and scanned 72 packages Timestamp 2024-05-24 13:55:53 0 vulnerabilities reported 0 vulnerabilities ignored +==============================================================================+ No known security vulnerabilities found. +==============================================================================+ Safety is using PyUp's free open-source vulnerability database. This data is 30 days old and limited. For real-time enhanced vulnerability data, fix recommendations, severity reporting, cybersecurity support, team and project policy management and more sign up at https://pyup.io or email [email protected] +==============================================================================+ ``` <!-- Sticky Pull Request CommentSafety result -->
diff --git a/src/fdk_rdf_parser/parse_functions/concept.py b/src/fdk_rdf_parser/parse_functions/concept.py index cb07846..b8bb792 100644 --- a/src/fdk_rdf_parser/parse_functions/concept.py +++ b/src/fdk_rdf_parser/parse_functions/concept.py @@ -18,10 +18,7 @@ from rdflib.namespace import ( SKOS, ) -from fdk_rdf_parser.classes import ( - Concept, - Temporal, -) +from fdk_rdf_parser.classes import Concept from fdk_rdf_parser.classes.concept import ( AssociativeRelation, Collection, @@ -50,7 +47,7 @@ from fdk_rdf_parser.rdf_utils import ( from .contactpoint import extract_contact_points from .harvest_meta_data import extract_meta_data from .publisher import extract_publisher -from .temporal import extract_temporal +from .temporal import extract_temporal_skos def parse_text_and_uri(graph: Graph, subject: URIRef) -> TextAndURI: @@ -340,6 +337,15 @@ def extract_generic_relations( return generic_relations if len(generic_relations) > 0 else None +def extract_collection_label( + graph: Graph, collection_uri: URIRef +) -> Optional[Dict[str, str]]: + if has_literal_value_on_predicate(graph, collection_uri, DCTERMS.title): + return value_translations(graph, collection_uri, DCTERMS.title) + else: + return value_translations(graph, collection_uri, RDFS.label) + + def parse_collection(graph: Graph, concept_record_uri: URIRef) -> Optional[Collection]: collection_record_uri = graph.value(concept_record_uri, DCTERMS.isPartOf) @@ -352,7 +358,7 @@ def parse_collection(graph: Graph, concept_record_uri: URIRef) -> Optional[Colle return Collection( id=object_value(graph, collection_record_uri, DCTERMS.identifier), publisher=extract_publisher(graph, collection_uri), - label=value_translations(graph, collection_uri, RDFS.label), + label=extract_collection_label(graph, collection_uri), uri=collection_uri.toPython(), description=value_translations( graph, collection_uri, DCTERMS.description @@ -384,8 +390,8 @@ def extract_labels( def _parse_concept( graph: Graph, fdk_record_uri: URIRef, concept_uri: URIRef ) -> Concept: - concept_temporal_list = extract_temporal(graph, concept_uri) - concept_temporal = concept_temporal_list[0] if concept_temporal_list else Temporal() + + concept_temporal = extract_temporal_skos(graph, concept_uri) contact_points = extract_contact_points(graph, concept_uri) pref_label_list = extract_labels( diff --git a/src/fdk_rdf_parser/parse_functions/temporal.py b/src/fdk_rdf_parser/parse_functions/temporal.py index 42e9280..c5c3dca 100644 --- a/src/fdk_rdf_parser/parse_functions/temporal.py +++ b/src/fdk_rdf_parser/parse_functions/temporal.py @@ -14,6 +14,7 @@ from fdk_rdf_parser.classes import Temporal from fdk_rdf_parser.rdf_utils import ( date_value, dcat_uri, + euvoc_uri, owl_time_uri, resource_list, schema_uri, @@ -59,6 +60,24 @@ def extract_temporal(graph: Graph, subject: URIRef) -> Optional[List[Temporal]]: return values if len(values) > 0 else None +def extract_temporal_skos(graph: Graph, subject: URIRef) -> Temporal: + temporal = Temporal() + + start_value = date_value(graph, subject, euvoc_uri("startDate")) + end_value = date_value(graph, subject, euvoc_uri("endDate")) + + deprecated_resource = graph.value(subject, DCTERMS.temporal) + if start_value or end_value: + temporal = Temporal(startDate=start_value, endDate=end_value) + elif deprecated_resource is not None: + start_value = date_value(graph, deprecated_resource, schema_uri("startDate")) + end_value = date_value(graph, deprecated_resource, schema_uri("endDate")) + + temporal = Temporal(startDate=start_value, endDate=end_value) + + return temporal + + def extract_owl_time_instant(graph: Graph, subject: Any) -> Optional[str]: owl_date = date_value(graph, subject, owl_time_uri("inXSDDateTime")) owl_date = (
ny startDate & endDate fra skos-ap-no v.2.0.3 ref https://data.norge.no/specification/skos-ap-no-begrep#Begrep-dato-gyldig-fra-og-med og https://data.norge.no/specification/skos-ap-no-begrep#Begrep-dato-gyldig-til-og-med gyldig fra og til vil ikke lenger bli angitt via en liste med PeriodOfTime, kun direkte angitt på selve begrepet, og skal bruke euvoc:startDate og euvoc:endDate i stedet for hhv schema:startDate og schema:endDate Disse linjene bør flyttes ut til en egen metode og legge til støtte for v2.0.3 av skos-ap-no: https://github.com/Informasjonsforvaltning/fdk-rdf-parser/blob/main/src/fdk_rdf_parser/parse_functions/concept.py#L383-L384 Dvs dette i ny skos-ap-no: ```` euvoc:startDate "2020-05-29"^^xsd:date; euvoc:endDate "2021-05-29"^^xsd:date; ```` er ekvivalent med dette i gammel skos-ap-no: ```` dct:temporal [ a dct:PeriodOfTime ; schema:startDate "2020-05-29"^^xsd:date; schema:endDate "2021-05-29"^^xsd:date; ] ; ````
Informasjonsforvaltning/fdk-rdf-parser
diff --git a/tests/test_concept.py b/tests/test_concept.py index 0d0466a..c1bac4d 100644 --- a/tests/test_concept.py +++ b/tests/test_concept.py @@ -47,10 +47,11 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: @prefix xkos: <http://rdf-vocabulary.ddialliance.org/xkos#> . @prefix euvoc: <http://publications.europa.eu/ontology/euvoc#> . @prefix uneskos: <http://purl.org/umu/uneskos#> . +@prefix schema: <http://schema.org/> . <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028> a skos:Collection ; - rdfs:label "Concept collection belonging to 910258028" ; + dct:title "Concept collection belonging to 910258028" ; dct:identifier "https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028" ; dct:publisher <https://data.brreg.no/enhetsregisteret/api/enheter/910258028> ; skos:member <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/c4ae179e-6a3a-42bc-85a2-1e32d75fc013> , <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/3609b02d-72c5-47e0-a6b8-df0a503cf190> , <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/1843b048-f9af-4665-8e53-3c001d0166c0> , <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/9f25b5ad-8aa7-4233-853b-7434e20aeaef> , <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/523ff894-638b-44a2-a4fd-3e96a5a8a5a3> . @@ -65,6 +66,10 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/1843b048-f9af-4665-8e53-3c001d0166c0> a skos:Concept ; + dct:temporal [ a dct:PeriodOfTime ; + schema:startDate "2020-05-29"^^xsd:date; + schema:endDate "2021-05-29"^^xsd:date; + ] ; dct:created "2023-02-17"^^xsd:date ; dct:identifier "1843b048-f9af-4665-8e53-3c001d0166c0" ; dct:modified "2019-12-16"^^xsd:date ; @@ -301,11 +306,6 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ], ), definitions=[ - Definition( - text={"nb": "def-2"}, - targetGroup="https://data.norge.no/vocabulary/audience-type#public", - sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", - ), Definition( text={"nb": "def-1"}, sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", @@ -315,6 +315,11 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ) ], ), + Definition( + text={"nb": "def-2"}, + targetGroup="https://data.norge.no/vocabulary/audience-type#public", + sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", + ), ], associativeRelation=[ AssociativeRelation( @@ -343,6 +348,8 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ), ], type="concept", + validFromIncluding="2020-05-29", + validToIncluding="2021-05-29", ), "https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/3609b02d-72c5-47e0-a6b8-df0a503cf190": Concept( id="fc8baf8d-6146-3b69-93c5-52bd41592c4e", @@ -634,7 +641,9 @@ def test_parse_concept(mock_reference_data_client: Mock) -> None: skosno:valueRange "test-nn"@nn, "test", - <https://range.com> . + <https://range.com> ; + euvoc:startDate "2020-05-29"^^xsd:date; + euvoc:endDate "2021-05-29"^^xsd:date . <http://publications.europa.eu/resource/authority/concept-status/CURRENT> @@ -706,6 +715,8 @@ def test_parse_concept(mock_reference_data_client: Mock) -> None: ) ], type="concept", + validFromIncluding="2020-05-29", + validToIncluding="2021-05-29", ) result = parse_concept(src)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
2.7
{ "env_vars": null, "env_yml_path": null, "install": "poetry install", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "poetry", "pip_packages": [ "pytest", "pytest-cov", "pytest-mock" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.6.0 argcomplete==3.3.0 attrs==23.2.0 Authlib==1.3.0 bandit==1.7.8 black==24.4.2 Brotli @ file:///croot/brotli-split_1736182456865/work build @ file:///croot/python-build_1679596508056/work CacheControl @ file:///croot/cachecontrol-split_1676365553644/work certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 cleo @ file:///croot/cleo_1705431334181/work click==8.1.7 codecov==2.1.13 colorlog==6.8.2 coverage==7.5.0 crashtest @ file:///croot/crashtest_1679422372509/work cryptography==42.0.5 distlib==0.3.8 dparse==0.6.4b0 dulwich @ file:///croot/dulwich_1679420040193/work exceptiongroup==1.2.1 -e git+https://github.com/Informasjonsforvaltning/fdk-rdf-parser.git@e2ff215db4d333aa5a7b2f6068aebc94261c9a16#egg=fdk_rdf_parser filelock==3.13.4 flake8==7.0.0 flake8-annotations==3.0.1 flake8-bandit==4.1.1 flake8-black==0.3.6 flake8-bugbear==24.4.26 flake8-import-order==0.18.2 html5lib @ file:///Users/ktietz/demo/mc3/conda-bld/html5lib_1629144453894/work idna==3.7 importlib_metadata @ file:///croot/importlib_metadata-suite_1732633488278/work iniconfig==2.0.0 installer @ file:///croot/python-installer_1679432998036/work isodate==0.6.1 jaraco.classes @ file:///tmp/build/80754af9/jaraco.classes_1620983179379/work jeepney @ file:///tmp/build/80754af9/jeepney_1627537048313/work Jinja2==3.1.3 jsonschema @ file:///croot/jsonschema_1728486696720/work jsonschema-specifications @ file:///croot/jsonschema-specifications_1699032386549/work keyring @ file:///croot/keyring_1678999217139/work lockfile==0.12.2 markdown-it-py==3.0.0 MarkupSafe==2.1.5 marshmallow==3.21.1 mccabe==0.7.0 mdurl==0.1.2 more-itertools @ file:///croot/more-itertools_1727185441804/work msgpack @ file:///opt/conda/conda-bld/msgpack-python_1652362659880/work mypy==1.10.0 mypy-extensions==1.0.0 nox==2024.4.15 nox-poetry==1.0.3 numpy @ file:///croot/numpy_and_numpy_base_1725470312869/work/dist/numpy-2.0.1-cp39-cp39-linux_x86_64.whl#sha256=b8c18bbfe185fbdff23024458e4b8ffbe2040e705abd5fb6cda1ef9d20b5974d packaging==24.0 pathspec==0.12.1 pbr==6.0.0 pep8-naming==0.13.3 pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pkginfo @ file:///croot/pkginfo_1743184746806/work platformdirs==4.2.1 pluggy==1.5.0 poetry @ file:///croot/poetry_1680193142998/work poetry-core @ file:///croot/poetry-core_1680018645313/work poetry-plugin-export @ file:///croot/poetry-plugin-export_1680122784541/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl pycodestyle==2.11.1 pycparser==2.22 pydantic==2.7.1 pydantic_core==2.18.2 pyflakes==3.2.0 Pygments==2.17.2 pyOpenSSL @ file:///croot/pyopenssl_1741343803032/work pyparsing==3.1.2 pyproject_hooks @ file:///croot/pyproject_hooks_1679584411881/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305812635/work pytest==8.2.0 pytest-cov==5.0.0 pytest-mock==3.14.0 PyYAML==6.0.1 RapidFuzz @ file:///croot/rapidfuzz_1738592335633/work rdflib==7.0.0 referencing @ file:///croot/referencing_1699012038513/work requests==2.31.0 requests-toolbelt @ file:///Users/ktietz/demo/mc3/conda-bld/requests-toolbelt_1629456163440/work rich==13.7.1 rpds-py @ file:///croot/rpds-py_1736541261634/work ruamel.yaml==0.18.6 ruamel.yaml.clib==0.2.8 safety==3.1.0 safety-schemas==0.0.2 SecretStorage @ file:///croot/secretstorage_1678709481048/work shellingham==1.5.4 six==1.16.0 stevedore==5.2.0 tomli==2.0.1 tomlkit==0.12.4 trove-classifiers @ file:///croot/trove-classifiers_1729277230900/work typer==0.12.3 typing_extensions==4.11.0 urllib3==2.2.1 virtualenv==20.26.0 webencodings==0.5.1 zipp @ file:///croot/zipp_1732630741423/work
name: fdk-rdf-parser channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - blas=1.0=openblas - brotli-python=1.0.9=py39h6a678d5_9 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - cachecontrol=0.12.11=py39h06a4308_1 - charset-normalizer=3.3.2=pyhd3eb1b0_0 - cleo=2.1.0=py39h06a4308_0 - crashtest=0.4.1=py39h06a4308_0 - dbus=1.13.18=hb2f20db_0 - distlib=0.3.8=py39h06a4308_0 - dulwich=0.21.3=py39h5eee18b_0 - expat=2.6.4=h6a678d5_0 - glib=2.78.4=h6a678d5_0 - glib-tools=2.78.4=h6a678d5_0 - html5lib=1.1=pyhd3eb1b0_0 - idna=3.7=py39h06a4308_0 - importlib-metadata=8.5.0=py39h06a4308_0 - importlib_metadata=8.5.0=hd3eb1b0_0 - jaraco.classes=3.2.1=pyhd3eb1b0_0 - jeepney=0.7.1=pyhd3eb1b0_0 - jsonschema=4.23.0=py39h06a4308_0 - jsonschema-specifications=2023.7.1=py39h06a4308_0 - keyring=23.13.1=py39h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=11.2.0=h00389a5_1 - libgfortran5=11.2.0=h1234567_1 - libglib=2.78.4=hdc74915_0 - libgomp=11.2.0=h1234567_1 - libiconv=1.16=h5eee18b_3 - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - lockfile=0.12.2=py39h06a4308_0 - more-itertools=10.3.0=py39h06a4308_0 - msgpack-python=1.0.3=py39hd09550d_0 - ncurses=6.4=h6a678d5_0 - numpy=2.0.1=py39heeff2f4_1 - numpy-base=2.0.1=py39h8a23956_1 - openssl=3.0.16=h5eee18b_0 - pcre2=10.42=hebb0a14_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pip=25.0=py39h06a4308_0 - pkginfo=1.12.0=py39h06a4308_0 - poetry=1.4.0=py39h06a4308_0 - poetry-core=1.5.1=py39h06a4308_0 - poetry-plugin-export=1.3.0=py39h4849bfd_0 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pyopenssl=25.0.0=py39h06a4308_0 - pyproject_hooks=1.0.0=py39h06a4308_0 - pysocks=1.7.1=py39h06a4308_0 - python=3.9.21=he870216_1 - python-build=0.10.0=py39h06a4308_0 - python-installer=0.6.0=py39h06a4308_0 - rapidfuzz=3.12.1=py39h6a678d5_0 - readline=8.2=h5eee18b_0 - referencing=0.30.2=py39h06a4308_0 - requests-toolbelt=0.9.1=pyhd3eb1b0_0 - rpds-py=0.22.3=py39h4aa5aa6_0 - secretstorage=3.3.1=py39h06a4308_1 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - trove-classifiers=2024.10.14=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - webencodings=0.5.1=py39h06a4308_1 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.21.0=py39h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.6.0 - argcomplete==3.3.0 - attrs==23.2.0 - authlib==1.3.0 - bandit==1.7.8 - black==24.4.2 - certifi==2024.2.2 - cffi==1.16.0 - click==8.1.7 - codecov==2.1.13 - colorlog==6.8.2 - coverage==7.5.0 - cryptography==42.0.5 - dparse==0.6.4b0 - exceptiongroup==1.2.1 - fdk-rdf-parser==2.7.2 - filelock==3.13.4 - flake8==7.0.0 - flake8-annotations==3.0.1 - flake8-bandit==4.1.1 - flake8-black==0.3.6 - flake8-bugbear==24.4.26 - flake8-import-order==0.18.2 - iniconfig==2.0.0 - isodate==0.6.1 - jinja2==3.1.3 - markdown-it-py==3.0.0 - markupsafe==2.1.5 - marshmallow==3.21.1 - mccabe==0.7.0 - mdurl==0.1.2 - mypy==1.10.0 - mypy-extensions==1.0.0 - nox==2024.4.15 - nox-poetry==1.0.3 - packaging==24.0 - pathspec==0.12.1 - pbr==6.0.0 - pep8-naming==0.13.3 - platformdirs==4.2.1 - pluggy==1.5.0 - pycodestyle==2.11.1 - pycparser==2.22 - pydantic==2.7.1 - pydantic-core==2.18.2 - pyflakes==3.2.0 - pygments==2.17.2 - pyparsing==3.1.2 - pytest==8.2.0 - pytest-cov==5.0.0 - pytest-mock==3.14.0 - pyyaml==6.0.1 - rdflib==7.0.0 - requests==2.31.0 - rich==13.7.1 - ruamel-yaml==0.18.6 - ruamel-yaml-clib==0.2.8 - safety==3.1.0 - safety-schemas==0.0.2 - setuptools==69.5.1 - shellingham==1.5.4 - stevedore==5.2.0 - tomlkit==0.12.4 - typer==0.12.3 - typing-extensions==4.11.0 - urllib3==2.2.1 - virtualenv==20.26.0 prefix: /opt/conda/envs/fdk-rdf-parser
[ "tests/test_concept.py::test_parse_concepts", "tests/test_concept.py::test_parse_concept" ]
[]
[ "tests/test_concept.py::test_parse_concept_handles_wrong_collection_type" ]
[]
Apache License 2.0
18,505
1,054
[ "src/fdk_rdf_parser/parse_functions/concept.py", "src/fdk_rdf_parser/parse_functions/temporal.py" ]
tobymao__sqlglot-3547
57faa3ee222da9bddd517cb742401ef0aa53d233
2024-05-24 15:45:23
1e1dc3fea8c5fc1f86fefe6af384e38c8531f2d2
diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 1cd5b79c..8663bc5a 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -4274,7 +4274,7 @@ class Parser(metaclass=_Parser): if self._match(TokenType.L_PAREN): if is_struct: - expressions = self._parse_csv(self._parse_struct_types) + expressions = self._parse_csv(lambda: self._parse_struct_types(type_required=True)) elif nested: expressions = self._parse_csv( lambda: self._parse_types( @@ -4392,15 +4392,16 @@ class Parser(metaclass=_Parser): or self._parse_id_var() ) self._match(TokenType.COLON) - column_def = self._parse_column_def(this) - if type_required and ( - (isinstance(this, exp.Column) and this.this is column_def) or this is column_def + if ( + type_required + and not isinstance(this, exp.DataType) + and not self._match_set(self.TYPE_TOKENS, advance=False) ): self._retreat(index) return self._parse_types() - return column_def + return self._parse_column_def(this) def _parse_at_time_zone(self, this: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]: if not self._match_text_seq("AT", "TIME", "ZONE"):
Regression in parsing clickhouse tuple types On 23.17.0 this works: ``` In [1]: import sqlglot.expressions as sge, sqlglot as sg In [2]: sg.__version__ Out[2]: '23.17.0' In [3]: sg.parse_one('select cast(x as Tuple(String, Array(Nullable(Float64))))', read='clickhouse') Out[3]: Select( expressions=[ Cast( this=Column( this=Identifier(this=x, quoted=False)), to=DataType( this=Type.STRUCT, expressions=[ Identifier(this=String, quoted=False), Array( expressions=[ Anonymous( this=Nullable, expressions=[ Column( this=Identifier(this=Float64, quoted=False))])])], nested=True))]) ``` but fails to parse in 24.0.1: ``` In [1]: import sqlglot.expressions as sge, sqlglot as sg In [2]: sg.__version__ Out[2]: '24.0.1' In [3]: sg.parse_one('select cast(x as Tuple(String, Array(Nullable(Float64))))', read='clickhouse') ... ParseError: Expected TYPE after CAST. Line 1, Col: 22. select cast(x as Tuple(String, Array(Nullable(Float64)))) ```
tobymao/sqlglot
diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py index 15adda8a..72634a80 100644 --- a/tests/dialects/test_clickhouse.py +++ b/tests/dialects/test_clickhouse.py @@ -42,6 +42,7 @@ class TestClickhouse(Validator): self.assertEqual(expr.sql(dialect="clickhouse"), "COUNT(x)") self.assertIsNone(expr._meta) + self.validate_identity("SELECT CAST(x AS Tuple(String, Array(Nullable(Float64))))") self.validate_identity("countIf(x, y)") self.validate_identity("x = y") self.validate_identity("x <> y")
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
24.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pre-commit", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 Pygments==2.19.1 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@57faa3ee222da9bddd517cb742401ef0aa53d233#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - pygments==2.19.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse" ]
[]
[ "tests/dialects/test_clickhouse.py::TestClickhouse::test_agg_functions", "tests/dialects/test_clickhouse.py::TestClickhouse::test_cte", "tests/dialects/test_clickhouse.py::TestClickhouse::test_ddl", "tests/dialects/test_clickhouse.py::TestClickhouse::test_drop_on_cluster", "tests/dialects/test_clickhouse.py::TestClickhouse::test_parameterization", "tests/dialects/test_clickhouse.py::TestClickhouse::test_signed_and_unsigned_types", "tests/dialects/test_clickhouse.py::TestClickhouse::test_ternary" ]
[]
MIT License
18,506
347
[ "sqlglot/parser.py" ]
dag-hammarskjold-library__dlx-293
733e9cadb70ac2b520809bb0381c5bdd01718087
2024-05-24 19:05:56
7bc9c436adc657b48945eafa70a190381864e26c
diff --git a/dlx/config.py b/dlx/config.py index 89ded7e..6d2911d 100644 --- a/dlx/config.py +++ b/dlx/config.py @@ -101,7 +101,6 @@ class Config(): '130': ['adfgklnp'], '490': ['a'], '495': ['a'], - '245': ['p'], '495': ['a'], '765': ['t'], '767': ['t'], diff --git a/dlx/marc/query.py b/dlx/marc/query.py index ad0c2ca..defd40e 100644 --- a/dlx/marc/query.py +++ b/dlx/marc/query.py @@ -406,8 +406,10 @@ class Query(): # regex if isinstance(value, Regex): - matches = DB.handle[f'_index_{field}'].find({'text': value} if isinstance(value, WildcardRegex) else {'_id': value}) - values = [x['_id'] for x in matches] + if isinstance(value, WildcardRegex): + q = {'text': value} + else: + q = {'_id': value} # text else: quoted = re.findall(r'"(.+?)"', value) @@ -420,20 +422,20 @@ class Query(): if not value.strip(): raise Exception('Search term can\'t contain only negations') - - q = { - '$and': [ - {'words': {'$all': Tokenizer.tokenize(value)}} - ] - } - - if negated: - q['$and'].append({'words': {'$nin': Tokenizer.tokenize(' '.join(negated))}}) - - if quoted: - q['$and'].append({'text': Regex(' '.join(quoted))}) + + q = { + '$and': [ + {'words': {'$all': Tokenizer.tokenize(value)}} + ] + } + + if negated: + q['$and'].append({'words': {'$nin': Tokenizer.tokenize(' '.join(negated))}}) + + if quoted: + q['$and'].append({'text': Regex(' '.join(quoted))}) - matches = DB.handle[f'_index_{field}'].find(q) + matches = DB.handle[f'_index_{field}'].find(q) values = [x['_id'] for x in matches] if sys.getsizeof(values) > 1e6: # 1 MB @@ -648,7 +650,7 @@ class Condition(object): submatch = subconditions[0] if len(subconditions) == 1 else {'$all' : subconditions} if not self.modifier: - return SON({tag: {'$elemMatch': {'subfields': submatch}}}) + return SON({f'{tag}.subfields': submatch}) else: if self.modifier == 'not': return SON({'$or': [{tag: {'$not': {'$elemMatch': {'subfields': submatch}}}}, {tag: {'$exists': False}}]})
Wildcard in search string not working i.e. `query = Query.from_string('title:*test title*')`. Even though the test for this passes.
dag-hammarskjold-library/dlx
diff --git a/tests/test_marc.py b/tests/test_marc.py index 85e7596..397f7db 100644 --- a/tests/test_marc.py +++ b/tests/test_marc.py @@ -225,8 +225,8 @@ def test_querydocument(db): qjson = query.to_json() qdict = loads(qjson) - assert qdict['245']['$elemMatch']['subfields']['$elemMatch']['code'] == 'a' - assert qdict['245']['$elemMatch']['subfields']['$elemMatch']['value'] == 'This' + assert qdict['245.subfields']['$elemMatch']['code'] == 'a' + assert qdict['245.subfields']['$elemMatch']['value'] == 'This' query = Query( Condition(tag='245', subfields={'a': re.compile(r'(This|Another)'), 'b': 'is the', 'c': 'title'}), @@ -357,6 +357,10 @@ def test_querystring(db): query = Query.from_string(f'title:\'This title: is a title\'', record_type='bib') assert len(list(BibSet.from_query(query.compile()))) == 1 + # logical field widldcard + query = Query.from_string(f"title:*is*", record_type='bib') + assert len(list(BibSet.from_query(query.compile()))) == 3 + # NOT for bib in BibSet.from_query({}): # delete all bibs for further tests
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==23.2.0 boto3==1.34.100 botocore==1.34.100 certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 click==8.1.7 cryptography==42.0.7 -e git+https://github.com/dag-hammarskjold-library/dlx.git@733e9cadb70ac2b520809bb0381c5bdd01718087#egg=dlx dnspython==2.6.1 exceptiongroup==1.2.1 idna==3.7 iniconfig==2.0.0 Jinja2==3.1.4 jmespath==1.0.1 joblib==1.4.2 jsonschema==4.0.0 lxml==5.2.1 MarkupSafe==2.1.5 mongomock==4.1.2 moto==5.0.6 nltk==3.8.1 packaging==24.0 pluggy==1.5.0 pycparser==2.22 pymongo==4.6.3 pyrsistent==0.20.0 pytest==8.2.0 python-dateutil==2.9.0.post0 pytz==2024.1 PyYAML==6.0.1 regex==2024.4.28 requests==2.32.0 responses==0.25.0 s3transfer==0.10.1 sentinels==1.0.0 six==1.16.0 tomli==2.0.1 tqdm==4.66.4 urllib3==1.26.18 Werkzeug==3.0.3 xlrd==1.2.0 xmldiff==2.4 xmltodict==0.13.0
name: dlx channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==23.2.0 - boto3==1.34.100 - botocore==1.34.100 - certifi==2024.2.2 - cffi==1.16.0 - charset-normalizer==3.3.2 - click==8.1.7 - cryptography==42.0.7 - dnspython==2.6.1 - exceptiongroup==1.2.1 - idna==3.7 - iniconfig==2.0.0 - jinja2==3.1.4 - jmespath==1.0.1 - joblib==1.4.2 - jsonschema==4.0.0 - lxml==5.2.1 - markupsafe==2.1.5 - mongomock==4.1.2 - moto==5.0.6 - nltk==3.8.1 - packaging==24.0 - pluggy==1.5.0 - pycparser==2.22 - pymongo==4.6.3 - pyrsistent==0.20.0 - pytest==8.2.0 - python-dateutil==2.9.0.post0 - pytz==2024.1 - pyyaml==6.0.1 - regex==2024.4.28 - requests==2.32.0 - responses==0.25.0 - s3transfer==0.10.1 - sentinels==1.0.0 - six==1.16.0 - tomli==2.0.1 - tqdm==4.66.4 - urllib3==1.26.18 - werkzeug==3.0.3 - xlrd==1.2.0 - xmldiff==2.4 - xmltodict==0.13.0 prefix: /opt/conda/envs/dlx
[ "tests/test_marc.py::test_querydocument", "tests/test_marc.py::test_querystring" ]
[]
[ "tests/test_marc.py::test_init_marc", "tests/test_marc.py::test_init_bib", "tests/test_marc.py::test_init_auth", "tests/test_marc.py::test_init_auth_check", "tests/test_marc.py::test_commit", "tests/test_marc.py::test_delete", "tests/test_marc.py::test_from_id", "tests/test_marc.py::test_from_query", "tests/test_marc.py::test_from_aggregation", "tests/test_marc.py::test_atlasquery", "tests/test_marc.py::test_get_field", "tests/test_marc.py::test_field_get_value", "tests/test_marc.py::test_set_field", "tests/test_marc.py::test_get_value", "tests/test_marc.py::test_get_xref", "tests/test_marc.py::test_set", "tests/test_marc.py::test_zmerge", "tests/test_marc.py::test_xmerge", "tests/test_marc.py::test_set_008", "tests/test_marc.py::test_delete_field", "tests/test_marc.py::test_auth_lookup", "tests/test_marc.py::test_xlookup", "tests/test_marc.py::test_auth_control", "tests/test_marc.py::test_language", "tests/test_marc.py::test_to_xml", "tests/test_marc.py::test_xml_encoding", "tests/test_marc.py::test_to_mrc", "tests/test_marc.py::test_to_mrk", "tests/test_marc.py::test_from_mrk", "tests/test_marc.py::test_from_json", "tests/test_marc.py::test_to_jmarcnx", "tests/test_marc.py::test_field_from_json", "tests/test_marc.py::test_partial_lookup", "tests/test_marc.py::test_diff", "tests/test_marc.py::test_blank_fields", "tests/test_marc.py::test_auth_in_use", "tests/test_marc.py::test_catch_delete_auth", "tests/test_marc.py::test_from_xml", "tests/test_marc.py::test_auth_use_count", "tests/test_marc.py::test_auth_merge", "tests/test_marc.py::test_logical_fields", "tests/test_marc.py::test_bib_files", "tests/test_marc.py::test_list_attached" ]
[]
null
18,509
750
[ "dlx/config.py", "dlx/marc/query.py" ]
Informasjonsforvaltning__fdk-rdf-parser-308
e2ff215db4d333aa5a7b2f6068aebc94261c9a16
2024-05-27 07:25:24
0a72edaddfd8858b4fe4830a24875fc1cc1be7fb
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/308?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 100.00%. Comparing base [(`e2ff215`)](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/commit/e2ff215db4d333aa5a7b2f6068aebc94261c9a16?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning) to head [(`6e9e747`)](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/commit/6e9e74705e42c5638c87043a618bc4cfc201bbfe?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning). <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #308 +/- ## ========================================= Coverage 100.00% 100.00% ========================================= Files 89 89 Lines 2372 2377 +5 Branches 265 267 +2 ========================================= + Hits 2372 2377 +5 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/Informasjonsforvaltning/fdk-rdf-parser/pull/308?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Informasjonsforvaltning). github-actions[bot]: ``` Warning: poetry-plugin-export will not be installed by default in a future version of Poetry. In order to avoid a breaking change and make your automation forward-compatible, please install poetry-plugin-export explicitly. See https://python-poetry.org/docs/plugins/#using-plugins for details on how to install a plugin. To disable this warning run 'poetry config warnings.export false'. The `--dev` option is deprecated, use the `--with dev` notation instead. +==============================================================================+ /$$$$$$ /$$ /$$__ $$ | $$ /$$$$$$$ /$$$$$$ | $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$_____/ |____ $$| $$$$ /$$__ $$|_ $$_/ | $$ | $$ | $$$$$$ /$$$$$$$| $$_/ | $$$$$$$$ | $$ | $$ | $$ \____ $$ /$$__ $$| $$ | $$_____/ | $$ /$$| $$ | $$ /$$$$$$$/| $$$$$$$| $$ | $$$$$$$ | $$$$/| $$$$$$$ |_______/ \_______/|__/ \_______/ \___/ \____ $$ /$$ | $$ | $$$$$$/ by safetycli.com \______/ +==============================================================================+ REPORT Safety is using PyUp's free open-source vulnerability database. This data is 30 days old and limited. For real-time enhanced vulnerability data, fix recommendations, severity reporting, cybersecurity support, team and project policy management and more sign up at https://pyup.io or email [email protected] Safety v3.1.0 is scanning for Vulnerabilities... Scanning dependencies in your files: -> /tmp/tmpkcn2it00 Using open-source vulnerability database Found and scanned 72 packages Timestamp 2024-05-27 07:26:07 0 vulnerabilities reported 0 vulnerabilities ignored +==============================================================================+ No known security vulnerabilities found. +==============================================================================+ Safety is using PyUp's free open-source vulnerability database. This data is 30 days old and limited. For real-time enhanced vulnerability data, fix recommendations, severity reporting, cybersecurity support, team and project policy management and more sign up at https://pyup.io or email [email protected] +==============================================================================+ ``` <!-- Sticky Pull Request CommentSafety result -->
diff --git a/src/fdk_rdf_parser/parse_functions/concept.py b/src/fdk_rdf_parser/parse_functions/concept.py index cb07846..f7f0146 100644 --- a/src/fdk_rdf_parser/parse_functions/concept.py +++ b/src/fdk_rdf_parser/parse_functions/concept.py @@ -18,10 +18,7 @@ from rdflib.namespace import ( SKOS, ) -from fdk_rdf_parser.classes import ( - Concept, - Temporal, -) +from fdk_rdf_parser.classes import Concept from fdk_rdf_parser.classes.concept import ( AssociativeRelation, Collection, @@ -50,7 +47,7 @@ from fdk_rdf_parser.rdf_utils import ( from .contactpoint import extract_contact_points from .harvest_meta_data import extract_meta_data from .publisher import extract_publisher -from .temporal import extract_temporal +from .temporal import extract_temporal_skos def parse_text_and_uri(graph: Graph, subject: URIRef) -> TextAndURI: @@ -315,6 +312,22 @@ def extract_partitive_relations( def parse_generic_relation( graph: Graph, generic_relation_ref: URIRef +) -> GenericRelation: + return GenericRelation( + divisioncriterion=value_translations( + graph, generic_relation_ref, DCTERMS.description + ), + generalizes=object_value( + graph, generic_relation_ref, skosno_uri("hasSpecificConcept") + ), + specializes=object_value( + graph, generic_relation_ref, skosno_uri("hasGenericConcept") + ), + ) + + +def parse_generic_relation_deprecated( + graph: Graph, generic_relation_ref: URIRef ) -> GenericRelation: return GenericRelation( divisioncriterion=value_translations( @@ -333,13 +346,35 @@ def extract_generic_relations( graph: Graph, concept_uri: URIRef ) -> Optional[List[GenericRelation]]: generic_relations = [] - for generic_relation_ref in graph.objects( - concept_uri, skosno_uri("generiskRelasjon") + + if has_value_on_predicate( + graph, concept_uri, skosno_uri("hasGenericConceptRelation") ): - generic_relations.append(parse_generic_relation(graph, generic_relation_ref)) + for generic_relation_ref in graph.objects( + concept_uri, skosno_uri("hasGenericConceptRelation") + ): + generic_relations.append( + parse_generic_relation(graph, generic_relation_ref) + ) + else: + for generic_relation_ref in graph.objects( + concept_uri, skosno_uri("generiskRelasjon") + ): + generic_relations.append( + parse_generic_relation_deprecated(graph, generic_relation_ref) + ) return generic_relations if len(generic_relations) > 0 else None +def extract_collection_label( + graph: Graph, collection_uri: URIRef +) -> Optional[Dict[str, str]]: + if has_literal_value_on_predicate(graph, collection_uri, DCTERMS.title): + return value_translations(graph, collection_uri, DCTERMS.title) + else: + return value_translations(graph, collection_uri, RDFS.label) + + def parse_collection(graph: Graph, concept_record_uri: URIRef) -> Optional[Collection]: collection_record_uri = graph.value(concept_record_uri, DCTERMS.isPartOf) @@ -352,7 +387,7 @@ def parse_collection(graph: Graph, concept_record_uri: URIRef) -> Optional[Colle return Collection( id=object_value(graph, collection_record_uri, DCTERMS.identifier), publisher=extract_publisher(graph, collection_uri), - label=value_translations(graph, collection_uri, RDFS.label), + label=extract_collection_label(graph, collection_uri), uri=collection_uri.toPython(), description=value_translations( graph, collection_uri, DCTERMS.description @@ -384,8 +419,8 @@ def extract_labels( def _parse_concept( graph: Graph, fdk_record_uri: URIRef, concept_uri: URIRef ) -> Concept: - concept_temporal_list = extract_temporal(graph, concept_uri) - concept_temporal = concept_temporal_list[0] if concept_temporal_list else Temporal() + + concept_temporal = extract_temporal_skos(graph, concept_uri) contact_points = extract_contact_points(graph, concept_uri) pref_label_list = extract_labels( diff --git a/src/fdk_rdf_parser/parse_functions/temporal.py b/src/fdk_rdf_parser/parse_functions/temporal.py index 42e9280..c5c3dca 100644 --- a/src/fdk_rdf_parser/parse_functions/temporal.py +++ b/src/fdk_rdf_parser/parse_functions/temporal.py @@ -14,6 +14,7 @@ from fdk_rdf_parser.classes import Temporal from fdk_rdf_parser.rdf_utils import ( date_value, dcat_uri, + euvoc_uri, owl_time_uri, resource_list, schema_uri, @@ -59,6 +60,24 @@ def extract_temporal(graph: Graph, subject: URIRef) -> Optional[List[Temporal]]: return values if len(values) > 0 else None +def extract_temporal_skos(graph: Graph, subject: URIRef) -> Temporal: + temporal = Temporal() + + start_value = date_value(graph, subject, euvoc_uri("startDate")) + end_value = date_value(graph, subject, euvoc_uri("endDate")) + + deprecated_resource = graph.value(subject, DCTERMS.temporal) + if start_value or end_value: + temporal = Temporal(startDate=start_value, endDate=end_value) + elif deprecated_resource is not None: + start_value = date_value(graph, deprecated_resource, schema_uri("startDate")) + end_value = date_value(graph, deprecated_resource, schema_uri("endDate")) + + temporal = Temporal(startDate=start_value, endDate=end_value) + + return temporal + + def extract_owl_time_instant(graph: Graph, subject: Any) -> Optional[str]: owl_date = date_value(graph, subject, owl_time_uri("inXSDDateTime")) owl_date = (
ny generisk relasjon fra skos-ap-no v2.0.3 https://data.norge.no/specification/skos-ap-no-begrep#Begrep-har-generisk-begrepsrelasjon https://data.norge.no/specification/skos-ap-no-begrep#Generisk-begrepsrelasjon - predikat for angivelse av assosiativ relasjon endres fra `skosno:generiskRelasjon` til `skosno:hasGenericConceptRelation` - type endres fra `skosno:GeneriskRelasjon` til `skosno:GenericConceptRelation` (har ikke effekt i parse-kode) - predikat for underordnet begrep endres fra `xkos:generalizes` til `skosno:hasSpecificConcept` - predikat for overordnet begrep endres fra `xkos:specializes` til `skosno:hasGenericConcept` - predikat for inndelingskritrium endres fra `skosno:inndelingskriterium` til `dct:description` ```` <biffbestikk> a skos:Concept ; skosno:hasGenericConceptRelation [ a skosno:GenericConceptRelation ; skosno:hasGenericConcept <bestikk> ; dct:description "bruksformål"@nb ; ] . <bestikk> a skos:Concept ; skosno:hasGenericConceptRelation [ a skosno:GenericConceptRelation ; skosno:hasSpecificConcept <biffbestikk> ; ] . ```` er ekvivalent med dette fra gammel skos-ap-no: ```` <biffbestikk> a skos:Concept ; skosno:generiskRelasjon [ a skosno:GeneriskRelasjon ; xkos:specializes <bestikk> ; skosno:inndelingskriterium "bruksformål"@nb ; ] . <bestikk> a skos:Concept ; skosno:generiskRelasjon [ a skosno:GeneriskRelasjon ; xkos:generalizes <biffbestikk> ; ] . ````
Informasjonsforvaltning/fdk-rdf-parser
diff --git a/tests/test_concept.py b/tests/test_concept.py index 0d0466a..3016faf 100644 --- a/tests/test_concept.py +++ b/tests/test_concept.py @@ -47,10 +47,11 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: @prefix xkos: <http://rdf-vocabulary.ddialliance.org/xkos#> . @prefix euvoc: <http://publications.europa.eu/ontology/euvoc#> . @prefix uneskos: <http://purl.org/umu/uneskos#> . +@prefix schema: <http://schema.org/> . <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028> a skos:Collection ; - rdfs:label "Concept collection belonging to 910258028" ; + dct:title "Concept collection belonging to 910258028" ; dct:identifier "https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028" ; dct:publisher <https://data.brreg.no/enhetsregisteret/api/enheter/910258028> ; skos:member <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/c4ae179e-6a3a-42bc-85a2-1e32d75fc013> , <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/3609b02d-72c5-47e0-a6b8-df0a503cf190> , <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/1843b048-f9af-4665-8e53-3c001d0166c0> , <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/9f25b5ad-8aa7-4233-853b-7434e20aeaef> , <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/523ff894-638b-44a2-a4fd-3e96a5a8a5a3> . @@ -65,6 +66,10 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: <https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/1843b048-f9af-4665-8e53-3c001d0166c0> a skos:Concept ; + dct:temporal [ a dct:PeriodOfTime ; + schema:startDate "2020-05-29"^^xsd:date; + schema:endDate "2021-05-29"^^xsd:date; + ] ; dct:created "2023-02-17"^^xsd:date ; dct:identifier "1843b048-f9af-4665-8e53-3c001d0166c0" ; dct:modified "2019-12-16"^^xsd:date ; @@ -122,6 +127,16 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: skosno:assosiativRelasjon [ rdf:type skosno:AssosiativRelasjon ; dct:description "Beskrivelse"@nb ; skos:related <http://begrepskatalogen/begrep/virksomhet> ] ; + skosno:hasGenericConceptRelation [ + rdf:type skosno:GenericConceptRelation ; + dct:description "Inndelingskriterium"@nb ; + skosno:hasSpecificConcept <http://begrepskatalogen/begrep/biffbestikk> + ] ; + skosno:hasGenericConceptRelation [ + rdf:type skosno:GenericConceptRelation ; + dct:description "Inndelingskriterium"@nb ; + skosno:hasGenericConcept <http://begrepskatalogen/begrep/bestikk> + ] ; euvoc:status "status nb" , "status en"@en ; skosxl:altLabel [ a skosxl:Label ; skosxl:literalForm "stabilisator"@nb @@ -301,11 +316,6 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ], ), definitions=[ - Definition( - text={"nb": "def-2"}, - targetGroup="https://data.norge.no/vocabulary/audience-type#public", - sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", - ), Definition( text={"nb": "def-1"}, sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", @@ -315,6 +325,11 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ) ], ), + Definition( + text={"nb": "def-2"}, + targetGroup="https://data.norge.no/vocabulary/audience-type#public", + sourceRelationship="https://data.norge.no/vocabulary/relationship-with-source-type#self-composed", + ), ], associativeRelation=[ AssociativeRelation( @@ -343,6 +358,8 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: ), ], type="concept", + validFromIncluding="2020-05-29", + validToIncluding="2021-05-29", ), "https://registrering-begrep-api.staging.fellesdatakatalog.digdir.no/910258028/3609b02d-72c5-47e0-a6b8-df0a503cf190": Concept( id="fc8baf8d-6146-3b69-93c5-52bd41592c4e", @@ -370,6 +387,16 @@ def test_parse_concepts(mock_reference_data_client: Mock) -> None: related="http://begrepskatalogen/begrep/virksomhet", ), ], + genericRelation=[ + GenericRelation( + divisioncriterion={"nb": "Inndelingskriterium"}, + generalizes="http://begrepskatalogen/begrep/biffbestikk", + ), + GenericRelation( + divisioncriterion={"nb": "Inndelingskriterium"}, + specializes="http://begrepskatalogen/begrep/bestikk", + ), + ], altLabel=[{"nb": "stabilisator"}], definition=Definition(text={"nb": "ugyldig-audience-og-forholdtilkilde"}), definitions=[ @@ -634,7 +661,9 @@ def test_parse_concept(mock_reference_data_client: Mock) -> None: skosno:valueRange "test-nn"@nn, "test", - <https://range.com> . + <https://range.com> ; + euvoc:startDate "2020-05-29"^^xsd:date; + euvoc:endDate "2021-05-29"^^xsd:date . <http://publications.europa.eu/resource/authority/concept-status/CURRENT> @@ -706,6 +735,8 @@ def test_parse_concept(mock_reference_data_client: Mock) -> None: ) ], type="concept", + validFromIncluding="2020-05-29", + validToIncluding="2021-05-29", ) result = parse_concept(src)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 2 }
2.7
{ "env_vars": null, "env_yml_path": null, "install": "poetry install", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "poetry", "pip_packages": [ "pytest", "pytest-cov", "pytest-mock" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.6.0 argcomplete==3.3.0 attrs==23.2.0 Authlib==1.3.0 bandit==1.7.8 black==24.4.2 Brotli @ file:///croot/brotli-split_1736182456865/work build @ file:///croot/python-build_1679596508056/work CacheControl @ file:///croot/cachecontrol-split_1676365553644/work certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 cleo @ file:///croot/cleo_1705431334181/work click==8.1.7 codecov==2.1.13 colorlog==6.8.2 coverage==7.5.0 crashtest @ file:///croot/crashtest_1679422372509/work cryptography==42.0.5 distlib==0.3.8 dparse==0.6.4b0 dulwich @ file:///croot/dulwich_1679420040193/work exceptiongroup==1.2.1 -e git+https://github.com/Informasjonsforvaltning/fdk-rdf-parser.git@e2ff215db4d333aa5a7b2f6068aebc94261c9a16#egg=fdk_rdf_parser filelock==3.13.4 flake8==7.0.0 flake8-annotations==3.0.1 flake8-bandit==4.1.1 flake8-black==0.3.6 flake8-bugbear==24.4.26 flake8-import-order==0.18.2 html5lib @ file:///Users/ktietz/demo/mc3/conda-bld/html5lib_1629144453894/work idna==3.7 importlib_metadata @ file:///croot/importlib_metadata-suite_1732633488278/work iniconfig==2.0.0 installer @ file:///croot/python-installer_1679432998036/work isodate==0.6.1 jaraco.classes @ file:///tmp/build/80754af9/jaraco.classes_1620983179379/work jeepney @ file:///tmp/build/80754af9/jeepney_1627537048313/work Jinja2==3.1.3 jsonschema @ file:///croot/jsonschema_1728486696720/work jsonschema-specifications @ file:///croot/jsonschema-specifications_1699032386549/work keyring @ file:///croot/keyring_1678999217139/work lockfile==0.12.2 markdown-it-py==3.0.0 MarkupSafe==2.1.5 marshmallow==3.21.1 mccabe==0.7.0 mdurl==0.1.2 more-itertools @ file:///croot/more-itertools_1727185441804/work msgpack @ file:///opt/conda/conda-bld/msgpack-python_1652362659880/work mypy==1.10.0 mypy-extensions==1.0.0 nox==2024.4.15 nox-poetry==1.0.3 numpy @ file:///croot/numpy_and_numpy_base_1725470312869/work/dist/numpy-2.0.1-cp39-cp39-linux_x86_64.whl#sha256=b8c18bbfe185fbdff23024458e4b8ffbe2040e705abd5fb6cda1ef9d20b5974d packaging==24.0 pathspec==0.12.1 pbr==6.0.0 pep8-naming==0.13.3 pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pkginfo @ file:///croot/pkginfo_1743184746806/work platformdirs==4.2.1 pluggy==1.5.0 poetry @ file:///croot/poetry_1680193142998/work poetry-core @ file:///croot/poetry-core_1680018645313/work poetry-plugin-export @ file:///croot/poetry-plugin-export_1680122784541/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl pycodestyle==2.11.1 pycparser==2.22 pydantic==2.7.1 pydantic_core==2.18.2 pyflakes==3.2.0 Pygments==2.17.2 pyOpenSSL @ file:///croot/pyopenssl_1741343803032/work pyparsing==3.1.2 pyproject_hooks @ file:///croot/pyproject_hooks_1679584411881/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305812635/work pytest==8.2.0 pytest-cov==5.0.0 pytest-mock==3.14.0 PyYAML==6.0.1 RapidFuzz @ file:///croot/rapidfuzz_1738592335633/work rdflib==7.0.0 referencing @ file:///croot/referencing_1699012038513/work requests==2.31.0 requests-toolbelt @ file:///Users/ktietz/demo/mc3/conda-bld/requests-toolbelt_1629456163440/work rich==13.7.1 rpds-py @ file:///croot/rpds-py_1736541261634/work ruamel.yaml==0.18.6 ruamel.yaml.clib==0.2.8 safety==3.1.0 safety-schemas==0.0.2 SecretStorage @ file:///croot/secretstorage_1678709481048/work shellingham==1.5.4 six==1.16.0 stevedore==5.2.0 tomli==2.0.1 tomlkit==0.12.4 trove-classifiers @ file:///croot/trove-classifiers_1729277230900/work typer==0.12.3 typing_extensions==4.11.0 urllib3==2.2.1 virtualenv==20.26.0 webencodings==0.5.1 zipp @ file:///croot/zipp_1732630741423/work
name: fdk-rdf-parser channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - blas=1.0=openblas - brotli-python=1.0.9=py39h6a678d5_9 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - cachecontrol=0.12.11=py39h06a4308_1 - charset-normalizer=3.3.2=pyhd3eb1b0_0 - cleo=2.1.0=py39h06a4308_0 - crashtest=0.4.1=py39h06a4308_0 - dbus=1.13.18=hb2f20db_0 - distlib=0.3.8=py39h06a4308_0 - dulwich=0.21.3=py39h5eee18b_0 - expat=2.6.4=h6a678d5_0 - glib=2.78.4=h6a678d5_0 - glib-tools=2.78.4=h6a678d5_0 - html5lib=1.1=pyhd3eb1b0_0 - idna=3.7=py39h06a4308_0 - importlib-metadata=8.5.0=py39h06a4308_0 - importlib_metadata=8.5.0=hd3eb1b0_0 - jaraco.classes=3.2.1=pyhd3eb1b0_0 - jeepney=0.7.1=pyhd3eb1b0_0 - jsonschema=4.23.0=py39h06a4308_0 - jsonschema-specifications=2023.7.1=py39h06a4308_0 - keyring=23.13.1=py39h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=11.2.0=h00389a5_1 - libgfortran5=11.2.0=h1234567_1 - libglib=2.78.4=hdc74915_0 - libgomp=11.2.0=h1234567_1 - libiconv=1.16=h5eee18b_3 - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - lockfile=0.12.2=py39h06a4308_0 - more-itertools=10.3.0=py39h06a4308_0 - msgpack-python=1.0.3=py39hd09550d_0 - ncurses=6.4=h6a678d5_0 - numpy=2.0.1=py39heeff2f4_1 - numpy-base=2.0.1=py39h8a23956_1 - openssl=3.0.16=h5eee18b_0 - pcre2=10.42=hebb0a14_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pip=25.0=py39h06a4308_0 - pkginfo=1.12.0=py39h06a4308_0 - poetry=1.4.0=py39h06a4308_0 - poetry-core=1.5.1=py39h06a4308_0 - poetry-plugin-export=1.3.0=py39h4849bfd_0 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pyopenssl=25.0.0=py39h06a4308_0 - pyproject_hooks=1.0.0=py39h06a4308_0 - pysocks=1.7.1=py39h06a4308_0 - python=3.9.21=he870216_1 - python-build=0.10.0=py39h06a4308_0 - python-installer=0.6.0=py39h06a4308_0 - rapidfuzz=3.12.1=py39h6a678d5_0 - readline=8.2=h5eee18b_0 - referencing=0.30.2=py39h06a4308_0 - requests-toolbelt=0.9.1=pyhd3eb1b0_0 - rpds-py=0.22.3=py39h4aa5aa6_0 - secretstorage=3.3.1=py39h06a4308_1 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - trove-classifiers=2024.10.14=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - webencodings=0.5.1=py39h06a4308_1 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.21.0=py39h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.6.0 - argcomplete==3.3.0 - attrs==23.2.0 - authlib==1.3.0 - bandit==1.7.8 - black==24.4.2 - certifi==2024.2.2 - cffi==1.16.0 - click==8.1.7 - codecov==2.1.13 - colorlog==6.8.2 - coverage==7.5.0 - cryptography==42.0.5 - dparse==0.6.4b0 - exceptiongroup==1.2.1 - fdk-rdf-parser==2.7.2 - filelock==3.13.4 - flake8==7.0.0 - flake8-annotations==3.0.1 - flake8-bandit==4.1.1 - flake8-black==0.3.6 - flake8-bugbear==24.4.26 - flake8-import-order==0.18.2 - iniconfig==2.0.0 - isodate==0.6.1 - jinja2==3.1.3 - markdown-it-py==3.0.0 - markupsafe==2.1.5 - marshmallow==3.21.1 - mccabe==0.7.0 - mdurl==0.1.2 - mypy==1.10.0 - mypy-extensions==1.0.0 - nox==2024.4.15 - nox-poetry==1.0.3 - packaging==24.0 - pathspec==0.12.1 - pbr==6.0.0 - pep8-naming==0.13.3 - platformdirs==4.2.1 - pluggy==1.5.0 - pycodestyle==2.11.1 - pycparser==2.22 - pydantic==2.7.1 - pydantic-core==2.18.2 - pyflakes==3.2.0 - pygments==2.17.2 - pyparsing==3.1.2 - pytest==8.2.0 - pytest-cov==5.0.0 - pytest-mock==3.14.0 - pyyaml==6.0.1 - rdflib==7.0.0 - requests==2.31.0 - rich==13.7.1 - ruamel-yaml==0.18.6 - ruamel-yaml-clib==0.2.8 - safety==3.1.0 - safety-schemas==0.0.2 - setuptools==69.5.1 - shellingham==1.5.4 - stevedore==5.2.0 - tomlkit==0.12.4 - typer==0.12.3 - typing-extensions==4.11.0 - urllib3==2.2.1 - virtualenv==20.26.0 prefix: /opt/conda/envs/fdk-rdf-parser
[ "tests/test_concept.py::test_parse_concepts", "tests/test_concept.py::test_parse_concept" ]
[]
[ "tests/test_concept.py::test_parse_concept_handles_wrong_collection_type" ]
[]
Apache License 2.0
18,520
1,424
[ "src/fdk_rdf_parser/parse_functions/concept.py", "src/fdk_rdf_parser/parse_functions/temporal.py" ]
pyvista__pyvista-6127
9d162b26c26b7708d80ef505f403b7dc10e070c6
2024-05-27 21:36:54
b5d7a8114b128b5890c0e116fcf985d800fca950
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/pyvista/pyvista/pull/6127?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pyvista) Report Attention: Patch coverage is `50.00000%` with `1 lines` in your changes are missing coverage. Please review. > Project coverage is 90.58%. Comparing base [(`4d4d896`)](https://app.codecov.io/gh/pyvista/pyvista/commit/4d4d89645a8af8367b0833675bf98219d59169ec?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pyvista) to head [(`0c4a6e4`)](https://app.codecov.io/gh/pyvista/pyvista/commit/0c4a6e45cecaa95303d635c59a253267ee391e57?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pyvista). <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #6127 +/- ## ========================================== - Coverage 96.99% 90.58% -6.42% ========================================== Files 141 141 Lines 24667 24669 +2 ========================================== - Hits 23926 22346 -1580 - Misses 741 2323 +1582 ``` </details> tkoyama010: @pyvista-bot preview pyvista-bot: <!-- NETLIFY DEPLOY COMMENT GENERATED BY ACTIONS_NETLIFY - APP ID SHA256: a13cb84fb117b1fbb38c5e9d3853a95b804288edd848742e6f4a409c37f2648c --> 🚀 Deployed on https://6655b96f3247fcfea2200a3c--meek-duckanoo-d2f5ec.netlify.app
diff --git a/pyvista/core/pointset.py b/pyvista/core/pointset.py index 994a42cf..a3375c5c 100644 --- a/pyvista/core/pointset.py +++ b/pyvista/core/pointset.py @@ -347,6 +347,33 @@ class PointSet(_vtk.vtkPointSet, _PointSet): pdata.point_data[key] = value return pdata + def cast_to_unstructured_grid(self) -> pyvista.UnstructuredGrid: + """Cast this dataset to :class:`pyvista.UnstructuredGrid`. + + A deep copy of the points and point data is made. + + Returns + ------- + pyvista.UnstructuredGrid + Dataset cast to a :class:`pyvista.UnstructuredGrid`. + + Examples + -------- + Cast a :class:`pyvista.PointSet` to a + :class:`pyvista.UnstructuredGrid`. + + >>> import pyvista as pv + >>> from pyvista import examples + >>> mesh = examples.download_cloud_dark_matter() + >>> type(mesh) + <class 'pyvista.core.pointset.PointSet'> + >>> grid = mesh.cast_to_unstructured_grid() + >>> type(grid) + <class 'pyvista.core.pointset.UnstructuredGrid'> + + """ + return self.cast_to_polydata(deep=False).cast_to_unstructured_grid() + @wraps(DataSet.plot) def plot(self, *args, **kwargs): """Cast to PolyData and plot."""
`cast_to_unstructured_grid` not working for `PointSet` ### Describe the bug, what's wrong, and what you expected. See code below. The output type is the same as the input type. The output type is expected to be an unstructured grid. ### Steps to reproduce the bug. ``` python import pyvista as pv from pyvista import examples mesh = examples.download_cloud_dark_matter() print(type(mesh)) # <class 'pyvista.core.pointset.PointSet'> grid = mesh.cast_to_unstructured_grid() print(type(grid)) # <class 'pyvista.core.pointset.PointSet'> ``` ### System Information ```shell pyvista : 0.44.dev0 vtk : 9.3.0 numpy : 1.26.4 matplotlib : 3.8.2 scooby : 0.9.2 pooch : 1.8.0 pillow : 10.2.0 imageio : 2.34.0 IPython : 8.21.0 colorcet : 3.1.0 cmocean : 3.1.3 ipywidgets : 8.1.2 scipy : 1.12.0 tqdm : 4.66.2 meshio : 5.3.5 jupyterlab : 4.1.4 pytest_pyvista : 0.1.8 trame : 3.5.3 trame_client : 2.16.1 trame_server : 2.17.2 trame_vtk : 2.8.5 trame_vuetify : 2.4.3 nest_asyncio : 1.6.0 ``` ### Screenshots _No response_
pyvista/pyvista
diff --git a/tests/core/test_pointset.py b/tests/core/test_pointset.py index 4402d7aa..373318d0 100644 --- a/tests/core/test_pointset.py +++ b/tests/core/test_pointset.py @@ -111,6 +111,19 @@ def test_cast_to_polydata(pointset, deep): assert np.allclose(pdata.point_data[key], pointset.point_data[key]) +def test_cast_to_unstructured_grid(pointset): + data = np.linspace(0, 1, pointset.n_points) + key = 'key' + pointset.point_data[key] = data + + pdata = pointset.cast_to_unstructured_grid() + assert isinstance(pdata, pv.UnstructuredGrid) + assert key in pdata.point_data + assert np.allclose(pdata.point_data[key], pointset.point_data[key]) + pdata.point_data[key][:] = 0 + assert not np.allclose(pdata.point_data[key], pointset.point_data[key]) + + def test_filters_return_pointset(sphere): pointset = sphere.cast_to_pointset() clipped = pointset.clip()
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.43
{ "env_vars": null, "env_yml_path": [ "environment.yml" ], "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "environment.yml", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiohappyeyeballs @ file:///home/conda/feedstock_root/build_artifacts/aiohappyeyeballs_1741775197943/work aiohttp @ file:///home/conda/feedstock_root/build_artifacts/aiohttp_1742268596946/work aiosignal @ file:///home/conda/feedstock_root/build_artifacts/aiosignal_1734342155601/work anyio @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_anyio_1742243108/work argon2-cffi @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi_1733311059102/work argon2-cffi-bindings @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi-bindings_1725356560642/work arrow @ file:///home/conda/feedstock_root/build_artifacts/arrow_1733584251875/work asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1733250440834/work async-lru @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_async-lru_1742153708/work async-timeout @ file:///home/conda/feedstock_root/build_artifacts/async-timeout_1733235340728/work attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1741918516150/work babel @ file:///home/conda/feedstock_root/build_artifacts/babel_1738490167835/work beautifulsoup4 @ file:///home/conda/feedstock_root/build_artifacts/beautifulsoup4_1738740337718/work bleach @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_bleach_1737382993/work Brotli @ file:///home/conda/feedstock_root/build_artifacts/brotli-split_1725267488082/work cached-property @ file:///home/conda/feedstock_root/build_artifacts/cached_property_1615209429212/work certifi @ file:///home/conda/feedstock_root/build_artifacts/certifi_1739515848642/work/certifi cffi @ file:///home/conda/feedstock_root/build_artifacts/cffi_1725571112467/work cftime @ file:///home/conda/feedstock_root/build_artifacts/cftime_1725400455427/work charset-normalizer @ file:///home/conda/feedstock_root/build_artifacts/charset-normalizer_1735929714516/work click @ file:///home/conda/feedstock_root/build_artifacts/click_1734858813237/work cmocean @ file:///home/conda/feedstock_root/build_artifacts/cmocean_1734343940570/work codecov @ file:///home/conda/feedstock_root/build_artifacts/codecov_1734975286850/work colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1733218098505/work colorcet @ file:///home/conda/feedstock_root/build_artifacts/colorcet_1734007314889/work colorspacious @ file:///home/conda/feedstock_root/build_artifacts/colorspacious_1734341944815/work comm @ file:///home/conda/feedstock_root/build_artifacts/comm_1733502965406/work contourpy @ file:///home/conda/feedstock_root/build_artifacts/contourpy_1727293517607/work coverage @ file:///home/conda/feedstock_root/build_artifacts/coverage_1743381224823/work cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1733332471406/work debugpy @ file:///home/conda/feedstock_root/build_artifacts/debugpy_1741148409996/work decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1740384970518/work defusedxml @ file:///home/conda/feedstock_root/build_artifacts/defusedxml_1615232257335/work exceptiongroup @ file:///home/conda/feedstock_root/build_artifacts/exceptiongroup_1733208806608/work execnet @ file:///home/conda/feedstock_root/build_artifacts/execnet_1733230988954/work executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1733569351617/work fastjsonschema @ file:///home/conda/feedstock_root/build_artifacts/python-fastjsonschema_1733235979760/work/dist fonttools @ file:///home/conda/feedstock_root/build_artifacts/fonttools_1738940303262/work fqdn @ file:///home/conda/feedstock_root/build_artifacts/fqdn_1733327382592/work/dist frozenlist @ file:///home/conda/feedstock_root/build_artifacts/frozenlist_1737645236190/work h11 @ file:///home/conda/feedstock_root/build_artifacts/h11_1733327467879/work h2 @ file:///home/conda/feedstock_root/build_artifacts/h2_1738578511449/work h5py @ file:///home/conda/feedstock_root/build_artifacts/h5py_1739952287730/work hpack @ file:///home/conda/feedstock_root/build_artifacts/hpack_1737618293087/work httpcore @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_httpcore_1731707562/work httpx @ file:///home/conda/feedstock_root/build_artifacts/httpx_1733663348460/work hyperframe @ file:///home/conda/feedstock_root/build_artifacts/hyperframe_1737618333194/work hypothesis @ file:///home/conda/feedstock_root/build_artifacts/hypothesis_1742900877539/work idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1733211830134/work imageio @ file:///home/conda/feedstock_root/build_artifacts/imageio_1738273805233/work imageio-ffmpeg @ file:///home/conda/feedstock_root/build_artifacts/imageio-ffmpeg_1737102630951/work importlib_metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1737420181517/work importlib_resources @ file:///home/conda/feedstock_root/build_artifacts/importlib_resources_1736252299705/work iniconfig @ file:///home/conda/feedstock_root/build_artifacts/iniconfig_1733223141826/work ipykernel @ file:///home/conda/feedstock_root/build_artifacts/ipykernel_1719845459717/work ipython @ file:///home/conda/feedstock_root/build_artifacts/ipython_1701831663892/work isoduration @ file:///home/conda/feedstock_root/build_artifacts/isoduration_1733493628631/work/dist jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1733300866624/work Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1741263328855/work json5 @ file:///home/conda/feedstock_root/build_artifacts/json5_1733272076743/work jsonpointer @ file:///home/conda/feedstock_root/build_artifacts/jsonpointer_1725302957584/work jsonschema @ file:///home/conda/feedstock_root/build_artifacts/jsonschema_1733472696581/work jsonschema-specifications @ file:///tmp/tmpk0f344m9/src jupyter-events @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_jupyter_events_1738765986/work jupyter-lsp @ file:///home/conda/feedstock_root/build_artifacts/jupyter-lsp-meta_1733492907176/work/jupyter-lsp jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1733440914442/work jupyter_core @ file:///home/conda/feedstock_root/build_artifacts/jupyter_core_1727163409502/work jupyter_server @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_1734702637701/work jupyter_server_terminals @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_terminals_1733427956852/work jupyterlab @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_1741964057182/work jupyterlab_pygments @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_pygments_1733328101776/work jupyterlab_server @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_server_1733599573484/work kiwisolver @ file:///home/conda/feedstock_root/build_artifacts/kiwisolver_1725459266648/work loguru @ file:///home/conda/feedstock_root/build_artifacts/loguru_1725349754278/work markdown-it-py @ file:///home/conda/feedstock_root/build_artifacts/markdown-it-py_1733250460757/work MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1733219680183/work matplotlib==3.9.4 matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1733416936468/work mdurl @ file:///home/conda/feedstock_root/build_artifacts/mdurl_1733255585584/work meshio @ file:///home/conda/feedstock_root/build_artifacts/meshio_1706720595231/work mistune @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_mistune_1742402716/work more-itertools @ file:///home/conda/feedstock_root/build_artifacts/more-itertools_1736883817510/work msgpack @ file:///home/conda/feedstock_root/build_artifacts/msgpack-python_1725975012026/work multidict @ file:///home/conda/feedstock_root/build_artifacts/multidict_1742308123521/work munkres==1.1.4 nbclient @ file:///home/conda/feedstock_root/build_artifacts/nbclient_1734628800805/work nbconvert @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_nbconvert-core_1738067871/work nbformat @ file:///home/conda/feedstock_root/build_artifacts/nbformat_1733402752141/work nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1733325553580/work netCDF4 @ file:///home/conda/feedstock_root/build_artifacts/netcdf4_1733253338730/work notebook_shim @ file:///home/conda/feedstock_root/build_artifacts/notebook-shim_1733408315203/work numpy @ file:///home/conda/feedstock_root/build_artifacts/numpy_1707225342954/work/dist/numpy-1.26.4-cp39-cp39-linux_x86_64.whl#sha256=c799942b5898f6e6c60264d1663a6469a475290e758c654aeeb78e2596463abd overrides @ file:///home/conda/feedstock_root/build_artifacts/overrides_1734587627321/work packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1733203243479/work pandocfilters @ file:///home/conda/feedstock_root/build_artifacts/pandocfilters_1631603243851/work parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1733271261340/work pexpect @ file:///home/conda/feedstock_root/build_artifacts/pexpect_1733301927746/work pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1733327343728/work pillow @ file:///home/conda/feedstock_root/build_artifacts/pillow_1735929703139/work pkgutil_resolve_name @ file:///home/conda/feedstock_root/build_artifacts/pkgutil-resolve-name_1733344503739/work platformdirs @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_platformdirs_1742485085/work pluggy @ file:///home/conda/feedstock_root/build_artifacts/pluggy_1733222765875/work pooch @ file:///home/conda/feedstock_root/build_artifacts/pooch_1733421311631/work prometheus_client @ file:///home/conda/feedstock_root/build_artifacts/prometheus_client_1733327310477/work prompt_toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1737453357274/work propcache @ file:///home/conda/feedstock_root/build_artifacts/propcache_1737635528546/work psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1740663125313/work ptyprocess @ file:///home/conda/feedstock_root/build_artifacts/ptyprocess_1733302279685/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl#sha256=92c32ff62b5fd8cf325bec5ab90d7be3d2a8ca8c8a3813ff487a8d2002630d1f pure_eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1733569405015/work pycparser @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_pycparser_1733195786/work pyembree @ file:///home/conda/feedstock_root/build_artifacts/pyembree_1718702851992/work Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1736243443484/work pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1743089729650/work PySide6==6.8.3 PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1733217236728/work pytest @ file:///home/conda/feedstock_root/build_artifacts/pytest_1740946542080/work pytest-asyncio==0.26.0 pytest-cov @ file:///home/conda/feedstock_root/build_artifacts/pytest-cov_1733223023082/work pytest-memprof==0.2.0 pytest-mock==3.14.0 pytest-xdist @ file:///home/conda/feedstock_root/build_artifacts/pytest-xdist_1733240780199/work python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1733215673016/work python-json-logger @ file:///home/conda/feedstock_root/build_artifacts/python-json-logger_1677079630776/work pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1742920838005/work -e git+https://github.com/pyvista/pyvista.git@9d162b26c26b7708d80ef505f403b7dc10e070c6#egg=pyvista PyYAML @ file:///home/conda/feedstock_root/build_artifacts/pyyaml_1737454647378/work pyzmq @ file:///home/conda/feedstock_root/build_artifacts/pyzmq_1741805177758/work referencing @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_referencing_1737836872/work requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1733217035951/work rfc3339_validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3339-validator_1733599910982/work rfc3986-validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3986-validator_1598024191506/work rich @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rich_1743371105/work/dist rpds-py @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rpds-py_1743037693/work rtree @ file:///home/conda/feedstock_root/build_artifacts/rtree_1741378561624/work scooby @ file:///home/conda/feedstock_root/build_artifacts/scooby_1734299019922/work Send2Trash @ file:///home/conda/feedstock_root/build_artifacts/send2trash_1733322040660/work shiboken6==6.8.3 six @ file:///home/conda/feedstock_root/build_artifacts/six_1733380938961/work sniffio @ file:///home/conda/feedstock_root/build_artifacts/sniffio_1733244044561/work sortedcontainers @ file:///home/conda/feedstock_root/build_artifacts/sortedcontainers_1738440353519/work soupsieve @ file:///home/conda/feedstock_root/build_artifacts/soupsieve_1693929250441/work stack_data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1733569443808/work terminado @ file:///home/conda/feedstock_root/build_artifacts/terminado_1710262609923/work tinycss2 @ file:///home/conda/feedstock_root/build_artifacts/tinycss2_1729802851396/work toml @ file:///home/conda/feedstock_root/build_artifacts/toml_1734091811753/work tomli @ file:///home/conda/feedstock_root/build_artifacts/tomli_1733256695513/work tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1732615921868/work tqdm @ file:///home/conda/feedstock_root/build_artifacts/tqdm_1735661334605/work traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1733367359838/work trame @ file:///home/conda/feedstock_root/build_artifacts/trame_1741413642518/work trame-client @ file:///home/conda/feedstock_root/build_artifacts/trame-client_1742874331306/work trame-server @ file:///home/conda/feedstock_root/build_artifacts/trame-server_1741638011360/work trame-vtk @ file:///home/conda/feedstock_root/build_artifacts/trame-vtk_1739145199105/work trame-vuetify @ file:///home/conda/feedstock_root/build_artifacts/trame-vuetify_1743263303319/work trimesh @ file:///home/conda/feedstock_root/build_artifacts/trimesh_1743289679380/work types-python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/types-python-dateutil_1733612335562/work typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_typing_extensions_1743201626/work typing_utils @ file:///home/conda/feedstock_root/build_artifacts/typing_utils_1733331286120/work unicodedata2 @ file:///home/conda/feedstock_root/build_artifacts/unicodedata2_1736692503055/work uri-template @ file:///home/conda/feedstock_root/build_artifacts/uri-template_1733323593477/work/dist urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1734859416348/work vtk==9.3.1 wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1733231326287/work webcolors @ file:///home/conda/feedstock_root/build_artifacts/webcolors_1733359735138/work webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1733236011802/work websocket-client @ file:///home/conda/feedstock_root/build_artifacts/websocket-client_1733157342724/work wslink @ file:///home/conda/feedstock_root/build_artifacts/wslink_1742768409749/work yarl @ file:///home/conda/feedstock_root/build_artifacts/yarl_1737575777699/work zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1732827521216/work zstandard==0.23.0
name: pyvista channels: - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=conda_forge - _openmp_mutex=4.5=2_gnu - aiohappyeyeballs=2.6.1=pyhd8ed1ab_0 - aiohttp=3.11.14=py39h9399b63_0 - aiosignal=1.3.2=pyhd8ed1ab_0 - alsa-lib=1.2.13=hb9d3cd8_0 - anyio=4.9.0=pyh29332c3_0 - aom=3.9.1=hac33072_0 - argon2-cffi=23.1.0=pyhd8ed1ab_1 - argon2-cffi-bindings=21.2.0=py39h8cd3c5a_5 - arrow=1.3.0=pyhd8ed1ab_1 - asttokens=3.0.0=pyhd8ed1ab_1 - async-lru=2.0.5=pyh29332c3_0 - async-timeout=5.0.1=pyhd8ed1ab_1 - attr=2.5.1=h166bdaf_1 - attrs=25.3.0=pyh71513ae_0 - babel=2.17.0=pyhd8ed1ab_0 - beautifulsoup4=4.13.3=pyha770c72_0 - bleach=6.2.0=pyh29332c3_4 - bleach-with-css=6.2.0=h82add2a_4 - blosc=1.21.6=he440d0b_1 - brotli=1.1.0=hb9d3cd8_2 - brotli-bin=1.1.0=hb9d3cd8_2 - brotli-python=1.1.0=py39hf88036b_2 - bzip2=1.0.8=h4bc722e_7 - c-ares=1.34.4=hb9d3cd8_0 - ca-certificates=2025.1.31=hbcca054_0 - cached-property=1.5.2=hd8ed1ab_1 - cached_property=1.5.2=pyha770c72_1 - cairo=1.18.4=h3394656_0 - certifi=2025.1.31=pyhd8ed1ab_0 - cffi=1.17.1=py39h15c3d72_0 - cftime=1.6.4=py39hf3d9206_1 - charset-normalizer=3.4.1=pyhd8ed1ab_0 - click=8.1.8=pyh707e725_0 - cmocean=4.0.3=pyhd8ed1ab_1 - codecov=2.1.13=pyhd8ed1ab_1 - colorama=0.4.6=pyhd8ed1ab_1 - colorcet=3.1.0=pyhd8ed1ab_1 - colorspacious=1.1.2=pyhecae5ae_1 - comm=0.2.2=pyhd8ed1ab_1 - contourpy=1.3.0=py39h74842e3_2 - coverage=7.8.0=py39h9399b63_0 - cycler=0.12.1=pyhd8ed1ab_1 - cyrus-sasl=2.1.27=h54b06d7_7 - dav1d=1.2.1=hd590300_0 - dbus=1.13.6=h5008d03_3 - debugpy=1.8.13=py39hf88036b_0 - decorator=5.2.1=pyhd8ed1ab_0 - defusedxml=0.7.1=pyhd8ed1ab_0 - double-conversion=3.3.1=h5888daf_0 - embree=2.17.7=ha770c72_3 - exceptiongroup=1.2.2=pyhd8ed1ab_1 - execnet=2.1.1=pyhd8ed1ab_1 - executing=2.1.0=pyhd8ed1ab_1 - expat=2.6.4=h5888daf_0 - ffmpeg=7.1.1=gpl_h0b79d52_704 - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 - font-ttf-inconsolata=3.000=h77eed37_0 - font-ttf-source-code-pro=2.038=h77eed37_0 - font-ttf-ubuntu=0.83=h77eed37_3 - fontconfig=2.15.0=h7e30c49_1 - fonts-conda-ecosystem=1=0 - fonts-conda-forge=1=0 - fonttools=4.56.0=py39h9399b63_0 - fqdn=1.5.1=pyhd8ed1ab_1 - freetype=2.13.3=h48d6fc4_0 - fribidi=1.0.10=h36c2ea0_0 - frozenlist=1.5.0=py39h9399b63_1 - gdk-pixbuf=2.42.12=hb9ae30d_0 - gettext=0.23.1=h5888daf_0 - gettext-tools=0.23.1=h5888daf_0 - gl2ps=1.4.2=hae5d5c5_1 - glew=2.1.0=h9c3ff4c_2 - gmp=6.3.0=hac33072_2 - graphite2=1.3.13=h59595ed_1003 - h11=0.14.0=pyhd8ed1ab_1 - h2=4.2.0=pyhd8ed1ab_0 - h5py=3.13.0=nompi_py39h30a5a8d_100 - harfbuzz=11.0.0=h76408a6_0 - hdf4=4.2.15=h2a13503_7 - hdf5=1.14.3=nompi_h2d575fe_109 - hpack=4.1.0=pyhd8ed1ab_0 - httpcore=1.0.7=pyh29332c3_1 - httpx=0.28.1=pyhd8ed1ab_0 - hyperframe=6.1.0=pyhd8ed1ab_0 - hypothesis=6.130.4=pyha770c72_0 - icu=75.1=he02047a_0 - idna=3.10=pyhd8ed1ab_1 - imageio=2.37.0=pyhfb79c49_0 - imageio-ffmpeg=0.6.0=pyhd8ed1ab_0 - importlib-metadata=8.6.1=pyha770c72_0 - importlib-resources=6.5.2=pyhd8ed1ab_0 - importlib_metadata=8.6.1=hd8ed1ab_0 - importlib_resources=6.5.2=pyhd8ed1ab_0 - iniconfig=2.0.0=pyhd8ed1ab_1 - ipykernel=6.29.5=pyh3099207_0 - ipython=8.18.1=pyh707e725_3 - isoduration=20.11.0=pyhd8ed1ab_1 - jack=1.9.22=h7c63dc7_2 - jedi=0.19.2=pyhd8ed1ab_1 - jinja2=3.1.6=pyhd8ed1ab_0 - json5=0.10.0=pyhd8ed1ab_1 - jsoncpp=1.9.6=hf42df4d_1 - jsonpointer=3.0.0=py39hf3d152e_1 - jsonschema=4.23.0=pyhd8ed1ab_1 - jsonschema-specifications=2024.10.1=pyhd8ed1ab_1 - jsonschema-with-format-nongpl=4.23.0=hd8ed1ab_1 - jupyter-lsp=2.2.5=pyhd8ed1ab_1 - jupyter_client=8.6.3=pyhd8ed1ab_1 - jupyter_core=5.7.2=pyh31011fe_1 - jupyter_events=0.12.0=pyh29332c3_0 - jupyter_server=2.15.0=pyhd8ed1ab_0 - jupyter_server_terminals=0.5.3=pyhd8ed1ab_1 - jupyterlab=4.3.6=pyhd8ed1ab_0 - jupyterlab_pygments=0.3.0=pyhd8ed1ab_2 - jupyterlab_server=2.27.3=pyhd8ed1ab_1 - keyutils=1.6.1=h166bdaf_0 - kiwisolver=1.4.7=py39h74842e3_0 - krb5=1.21.3=h659f571_0 - lame=3.100=h166bdaf_1003 - lcms2=2.17=h717163a_0 - ld_impl_linux-64=2.43=h712a8e2_4 - lerc=4.0.0=h27087fc_0 - level-zero=1.21.6=h84d6215_0 - libabseil=20250127.1=cxx17_hbbce691_0 - libaec=1.1.3=h59595ed_0 - libasprintf=0.23.1=h8e693c7_0 - libasprintf-devel=0.23.1=h8e693c7_0 - libass=0.17.3=h52826cd_2 - libblas=3.9.0=31_h59b9bed_openblas - libbrotlicommon=1.1.0=hb9d3cd8_2 - libbrotlidec=1.1.0=hb9d3cd8_2 - libbrotlienc=1.1.0=hb9d3cd8_2 - libcap=2.75=h39aace5_0 - libcblas=3.9.0=31_he106b2a_openblas - libclang-cpp20.1=20.1.1=default_hb5137d0_0 - libclang13=20.1.1=default_h9c6a7e4_0 - libcups=2.3.3=h4637d8d_4 - libcurl=8.12.1=h332b0f4_0 - libdb=6.2.32=h9c3ff4c_0 - libdeflate=1.23=h4ddbbb0_0 - libdrm=2.4.124=hb9d3cd8_0 - libedit=3.1.20250104=pl5321h7949ede_0 - libegl=1.7.0=ha4b6fd6_2 - libev=4.33=hd590300_2 - libexpat=2.6.4=h5888daf_0 - libffi=3.4.6=h2dba641_0 - libflac=1.4.3=h59595ed_0 - libgcc=14.2.0=h767d61c_2 - libgcc-ng=14.2.0=h69a702a_2 - libgcrypt-lib=1.11.0=hb9d3cd8_2 - libgettextpo=0.23.1=h5888daf_0 - libgettextpo-devel=0.23.1=h5888daf_0 - libgfortran=14.2.0=h69a702a_2 - libgfortran5=14.2.0=hf1ad2bd_2 - libgl=1.7.0=ha4b6fd6_2 - libglib=2.84.0=h2ff4ddf_0 - libglu=9.0.3=h03adeef_0 - libglvnd=1.7.0=ha4b6fd6_2 - libglx=1.7.0=ha4b6fd6_2 - libgomp=14.2.0=h767d61c_2 - libgpg-error=1.51=hbd13f7d_1 - libhwloc=2.11.2=default_h0d58e46_1001 - libiconv=1.18=h4ce23a2_1 - libjpeg-turbo=3.0.0=hd590300_1 - liblapack=3.9.0=31_h7ac8fdf_openblas - libllvm20=20.1.1=ha7bfdaf_0 - liblzma=5.6.4=hb9d3cd8_0 - libnetcdf=4.9.2=nompi_h00e09a9_116 - libnghttp2=1.64.0=h161d5f1_0 - libnsl=2.0.1=hd590300_0 - libntlm=1.8=hb9d3cd8_0 - libogg=1.3.5=h4ab18f5_0 - libopenblas=0.3.29=pthreads_h94d23a6_0 - libopengl=1.7.0=ha4b6fd6_2 - libopenvino=2025.0.0=hdc3f47d_3 - libopenvino-auto-batch-plugin=2025.0.0=h4d9b6c2_3 - libopenvino-auto-plugin=2025.0.0=h4d9b6c2_3 - libopenvino-hetero-plugin=2025.0.0=h981d57b_3 - libopenvino-intel-cpu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-intel-gpu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-intel-npu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-ir-frontend=2025.0.0=h981d57b_3 - libopenvino-onnx-frontend=2025.0.0=h0e684df_3 - libopenvino-paddle-frontend=2025.0.0=h0e684df_3 - libopenvino-pytorch-frontend=2025.0.0=h5888daf_3 - libopenvino-tensorflow-frontend=2025.0.0=h684f15b_3 - libopenvino-tensorflow-lite-frontend=2025.0.0=h5888daf_3 - libopus=1.3.1=h7f98852_1 - libpciaccess=0.18=hd590300_0 - libpng=1.6.47=h943b412_0 - libpq=17.4=h27ae623_0 - libprotobuf=5.29.3=h501fc15_0 - librsvg=2.58.4=he92a37e_3 - libsndfile=1.2.2=hc60ed4a_1 - libsodium=1.0.20=h4ab18f5_0 - libspatialindex=2.1.0=he57a185_0 - libsqlite=3.49.1=hee588c1_2 - libssh2=1.11.1=hf672d98_0 - libstdcxx=14.2.0=h8f9b012_2 - libstdcxx-ng=14.2.0=h4852527_2 - libsystemd0=257.4=h4e0b6ca_1 - libtheora=1.1.1=h4ab18f5_1006 - libtiff=4.7.0=hd9ff511_3 - libudev1=257.4=hbe16f8c_1 - libunwind=1.6.2=h9c3ff4c_0 - liburing=2.9=h84d6215_0 - libusb=1.0.28=hb9d3cd8_0 - libuuid=2.38.1=h0b41bf4_0 - libva=2.22.0=h4f16b4b_2 - libvorbis=1.3.7=h9c3ff4c_0 - libvpx=1.14.1=hac33072_0 - libwebp-base=1.5.0=h851e524_0 - libxcb=1.17.0=h8a09558_0 - libxcrypt=4.4.36=hd590300_1 - libxkbcommon=1.8.1=hc4a0caf_0 - libxml2=2.13.7=h8d12d68_0 - libxslt=1.1.39=h76b75d6_0 - libzip=1.11.2=h6991a6a_0 - libzlib=1.3.1=hb9d3cd8_2 - loguru=0.7.2=py39hf3d152e_2 - lz4-c=1.10.0=h5888daf_1 - markdown-it-py=3.0.0=pyhd8ed1ab_1 - markupsafe=3.0.2=py39h9399b63_1 - matplotlib=3.9.4=py39hf3d152e_0 - matplotlib-base=3.9.4=py39h16632d1_0 - matplotlib-inline=0.1.7=pyhd8ed1ab_1 - mdurl=0.1.2=pyhd8ed1ab_1 - meshio=5.3.5=pyhd8ed1ab_0 - mistune=3.1.3=pyh29332c3_0 - more-itertools=10.6.0=pyhd8ed1ab_0 - mpg123=1.32.9=hc50e24c_0 - msgpack-python=1.1.0=py39h74842e3_0 - multidict=6.2.0=py39h9399b63_0 - munkres=1.1.4=pyh9f0ad1d_0 - mysql-common=9.0.1=h266115a_5 - mysql-libs=9.0.1=he0572af_5 - nbclient=0.10.2=pyhd8ed1ab_0 - nbconvert-core=7.16.6=pyh29332c3_0 - nbformat=5.10.4=pyhd8ed1ab_1 - ncurses=6.5=h2d0b736_3 - nest-asyncio=1.6.0=pyhd8ed1ab_1 - netcdf4=1.7.2=nompi_py39h9d02bfe_101 - nlohmann_json=3.11.3=he02047a_1 - notebook-shim=0.2.4=pyhd8ed1ab_1 - numpy=1.26.4=py39h474f0d3_0 - ocl-icd=2.3.2=hb9d3cd8_2 - opencl-headers=2024.10.24=h5888daf_0 - openh264=2.6.0=hc22cd8d_0 - openjpeg=2.5.3=h5fbd93e_0 - openldap=2.6.9=he970967_0 - openssl=3.4.1=h7b32b05_0 - overrides=7.7.0=pyhd8ed1ab_1 - packaging=24.2=pyhd8ed1ab_2 - pandocfilters=1.5.0=pyhd8ed1ab_0 - pango=1.56.3=h9ac818e_1 - parso=0.8.4=pyhd8ed1ab_1 - pcre2=10.44=hba22ea6_2 - pexpect=4.9.0=pyhd8ed1ab_1 - pickleshare=0.7.5=pyhd8ed1ab_1004 - pillow=11.1.0=py39h15c0740_0 - pip=25.0.1=pyh8b19718_0 - pixman=0.44.2=h29eaf8c_0 - pkgutil-resolve-name=1.3.10=pyhd8ed1ab_2 - platformdirs=4.3.7=pyh29332c3_0 - pluggy=1.5.0=pyhd8ed1ab_1 - pooch=1.8.2=pyhd8ed1ab_1 - proj=9.5.1=h0054346_0 - prometheus_client=0.21.1=pyhd8ed1ab_0 - prompt-toolkit=3.0.50=pyha770c72_0 - propcache=0.2.1=py39h9399b63_1 - psutil=7.0.0=py39h8cd3c5a_0 - pthread-stubs=0.4=hb9d3cd8_1002 - ptyprocess=0.7.0=pyhd8ed1ab_1 - pugixml=1.15=h3f63f65_0 - pulseaudio-client=17.0=hac146a9_1 - pure_eval=0.2.3=pyhd8ed1ab_1 - pycparser=2.22=pyh29332c3_1 - pyembree=0.1.6=py39hddac248_4 - pygments=2.19.1=pyhd8ed1ab_0 - pyparsing=3.2.3=pyhd8ed1ab_1 - pyside6=6.8.3=py39h0383914_0 - pysocks=1.7.1=pyha55dd90_7 - pytest=8.3.5=pyhd8ed1ab_0 - pytest-cov=6.0.0=pyhd8ed1ab_1 - pytest-xdist=3.6.1=pyhd8ed1ab_1 - python=3.9.21=h9c0c6dc_1_cpython - python-dateutil=2.9.0.post0=pyhff2d567_1 - python-fastjsonschema=2.21.1=pyhd8ed1ab_0 - python-json-logger=2.0.7=pyhd8ed1ab_0 - python_abi=3.9=5_cp39 - pytz=2025.2=pyhd8ed1ab_0 - pyyaml=6.0.2=py39h9399b63_2 - pyzmq=26.3.0=py39h4e4fb57_0 - qhull=2020.2=h434a139_5 - qt6-main=6.8.3=h6441bc3_1 - readline=8.2=h8c095d6_2 - referencing=0.36.2=pyh29332c3_0 - requests=2.32.3=pyhd8ed1ab_1 - rfc3339-validator=0.1.4=pyhd8ed1ab_1 - rfc3986-validator=0.1.1=pyh9f0ad1d_0 - rich=14.0.0=pyh29332c3_0 - rpds-py=0.24.0=py39h3506688_0 - rtree=1.4.0=pyh11ca60a_1 - scooby=0.10.0=pyhd8ed1ab_1 - sdl2=2.32.50=h9b8e6db_1 - sdl3=3.2.8=h3083f51_0 - send2trash=1.8.3=pyh0d859eb_1 - setuptools=75.8.2=pyhff2d567_0 - six=1.17.0=pyhd8ed1ab_0 - snappy=1.2.1=h8bd8927_1 - sniffio=1.3.1=pyhd8ed1ab_1 - sortedcontainers=2.4.0=pyhd8ed1ab_1 - soupsieve=2.5=pyhd8ed1ab_1 - sqlite=3.49.1=h9eae976_2 - stack_data=0.6.3=pyhd8ed1ab_1 - svt-av1=3.0.2=h5888daf_0 - tbb=2022.0.0=hceb3a55_0 - terminado=0.18.1=pyh0d859eb_0 - tinycss2=1.4.0=pyhd8ed1ab_0 - tk=8.6.13=noxft_h4845f30_101 - toml=0.10.2=pyhd8ed1ab_1 - tomli=2.2.1=pyhd8ed1ab_1 - tornado=6.4.2=py39h8cd3c5a_0 - tqdm=4.67.1=pyhd8ed1ab_1 - traitlets=5.14.3=pyhd8ed1ab_1 - trame=3.8.1=pyhd8ed1ab_0 - trame-client=3.6.1=pyhd8ed1ab_0 - trame-server=3.4.0=pyhd8ed1ab_0 - trame-vtk=2.8.15=pyhb419c8b_0 - trame-vuetify=2.9.0=pyhd8ed1ab_0 - trimesh=4.6.6=pyh7b2049a_0 - types-python-dateutil=2.9.0.20241206=pyhd8ed1ab_0 - typing-extensions=4.13.0=h9fa5a19_1 - typing_extensions=4.13.0=pyh29332c3_1 - typing_utils=0.1.0=pyhd8ed1ab_1 - tzdata=2025b=h78e105d_0 - unicodedata2=16.0.0=py39h8cd3c5a_0 - uri-template=1.3.0=pyhd8ed1ab_1 - urllib3=2.3.0=pyhd8ed1ab_0 - utfcpp=4.0.6=h005c6e1_0 - vtk=9.3.1=qt_py39h71fb23e_216 - vtk-base=9.3.1=qt_py39habd23de_216 - vtk-io-ffmpeg=9.3.1=qt_py39h71fb23e_216 - wayland=1.23.1=h3e06ad9_0 - wayland-protocols=1.42=hd8ed1ab_0 - wcwidth=0.2.13=pyhd8ed1ab_1 - webcolors=24.11.1=pyhd8ed1ab_0 - webencodings=0.5.1=pyhd8ed1ab_3 - websocket-client=1.8.0=pyhd8ed1ab_1 - wheel=0.45.1=pyhd8ed1ab_1 - wslink=2.3.3=pyhd8ed1ab_0 - x264=1!164.3095=h166bdaf_2 - x265=3.5=h924138e_3 - xcb-util=0.4.1=hb711507_2 - xcb-util-cursor=0.1.5=hb9d3cd8_0 - xcb-util-image=0.4.0=hb711507_2 - xcb-util-keysyms=0.4.1=hb711507_0 - xcb-util-renderutil=0.3.10=hb711507_0 - xcb-util-wm=0.4.2=hb711507_0 - xkeyboard-config=2.43=hb9d3cd8_0 - xorg-libice=1.1.2=hb9d3cd8_0 - xorg-libsm=1.2.6=he73a12e_0 - xorg-libx11=1.8.12=h4f16b4b_0 - xorg-libxau=1.0.12=hb9d3cd8_0 - xorg-libxcomposite=0.4.6=hb9d3cd8_2 - xorg-libxcursor=1.2.3=hb9d3cd8_0 - xorg-libxdamage=1.1.6=hb9d3cd8_0 - xorg-libxdmcp=1.1.5=hb9d3cd8_0 - xorg-libxext=1.3.6=hb9d3cd8_0 - xorg-libxfixes=6.0.1=hb9d3cd8_0 - xorg-libxi=1.8.2=hb9d3cd8_0 - xorg-libxrandr=1.5.4=hb9d3cd8_0 - xorg-libxrender=0.9.12=hb9d3cd8_0 - xorg-libxscrnsaver=1.2.4=hb9d3cd8_0 - xorg-libxt=1.3.1=hb9d3cd8_0 - xorg-libxtst=1.2.5=hb9d3cd8_3 - xorg-libxxf86vm=1.1.6=hb9d3cd8_0 - yaml=0.2.5=h7f98852_2 - yarl=1.18.3=py39h9399b63_1 - zeromq=4.3.5=h3b0a872_7 - zipp=3.21.0=pyhd8ed1ab_1 - zlib=1.3.1=hb9d3cd8_2 - zstandard=0.23.0=py39h8cd3c5a_1 - zstd=1.5.7=hb8e6e7a_2 - pip: - pytest-asyncio==0.26.0 - pytest-memprof==0.2.0 - pytest-mock==3.14.0 - pyvista==0.44.dev0 prefix: /opt/conda/envs/pyvista
[ "tests/core/test_pointset.py::test_cast_to_unstructured_grid" ]
[]
[ "tests/core/test_pointset.py::test_pointset_basic", "tests/core/test_pointset.py::test_pointset_from_vtk", "tests/core/test_pointset.py::test_pointset_wrap", "tests/core/test_pointset.py::test_pointset", "tests/core/test_pointset.py::test_save", "tests/core/test_pointset.py::test_cast_to_polydata[True]", "tests/core/test_pointset.py::test_cast_to_polydata[False]", "tests/core/test_pointset.py::test_filters_return_pointset", "tests/core/test_pointset.py::test_pointset_force_float[False-int64]", "tests/core/test_pointset.py::test_pointset_force_float[True-float32]", "tests/core/test_pointset.py::test_center_of_mass", "tests/core/test_pointset.py::test_points_to_double", "tests/core/test_pointset.py::test_translate", "tests/core/test_pointset.py::test_scale", "tests/core/test_pointset.py::test_flip_x", "tests/core/test_pointset.py::test_flip_y", "tests/core/test_pointset.py::test_flip_z", "tests/core/test_pointset.py::test_flip_normal", "tests/core/test_pointset.py::test_threshold", "tests/core/test_pointset.py::test_threshold_percent", "tests/core/test_pointset.py::test_explode", "tests/core/test_pointset.py::test_delaunay_3d", "tests/core/test_pointset.py::test_raise_unsupported", "tests/core/test_pointset.py::test_rotate_x", "tests/core/test_pointset.py::test_rotate_y", "tests/core/test_pointset.py::test_rotate_z", "tests/core/test_pointset.py::test_rotate_vector" ]
[]
MIT License
18,530
368
[ "pyvista/core/pointset.py" ]
networkx__networkx-7465
1d719c69f7fe035a10f09321efb21d1025faa52b
2024-05-28 07:29:32
409979eff35f02eff54f4eea3731736bd431dc2e
carissableker: Hi @dschult As the bug reporter, I have the following comment: > If I understand the subtleties here, it looks like this will no longer strip anything from the beginning of a line and will only strip a newline character off of the end of the line. Yes, this is correct. In my opinion this is the simplest and most predictable behaviour. The aim of this line is to prepare the input by removing the *completely expected* newline and split the line into its components by using the *explicit* user-provided delimitator. Doing anything more than this, e.g. attempting to do undocumented whitespace "cleaning" would be obscured, unpredictable and/or become very complex. > So, it fixes the problem with a tab delimiter, but breaks an input file that has spaces at the front or end of a line. It looks like all tests pass. It would not break (crash), it would respect the user input (an attribute/node name with leading or trailing white space). > I guess to fix the currently broken cases and leave the current behavior for extra whitespace at start and end, we should strip all white space **except** the delimiter. Something like: > > ```python > stripchars = None if delimiter is None else string.whitespace.replace(delimiter, "") > .... > <other stuff and start loop, etc> > s = line.strip(stripchars).split(delimiter) > ``` This is not consistent though. The following lines, (for an equivalent undirected edge) would have a different result: ``` A\tB\s\n ``` and ``` B\s\tA\n ``` or alternatively: ``` \s\tB\n ``` and ``` B\t\sA\n ``` Of course, it may not be the users intent to have a node name of ` A` or `B `, but it is what was provided to networkx and I don't think it should be networkx's prerogative to attempt to deduce what the user means and unilaterally "fix" it, as there lies many dragons. Compare this behaviour to other software, e.g. Excel or pandas, removing leading/trailing whitespace is usually done on per cell basis (instead of line), and is only done on explicit user direction. The only place where editing of (non newline or delimiter) whitespace in the background may be relevant is perhaps in "fixed width" format. ## Alternatively If you do require that node names should not have leading or trailing whitespace, this should be removed per item after `split(deliminator)` (and then be documented). E.g.: ``` s = [x.strip() for x in s] ``` In this case, also the two examples above would be consistent. cyschneck: For purposes of an example if it splits on a tab then ``` import string stripchars = string.whitespace.replace('\t', '') ``` ### Current Behavior (some conditions retain white space) If there a space after the B value and the tab ``` line = 'A\tB \n' s = line.strip(stripchars).split('\t') ``` Produces a clean value before and after the values A and B ``` ['A', 'B'] ``` However, if the space is after the B value and before the tab ``` line = 'B \tA\n' s = line.strip(stripchars).split('\t') ``` Produces an output that still includes the space after B ``` ['B ', 'A'] ``` ### rstrip() Behavior (conditions retain white space) ``` line = 'A\tB \n' s = line.rstrip('\n').split('\t') ``` Produces B with a space trailing it ``` ['A', 'B '] ``` As well as the if the space precedes the tab ``` line = 'B \tA\n' s = line.rstrip('\n').split('\t') ``` Where, the B is first in the list, but still includes the space ``` ['B ', 'A'] ``` ### Proposed List Comprehension (no additional white space) This seems promising since it does fully remove all white space around each element in the list ``` line = 'B \tA\n' s =[x.strip() for x in line if x.strip() != ''] ``` No space around B or A ``` ['B', 'A'] ``` And ``` s = 'A\tB \n' s =[x.strip() for x in line if x.strip() != ''] ``` Also with no space around the B or A ``` ['A', 'B'] ``` dschult: Yes -- when I said "broken" I meant it breaks backward compatibility -- not crashing anything. Sorry for the confusion. I understand the rationale for either stripping whitespace from every entry or none of the entries. stripping the whitespace on the start of the first and end of the last without doing anything in between is not consistent across entries in a line. I tend to lean toward the simpler approach of not stripping whitespace at either end -- just remove the newline. And that is what is in this PR. But, I'm worried about backward compatibility: Do we need to deprecate the current behavior? And what idiom can we give those for whom the tools work with their current file to get it to work with the new code. It seems like trouble could only occur for folks with `node_type=None` and `delimiter` set to something. For example: `line = " b,a\n"` or `line="b,a \n"`. I guess we could deprecate with a warning to strip their lines like: ```python with open(path, "rb") as file: G = nx.parse_edgelist([line.strip() for line in file], delimiter=",") ``` Is there a better way? Or does someone feel this doesn't need a deprecation? Or ;P maybe we should just tell people to fix the current Issue by doing: ```python with open(path, "rb") as file: G = nx.parse_edgelist([line.replace("\t", "@#$") for line in file], delimiter="@#$") ```
diff --git a/networkx/algorithms/bipartite/edgelist.py b/networkx/algorithms/bipartite/edgelist.py index ebd47b032..db6ef9d8e 100644 --- a/networkx/algorithms/bipartite/edgelist.py +++ b/networkx/algorithms/bipartite/edgelist.py @@ -220,7 +220,7 @@ def parse_edgelist( if not len(line): continue # split line, should have 2 or more - s = line.strip().split(delimiter) + s = line.rstrip("\n").split(delimiter) if len(s) < 2: continue u = s.pop(0) diff --git a/networkx/readwrite/adjlist.py b/networkx/readwrite/adjlist.py index 56a1b4d2b..768af5ad7 100644 --- a/networkx/readwrite/adjlist.py +++ b/networkx/readwrite/adjlist.py @@ -201,7 +201,7 @@ def parse_adjlist( line = line[:p] if not len(line): continue - vlist = line.strip().split(delimiter) + vlist = line.rstrip("\n").split(delimiter) u = vlist.pop(0) # convert types if nodetype is not None: diff --git a/networkx/readwrite/edgelist.py b/networkx/readwrite/edgelist.py index ed445c80b..393b64ed7 100644 --- a/networkx/readwrite/edgelist.py +++ b/networkx/readwrite/edgelist.py @@ -247,7 +247,7 @@ def parse_edgelist( if not line: continue # split line, should have 2 or more - s = line.strip().split(delimiter) + s = line.rstrip("\n").split(delimiter) if len(s) < 2: continue u = s.pop(0) diff --git a/networkx/readwrite/multiline_adjlist.py b/networkx/readwrite/multiline_adjlist.py index 526b30a9b..808445dbf 100644 --- a/networkx/readwrite/multiline_adjlist.py +++ b/networkx/readwrite/multiline_adjlist.py @@ -246,7 +246,7 @@ def parse_multiline_adjlist( if not line: continue try: - (u, deg) = line.strip().split(delimiter) + (u, deg) = line.rstrip("\n").split(delimiter) deg = int(deg) except BaseException as err: raise TypeError(f"Failed to read node and degree on line ({line})") from err @@ -270,7 +270,7 @@ def parse_multiline_adjlist( line = line[:p] if line: break - vlist = line.strip().split(delimiter) + vlist = line.rstrip("\n").split(delimiter) numb = len(vlist) if numb < 1: continue # isolated node
edgelist reader removes deliminators if deliminator is white-space and file has empty fields [BUG] This `line.strip` without an argument, means a white-space delimited file (e.g. tab, which is quite common) with empty edge attribute(s) in the last column(s) results in a crash with error `Edge data [...] and data_keys [...] are not the same length`. https://github.com/networkx/networkx/blob/729bec23b10e89b5f6d37175e30484f2278107c4/networkx/algorithms/bipartite/edgelist.py#L222 An example file that would crash: ``` A B interaction 2 B C interaction 4 C A interaction ``` The last line ends in `\t\n`, and both are striped instead of just the `\n`. This is inconsistent, as the same data in a different order of columns works fine, e.g.: ``` A B 2 interaction B C 4 interaction C A interaction ``` # Fix s = line.rstrip("\n").split(delimiter) is the safe fix, and is cross OS compatible in Python (https://peps.python.org/pep-0278/)
networkx/networkx
diff --git a/networkx/algorithms/bipartite/tests/test_edgelist.py b/networkx/algorithms/bipartite/tests/test_edgelist.py index 86ffba072..66be8a2f5 100644 --- a/networkx/algorithms/bipartite/tests/test_edgelist.py +++ b/networkx/algorithms/bipartite/tests/test_edgelist.py @@ -216,3 +216,25 @@ class TestEdgelist: G = bipartite.parse_edgelist( lines, nodetype=int, data=[("weight", int), ("key", int)] ) + + +def test_bipartite_edgelist_consistent_strip_handling(): + """See gh-7462 + + Input when printed looks like: + + A B interaction 2 + B C interaction 4 + C A interaction + + Note the trailing \\t in the last line, which indicates the existence of + an empty data field. + """ + lines = io.StringIO( + "A\tB\tinteraction\t2\nB\tC\tinteraction\t4\nC\tA\tinteraction\t" + ) + descr = [("type", str), ("weight", str)] + # Should not raise + G = nx.bipartite.parse_edgelist(lines, delimiter="\t", data=descr) + expected = [("A", "B", "2"), ("A", "C", ""), ("B", "C", "4")] + assert sorted(G.edges(data="weight")) == expected diff --git a/networkx/readwrite/tests/test_adjlist.py b/networkx/readwrite/tests/test_adjlist.py index 6f52c234f..f2218eba1 100644 --- a/networkx/readwrite/tests/test_adjlist.py +++ b/networkx/readwrite/tests/test_adjlist.py @@ -239,3 +239,24 @@ class TestMultilineAdjlist: H = nx.read_multiline_adjlist(fh, nodetype=int, delimiter=":") assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges())) + + [email protected]( + ("lines", "delim"), + ( + (["1 2 5", "2 3 4", "3 5", "4", "5"], None), # No extra whitespace + (["1\t2\t5", "2\t3\t4", "3\t5", "4", "5"], "\t"), # tab-delimited + ( + ["1\t2\t5", "2\t3\t4", "3\t5\t", "4\t", "5"], + "\t", + ), # tab-delimited, extra delims + ( + ["1\t2\t5", "2\t3\t4", "3\t5\t\t\n", "4\t", "5"], + "\t", + ), # extra delim+newlines + ), +) +def test_adjlist_rstrip_parsing(lines, delim): + """Regression test related to gh-7465""" + expected = nx.Graph([(1, 2), (1, 5), (2, 3), (2, 4), (3, 5)]) + nx.utils.graphs_equal(nx.parse_adjlist(lines, delimiter=delim), expected) diff --git a/networkx/readwrite/tests/test_edgelist.py b/networkx/readwrite/tests/test_edgelist.py index 9751885aa..fe58b3b7d 100644 --- a/networkx/readwrite/tests/test_edgelist.py +++ b/networkx/readwrite/tests/test_edgelist.py @@ -295,3 +295,20 @@ class TestEdgelist: assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges())) + + +def test_edgelist_consistent_strip_handling(): + """See gh-7462 + + Input when printed looks like:: + + 1 2 3 + 2 3 + 3 4 3.0 + + Note the trailing \\t after the `3` in the second row, indicating an empty + data value. + """ + s = io.StringIO("1\t2\t3\n2\t3\t\n3\t4\t3.0") + G = nx.parse_edgelist(s, delimiter="\t", nodetype=int, data=[("value", str)]) + assert sorted(G.edges(data="value")) == [(1, 2, "3"), (2, 3, ""), (3, 4, "3.0")]
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 4 }
3.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[default]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.11", "reqs_path": [ "requirements/default.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
contourpy==1.3.1 coverage==7.8.0 cycler==0.12.1 fonttools==4.56.0 iniconfig==2.1.0 kiwisolver==1.4.8 matplotlib==3.10.1 -e git+https://github.com/networkx/networkx.git@1d719c69f7fe035a10f09321efb21d1025faa52b#egg=networkx numpy==2.2.4 packaging==24.2 pandas==2.2.3 pillow==11.1.0 pluggy==1.5.0 pyparsing==3.2.3 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 scipy==1.15.2 six==1.17.0 tzdata==2025.2
name: networkx channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py311h06a4308_0 - python=3.11.11=he870216_0 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py311h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py311h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - contourpy==1.3.1 - coverage==7.8.0 - cycler==0.12.1 - fonttools==4.56.0 - iniconfig==2.1.0 - kiwisolver==1.4.8 - matplotlib==3.10.1 - networkx==3.4rc0.dev0 - numpy==2.2.4 - packaging==24.2 - pandas==2.2.3 - pillow==11.1.0 - pluggy==1.5.0 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - scipy==1.15.2 - six==1.17.0 - tzdata==2025.2 prefix: /opt/conda/envs/networkx
[ "networkx/algorithms/bipartite/tests/test_edgelist.py::test_bipartite_edgelist_consistent_strip_handling", "networkx/readwrite/tests/test_edgelist.py::test_edgelist_consistent_strip_handling" ]
[]
[ "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_read_edgelist_1", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_read_edgelist_3", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_1", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_2", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_3", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_4", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_unicode", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_latin1_issue", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_latin1", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_edgelist_graph", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_edgelist_integers", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_edgelist_multigraph", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_empty_digraph", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_raise_attribute", "networkx/algorithms/bipartite/tests/test_edgelist.py::TestEdgelist::test_parse_edgelist", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_read_multiline_adjlist_1", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_unicode", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_latin1_err", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_latin1", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_parse_adjlist", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_adjlist_graph", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_adjlist_digraph", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_adjlist_integers", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_adjlist_multigraph", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_adjlist_multidigraph", "networkx/readwrite/tests/test_adjlist.py::TestAdjlist::test_adjlist_delimiter", "networkx/readwrite/tests/test_adjlist.py::TestMultilineAdjlist::test_parse_multiline_adjlist", "networkx/readwrite/tests/test_adjlist.py::TestMultilineAdjlist::test_multiline_adjlist_graph", "networkx/readwrite/tests/test_adjlist.py::TestMultilineAdjlist::test_multiline_adjlist_digraph", "networkx/readwrite/tests/test_adjlist.py::TestMultilineAdjlist::test_multiline_adjlist_integers", "networkx/readwrite/tests/test_adjlist.py::TestMultilineAdjlist::test_multiline_adjlist_multigraph", "networkx/readwrite/tests/test_adjlist.py::TestMultilineAdjlist::test_multiline_adjlist_multidigraph", "networkx/readwrite/tests/test_adjlist.py::TestMultilineAdjlist::test_multiline_adjlist_delimiter", "networkx/readwrite/tests/test_adjlist.py::test_adjlist_rstrip_parsing[lines0-None]", "networkx/readwrite/tests/test_adjlist.py::test_adjlist_rstrip_parsing[lines1-\\t]", "networkx/readwrite/tests/test_adjlist.py::test_adjlist_rstrip_parsing[lines2-\\t]", "networkx/readwrite/tests/test_adjlist.py::test_adjlist_rstrip_parsing[lines3-\\t]", "networkx/readwrite/tests/test_edgelist.py::test_read_edgelist_no_data[\\n#", "networkx/readwrite/tests/test_edgelist.py::test_read_weighted_edgelist", "networkx/readwrite/tests/test_edgelist.py::test_read_edgelist_with_data[\\n#", "networkx/readwrite/tests/test_edgelist.py::test_parse_edgelist_no_data", "networkx/readwrite/tests/test_edgelist.py::test_parse_edgelist_with_data_dict", "networkx/readwrite/tests/test_edgelist.py::test_parse_edgelist_with_data_list", "networkx/readwrite/tests/test_edgelist.py::test_parse_edgelist", "networkx/readwrite/tests/test_edgelist.py::test_comments_None", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_1", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_2", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_3", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_write_edgelist_4", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_unicode", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_latin1_issue", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_latin1", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_graph", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_digraph", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_integers", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_multigraph", "networkx/readwrite/tests/test_edgelist.py::TestEdgelist::test_edgelist_multidigraph" ]
[]
BSD 3-Clause
18,533
745
[ "networkx/algorithms/bipartite/edgelist.py", "networkx/readwrite/adjlist.py", "networkx/readwrite/edgelist.py", "networkx/readwrite/multiline_adjlist.py" ]
biolink__biolink-model-toolkit-172
e421af4ebb7e33ce43a7d9de2e5a6ab4b9e94e5c
2024-05-28 23:01:49
e421af4ebb7e33ce43a7d9de2e5a6ab4b9e94e5c
diff --git a/bmt/toolkit.py b/bmt/toolkit.py index fed2f44..b61da7a 100644 --- a/bmt/toolkit.py +++ b/bmt/toolkit.py @@ -441,12 +441,26 @@ class Toolkit(object): A list of elements """ - association_elements = self.get_descendants("association") filtered_elements: List[str] = list() inverse_predicates: Optional[List[str]] = None + subject_categories_formatted = [] + object_categories_formatted = [] + predicates_formatted = [] + association_elements = self.get_descendants("association") + if subject_categories: + for sc in subject_categories: + sc_formatted = format_element(self.get_element(sc)) + subject_categories_formatted.append(sc_formatted) + if object_categories: + for oc in object_categories: + oc_formatted = format_element(self.get_element(oc)) + object_categories_formatted.append(oc_formatted) if predicates: + for pred in predicates: + pred_formatted = format_element(self.get_element(pred)) + predicates_formatted.append(pred_formatted) inverse_predicates = list() - for pred_curie in predicates: + for pred_curie in predicates_formatted: predicate = self.get_element(pred_curie) if predicate: inverse_p = self.get_inverse(predicate.name) @@ -454,7 +468,9 @@ class Toolkit(object): inverse_predicates.append(inverse_p) inverse_predicates = self._format_all_elements(elements=inverse_predicates, formatted=True) - if subject_categories or predicates or object_categories: + + + if subject_categories_formatted or predicates_formatted or object_categories_formatted: # This feels like a bit of a brute force approach as an implementation, # but we just use the list of all association names to retrieve each # association record for filtering against the constraints? @@ -471,10 +487,10 @@ class Toolkit(object): # Try to match associations in the forward direction if not( - self.match_association(association, subject_categories, predicates, object_categories) or + self.match_association(association, subject_categories_formatted, predicates_formatted, object_categories_formatted) or ( match_inverses and - self.match_association(association, object_categories, inverse_predicates, subject_categories) + self.match_association(association, object_categories, inverse_predicates, subject_categories_formatted) ) ): continue
get_associations() returns an emtpy list We are trying to use `get_associations()` and are getting some unexpected results. A couple of examples I tried: `tk.get_associations( subject_categories = ["chemical entity"], predicates = ["affects"], object_categories= ["gene or gene product"] )`, and was expecting a `"chemical affects gene association"` to be returned, but instead got an empty list. Similarly for: `tk.get_associations( subject_categories = ["gene"], predicates = ["member of"], object_categories= ["gene family"] )` I was expecting to get `"gene to gene family association"`, but got an empty list as well. Is this the right usage for this function?
biolink/biolink-model-toolkit
diff --git a/tests/unit/test_toolkit.py b/tests/unit/test_toolkit.py index cec72ce..dd976e0 100644 --- a/tests/unit/test_toolkit.py +++ b/tests/unit/test_toolkit.py @@ -33,6 +33,7 @@ CHEMICAL_ENTITY = "chemical entity" CHEMICAL_ENTITY_CURIE = "biolink:ChemicalEntity" GENE = "gene" GENE_CURIE = "biolink:Gene" +GENE_OR_GENE_PRODUCT_CURIE: "biolink:GeneOrGeneProduct" GENE_OR_GENE_PRODUCT = "gene or gene product" GENE_OR_GENE_PRODUCT_CURIE = "biolink:GeneOrGeneProduct" GENOMIC_ENTITY = "genomic entity" @@ -556,6 +557,17 @@ def test_get_associations_without_parameters(toolkit): "biolink:Association", "biolink:ChemicalAffectsGeneAssociation" ] + ), + ( # Q8 - Check if "biolink:Gene -- biolink:affected -> biolink:SmallMolecule" - still no direct match + [GENE_OR_GENE_PRODUCT], + ["biolink:affected_by"], + ["biolink:ChemicalEntity"], + False, # match_inverses + [], # as of Biolink Model release 3.5.4, there is no direct match for this set of SPO parameters + [ + "biolink:Association", + "biolink:ChemicalAffectsGeneAssociation" + ] ) ] ) @@ -581,6 +593,27 @@ def test_get_associations_with_parameters( assert not any([entry in associations for entry in does_not_contain]) +def test_get_associations_gene_to_chemical(toolkit): + associations = toolkit.get_associations( + subject_categories=["biolink:ChemicalEntity"], + predicates=["biolink:affects"], + object_categories=["biolink:GeneOrGeneProduct"], + # we don't bother testing the 'format' flag simply in confidence + # that the associated code is already well tested in other contexts + formatted=True + ) + assert associations + + unformatted_associations = toolkit.get_associations( + subject_categories=["chemical entity"], + predicates=["affects"], + object_categories=["gene or gene product"], + formatted=True + ) + + assert unformatted_associations + + def test_get_all_node_properties(toolkit): properties = toolkit.get_all_node_properties() assert "provided by" in properties
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.7.0 attrs==25.3.0 -e git+https://github.com/biolink/biolink-model-toolkit.git@e421af4ebb7e33ce43a7d9de2e5a6ab4b9e94e5c#egg=bmt certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 curies==0.10.10 Deprecated==1.2.18 deprecation==2.1.0 eval_type_backport==0.2.2 exceptiongroup==1.2.2 hbreader==0.9.1 idna==3.10 iniconfig==2.1.0 isodate==0.7.2 json-flattener==0.1.9 jsonasobj2==1.0.4 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 linkml-runtime==1.8.3 packaging==24.2 pluggy==1.5.0 prefixcommons==0.1.12 prefixmaps==0.2.6 pydantic==2.11.1 pydantic_core==2.33.0 pyparsing==3.2.3 pytest==8.3.5 pytest-logging==2015.11.4 PyTrie==0.4.0 PyYAML==6.0.2 rdflib==7.1.4 referencing==0.36.2 requests==2.32.3 rpds-py==0.24.0 sortedcontainers==2.4.0 stringcase==1.2.0 tomli==2.2.1 typing-inspection==0.4.0 typing_extensions==4.13.0 urllib3==2.3.0 wrapt==1.17.2
name: biolink-model-toolkit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.7.0 - attrs==25.3.0 - bmt==1.4.1.post2.dev0+e421af4 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - curies==0.10.10 - deprecated==1.2.18 - deprecation==2.1.0 - eval-type-backport==0.2.2 - exceptiongroup==1.2.2 - hbreader==0.9.1 - idna==3.10 - iniconfig==2.1.0 - isodate==0.7.2 - json-flattener==0.1.9 - jsonasobj2==1.0.4 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - linkml-runtime==1.8.3 - packaging==24.2 - pluggy==1.5.0 - prefixcommons==0.1.12 - prefixmaps==0.2.6 - pydantic==2.11.1 - pydantic-core==2.33.0 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-logging==2015.11.4 - pytrie==0.4.0 - pyyaml==6.0.2 - rdflib==7.1.4 - referencing==0.36.2 - requests==2.32.3 - rpds-py==0.24.0 - sortedcontainers==2.4.0 - stringcase==1.2.0 - tomli==2.2.1 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - urllib3==2.3.0 - wrapt==1.17.2 prefix: /opt/conda/envs/biolink-model-toolkit
[ "tests/unit/test_toolkit.py::test_get_associations_gene_to_chemical" ]
[]
[ "tests/unit/test_toolkit.py::test_get_model_version", "tests/unit/test_toolkit.py::test_sv", "tests/unit/test_toolkit.py::test_get_denormalized_association_slots", "tests/unit/test_toolkit.py::test_get_id_prefixes", "tests/unit/test_toolkit.py::test_validate_edge", "tests/unit/test_toolkit.py::test_mixin_validate_edge", "tests/unit/test_toolkit.py::test_not_valid_edge", "tests/unit/test_toolkit.py::test_get_element_via_alias", "tests/unit/test_toolkit.py::test_predicate_map", "tests/unit/test_toolkit.py::test_rna", "tests/unit/test_toolkit.py::test_get_element_by_mapping", "tests/unit/test_toolkit.py::test_get_element_by_prefix", "tests/unit/test_toolkit.py::test_get_all_elements", "tests/unit/test_toolkit.py::test_get_all_entities", "tests/unit/test_toolkit.py::test_get_all_associations", "tests/unit/test_toolkit.py::test_filter_values_on_slot", "tests/unit/test_toolkit.py::test_match_association[association-subj_cats0-predicates0-obj_cats0-True-True]", "tests/unit/test_toolkit.py::test_match_association[chemical", "tests/unit/test_toolkit.py::test_match_association[gene", "tests/unit/test_toolkit.py::test_match_association[pairwise", "tests/unit/test_toolkit.py::test_match_association[organism", "tests/unit/test_toolkit.py::test_match_association[exon", "tests/unit/test_toolkit.py::test_get_associations_without_parameters", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[None-None-None-True-contains0-does_not_contain0]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories1-None-None-True-contains1-does_not_contain1]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories2-None-object_categories2-True-contains2-does_not_contain2]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories3-predicates3-object_categories3-True-contains3-does_not_contain3]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories4-predicates4-object_categories4-True-contains4-does_not_contain4]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories5-predicates5-object_categories5-True-contains5-does_not_contain5]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories6-predicates6-object_categories6-True-contains6-does_not_contain6]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories7-predicates7-object_categories7-False-contains7-does_not_contain7]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories8-predicates8-object_categories8-False-contains8-does_not_contain8]", "tests/unit/test_toolkit.py::test_get_associations_with_parameters[subject_categories9-predicates9-object_categories9-False-contains9-does_not_contain9]", "tests/unit/test_toolkit.py::test_get_all_node_properties", "tests/unit/test_toolkit.py::test_get_all_edge_properties", "tests/unit/test_toolkit.py::test_get_element", "tests/unit/test_toolkit.py::test_get_enum_via_element", "tests/unit/test_toolkit.py::test_is_node_property", "tests/unit/test_toolkit.py::test_is_association_slot", "tests/unit/test_toolkit.py::test_is_predicate", "tests/unit/test_toolkit.py::test_is_mixin", "tests/unit/test_toolkit.py::test_is_symmetric", "tests/unit/test_toolkit.py::test_is_translator_canonical_predicate", "tests/unit/test_toolkit.py::test_has_inverse", "tests/unit/test_toolkit.py::test_get_inverse", "tests/unit/test_toolkit.py::test_get_get_inverse_predicate", "tests/unit/test_toolkit.py::test_category", "tests/unit/test_toolkit.py::test_is_qualifier", "tests/unit/test_toolkit.py::test_is_enum", "tests/unit/test_toolkit.py::test_is_subproperty_of", "tests/unit/test_toolkit.py::test_validate_qualifier[--None-False]", "tests/unit/test_toolkit.py::test_validate_qualifier[subject", "tests/unit/test_toolkit.py::test_validate_qualifier[-upregulated-None-False]", "tests/unit/test_toolkit.py::test_validate_qualifier[aspect", "tests/unit/test_toolkit.py::test_validate_qualifier[biolink:subject_direction_qualifier-upregulated-None-True]", "tests/unit/test_toolkit.py::test_validate_qualifier[species", "tests/unit/test_toolkit.py::test_validate_qualifier[biolink:species_context_qualifier-NCBITaxon:9606-None-True0]", "tests/unit/test_toolkit.py::test_validate_qualifier[biolink:species_context_qualifier-NCBITaxon:9606-None-True1]", "tests/unit/test_toolkit.py::test_validate_qualifier[biolink:subject_aspect_qualifier-synthesis-associations13-True]", "tests/unit/test_toolkit.py::test_validate_qualifier[qualified", "tests/unit/test_toolkit.py::test_validate_qualifier[biolink:qualified_predicate-causes-associations15-True]", "tests/unit/test_toolkit.py::test_validate_qualifier[biolink:object_aspect_qualifier-activity_or_abundance-associations16-True]", "tests/unit/test_toolkit.py::test_is_permissible_value_of_enum", "tests/unit/test_toolkit.py::test_ancestors", "tests/unit/test_toolkit.py::test_permissible_value_ancestors", "tests/unit/test_toolkit.py::test_ancestors_for_kgx", "tests/unit/test_toolkit.py::test_descendants", "tests/unit/test_toolkit.py::test_children", "tests/unit/test_toolkit.py::test_parent", "tests/unit/test_toolkit.py::test_mapping", "tests/unit/test_toolkit.py::test_get_slot_domain", "tests/unit/test_toolkit.py::test_get_slot_range", "tests/unit/test_toolkit.py::test_get_all_slots_with_class_domain", "tests/unit/test_toolkit.py::test_get_all_slots_with_class_range", "tests/unit/test_toolkit.py::test_get_all_predicates_with_class_domain", "tests/unit/test_toolkit.py::test_get_all_predicates_with_class_range", "tests/unit/test_toolkit.py::test_get_all_properties_with_class_domain", "tests/unit/test_toolkit.py::test_get_all_properties_with_class_range", "tests/unit/test_toolkit.py::test_get_value_type_for_slot", "tests/unit/test_toolkit.py::test_get_all_types", "tests/unit/test_toolkit.py::test_get_all_multivalued_slots" ]
[]
BSD 3-Clause "New" or "Revised" License
18,541
548
[ "bmt/toolkit.py" ]
zarr-developers__zarr-python-1929
72005d71fe6e78c03870b3e3b28b3bea3f367043
2024-05-29 12:36:47
fb11810170e864aada188f656fdc254d2de82720
rabernat: This is my first PR to the V3 branch. How are we handling docs? Is there anything to update? d-v-b: > This is my first PR to the V3 branch. > > How are we handling docs? Is there anything to update? Docs are a (big) tbd, for the moment code changes alone are fine.
diff --git a/src/zarr/array.py b/src/zarr/array.py index 3e6cf553..698894ba 100644 --- a/src/zarr/array.py +++ b/src/zarr/array.py @@ -366,6 +366,15 @@ class AsyncArray: def shape(self) -> ChunkCoords: return self.metadata.shape + @property + def chunks(self) -> ChunkCoords: + if isinstance(self.metadata.chunk_grid, RegularChunkGrid): + return self.metadata.chunk_grid.chunk_shape + else: + raise ValueError( + f"chunk attribute is only available for RegularChunkGrid, this array has a {self.metadata.chunk_grid}" + ) + @property def size(self) -> int: return np.prod(self.metadata.shape).item() @@ -641,6 +650,10 @@ class Array: def shape(self) -> ChunkCoords: return self._async_array.shape + @property + def chunks(self) -> ChunkCoords: + return self._async_array.chunks + @property def size(self) -> int: return self._async_array.size
v3 arrays have no `.chunks` attribute Similar to: https://github.com/zarr-developers/zarr-python/issues/1924 V2 arrays have a `.chunks` attribute: https://zarr.readthedocs.io/en/stable/_autoapi/zarr.core.Array.html#zarr.core.Array.chunks V3 arrays don't: ```python import zarr arr = zarr.Array.create(store=zarr.store.MemoryStore(), shape=(10,), chunks=(5,), dtype="i4") arr.chunks # -> attribute error # instead it is available at arr.metadata.chunk_grid.chunk_shape ``` It would be a pretty disruptive API change to remove this. I understand that the ChunkGrid concept makes this more complicated to support. We should reimplement a sane default for this attribute for regular chunk grids. So much code likely relies on this parameter.
zarr-developers/zarr-python
diff --git a/tests/v3/test_group.py b/tests/v3/test_group.py index 9ce9b07a..c529e249 100644 --- a/tests/v3/test_group.py +++ b/tests/v3/test_group.py @@ -79,7 +79,7 @@ def test_group(store: MemoryStore | LocalStore) -> None: assert arr.dtype == data.dtype # TODO: update this once the array api settles down - # assert arr.chunk_shape == (2, 2) + assert arr.chunks == (2, 2) bar2 = foo["bar"] assert dict(bar2.attrs) == {"baz": "qux"}
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
2.18
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-asyncio", "mypy" ], "pre_install": null, "python": "3.10", "reqs_path": [ "requirements_dev_minimal.txt", "requirements_dev_numpy.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asciitree==0.3.3 coverage==7.8.0 crc32c==2.7.1 donfig==0.8.1.post1 exceptiongroup==1.2.2 fasteners==0.19 iniconfig==2.1.0 mypy==1.15.0 mypy-extensions==1.0.0 numcodecs==0.13.1 numpy==2.2.4 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 PyYAML==6.0.2 tomli==2.2.1 typing_extensions==4.13.0 -e git+https://github.com/zarr-developers/zarr-python.git@72005d71fe6e78c03870b3e3b28b3bea3f367043#egg=zarr zstandard==0.23.0
name: zarr-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py310h06a4308_0 - python=3.10.16=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py310h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py310h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asciitree==0.3.3 - coverage==7.8.0 - crc32c==2.7.1 - donfig==0.8.1.post1 - exceptiongroup==1.2.2 - fasteners==0.19 - iniconfig==2.1.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - numcodecs==0.13.1 - numpy==2.2.4 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pyyaml==6.0.2 - tomli==2.2.1 - typing-extensions==4.13.0 - zarr==2.16.2.dev112+g72005d71 - zstandard==0.23.0 prefix: /opt/conda/envs/zarr-python
[ "tests/v3/test_group.py::test_group[local]", "tests/v3/test_group.py::test_group[memory]" ]
[]
[ "tests/v3/test_group.py::test_group_children[local]", "tests/v3/test_group.py::test_group_children[memory]", "tests/v3/test_group.py::test_group_create[True-local]", "tests/v3/test_group.py::test_group_create[True-memory]", "tests/v3/test_group.py::test_group_create[False-local]", "tests/v3/test_group.py::test_group_create[False-memory]", "tests/v3/test_group.py::test_asyncgroup_create[True-2-local]", "tests/v3/test_group.py::test_asyncgroup_create[True-2-memory]", "tests/v3/test_group.py::test_asyncgroup_create[True-3-local]", "tests/v3/test_group.py::test_asyncgroup_create[True-3-memory]", "tests/v3/test_group.py::test_asyncgroup_create[False-2-local]", "tests/v3/test_group.py::test_asyncgroup_create[False-2-memory]", "tests/v3/test_group.py::test_asyncgroup_create[False-3-local]", "tests/v3/test_group.py::test_asyncgroup_create[False-3-memory]", "tests/v3/test_group.py::test_asyncgroup_attrs[2-local]", "tests/v3/test_group.py::test_asyncgroup_attrs[2-memory]", "tests/v3/test_group.py::test_asyncgroup_attrs[3-local]", "tests/v3/test_group.py::test_asyncgroup_attrs[3-memory]", "tests/v3/test_group.py::test_asyncgroup_open[2-local]", "tests/v3/test_group.py::test_asyncgroup_open[2-memory]", "tests/v3/test_group.py::test_asyncgroup_open[3-local]", "tests/v3/test_group.py::test_asyncgroup_open[3-memory]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[2-local]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[2-memory]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[3-local]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[3-memory]", "tests/v3/test_group.py::test_asyncgroup_from_dict[data0-local]", "tests/v3/test_group.py::test_asyncgroup_from_dict[data0-memory]", "tests/v3/test_group.py::test_asyncgroup_from_dict[data1-local]", "tests/v3/test_group.py::test_asyncgroup_from_dict[data1-memory]", "tests/v3/test_group.py::test_asyncgroup_getitem[2-local]", "tests/v3/test_group.py::test_asyncgroup_getitem[2-memory]", "tests/v3/test_group.py::test_asyncgroup_getitem[3-local]", "tests/v3/test_group.py::test_asyncgroup_getitem[3-memory]", "tests/v3/test_group.py::test_asyncgroup_delitem[2-local]", "tests/v3/test_group.py::test_asyncgroup_delitem[2-memory]", "tests/v3/test_group.py::test_asyncgroup_delitem[3-local]", "tests/v3/test_group.py::test_asyncgroup_delitem[3-memory]", "tests/v3/test_group.py::test_asyncgroup_create_group[2-local]", "tests/v3/test_group.py::test_asyncgroup_create_group[2-memory]", "tests/v3/test_group.py::test_asyncgroup_create_group[3-local]", "tests/v3/test_group.py::test_asyncgroup_create_group[3-memory]", "tests/v3/test_group.py::test_asyncgroup_create_array[2-local]", "tests/v3/test_group.py::test_asyncgroup_create_array[2-memory]", "tests/v3/test_group.py::test_asyncgroup_create_array[3-local]", "tests/v3/test_group.py::test_asyncgroup_create_array[3-memory]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[2-local]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[2-memory]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[3-local]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[3-memory]", "tests/v3/test_group.py::test_group_init[2-local]", "tests/v3/test_group.py::test_group_init[2-memory]", "tests/v3/test_group.py::test_group_init[3-local]", "tests/v3/test_group.py::test_group_init[3-memory]", "tests/v3/test_group.py::test_group_name_properties[2-local]", "tests/v3/test_group.py::test_group_name_properties[2-memory]", "tests/v3/test_group.py::test_group_name_properties[3-local]", "tests/v3/test_group.py::test_group_name_properties[3-memory]" ]
[]
MIT License
18,546
269
[ "src/zarr/array.py" ]
hugovk__pypistats-438
bfda2c984f05adfc794a11744db621476a71a836
2024-05-30 06:34:53
bfda2c984f05adfc794a11744db621476a71a836
diff --git a/src/pypistats/__init__.py b/src/pypistats/__init__.py index 3bd7ac4..db31394 100644 --- a/src/pypistats/__init__.py +++ b/src/pypistats/__init__.py @@ -124,6 +124,9 @@ def pypi_stats_api( _save_cache(cache_file, res) + if not res.get("data", []): + return f"No data found for https://pypi.org/project/{res.get('package', '')}/" + # Actual first and last dates of the fetched data first, last = _date_range(res["data"])
Improper IndexError handling `File "/home/..../lib/python3.11/site-packages/pypistats/__init__.py", line 261, in _date_range first = data[0]["date"] ~~~~^^^ IndexError: list index out of range` The exception does not handle the data list is empty. The error will cause the program to stop without proper handling.
hugovk/pypistats
diff --git a/tests/test_pypistats.py b/tests/test_pypistats.py index 470ab32..85a205b 100644 --- a/tests/test_pypistats.py +++ b/tests/test_pypistats.py @@ -747,3 +747,22 @@ Date range: 2020-05-01 - 2020-05-01 # Assert assert isinstance(output, pandas.DataFrame) assert str(output).strip() == expected_output.strip() + + @respx.mock + def test_package_not_exist(self) -> None: + # Arrange + package = "a" * 100 + mocked_response = f"""{{ + "data":[], + "package":"{package}", + "type":"python_major_downloads" + }}""" + mocked_url = f"https://pypistats.org/api/packages/{package}/python_major" + expected_output = f"No data found for https://pypi.org/project/{package}/" + + # Act + respx.get(mocked_url).respond(content=mocked_response) + output = pypistats.python_major(package) + + # Assert + assert output == expected_output
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[numpy,pandas]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
anyio==4.9.0 certifi==2025.1.31 chardet==5.2.0 coverage==7.8.0 DataProperty==1.1.0 dominate==2.9.1 exceptiongroup==1.2.2 execnet==2.1.1 freezegun==1.5.0 h11==0.14.0 httpcore==1.0.7 httpx==0.27.0 idna==3.10 iniconfig==2.1.0 mbstrdecoder==1.1.4 numpy==1.26.4 packaging==24.2 pandas==2.2.2 pathvalidate==3.2.3 platformdirs==4.2.1 pluggy==1.5.0 prettytable==3.10.0 -e git+https://github.com/hugovk/pypistats.git@bfda2c984f05adfc794a11744db621476a71a836#egg=pypistats pytablewriter==1.2.0 pytest==8.2.0 pytest-cov==5.0.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 python-slugify==8.0.4 pytz==2025.2 respx==0.21.1 six==1.17.0 sniffio==1.3.1 tabledata==1.3.4 tcolorpy==0.1.7 termcolor==2.4.0 text-unidecode==1.3 tomli==2.2.1 typepy==1.3.4 typing_extensions==4.13.0 tzdata==2025.2 wcwidth==0.2.13
name: pypistats channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - anyio==4.9.0 - certifi==2025.1.31 - chardet==5.2.0 - coverage==7.8.0 - dataproperty==1.1.0 - dominate==2.9.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - freezegun==1.5.0 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.27.0 - idna==3.10 - iniconfig==2.1.0 - mbstrdecoder==1.1.4 - numpy==1.26.4 - packaging==24.2 - pandas==2.2.2 - pathvalidate==3.2.3 - platformdirs==4.2.1 - pluggy==1.5.0 - prettytable==3.10.0 - pypistats==1.5.1.dev58 - pytablewriter==1.2.0 - pytest==8.2.0 - pytest-cov==5.0.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - python-slugify==8.0.4 - pytz==2025.2 - respx==0.21.1 - six==1.17.0 - sniffio==1.3.1 - tabledata==1.3.4 - tcolorpy==0.1.7 - termcolor==2.4.0 - text-unidecode==1.3 - tomli==2.2.1 - typepy==1.3.4 - typing-extensions==4.13.0 - tzdata==2025.2 - wcwidth==0.2.13 prefix: /opt/conda/envs/pypistats
[ "tests/test_pypistats.py::TestPypiStats::test_package_not_exist" ]
[]
[ "tests/test_pypistats.py::TestPypiStats::test__filter_no_filters_no_change", "tests/test_pypistats.py::TestPypiStats::test__filter_start_date", "tests/test_pypistats.py::TestPypiStats::test__filter_end_date", "tests/test_pypistats.py::TestPypiStats::test__filter_start_and_end_date", "tests/test_pypistats.py::TestPypiStats::test_warn_if_start_date_before_earliest_available", "tests/test_pypistats.py::TestPypiStats::test_error_if_end_date_before_earliest_available", "tests/test_pypistats.py::TestPypiStats::test__paramify[period-None-]", "tests/test_pypistats.py::TestPypiStats::test__paramify[period-day-&period=day]", "tests/test_pypistats.py::TestPypiStats::test__paramify[mirrors-True-&mirrors=true]", "tests/test_pypistats.py::TestPypiStats::test__paramify[version-3-&version=3]", "tests/test_pypistats.py::TestPypiStats::test__paramify[version-3.7-&version=3.7]", "tests/test_pypistats.py::TestPypiStats::test__colourify", "tests/test_pypistats.py::TestPypiStats::test__tabulate_noarg", "tests/test_pypistats.py::TestPypiStats::test__tabulate[html]", "tests/test_pypistats.py::TestPypiStats::test__tabulate[markdown]", "tests/test_pypistats.py::TestPypiStats::test__tabulate[pretty]", "tests/test_pypistats.py::TestPypiStats::test__tabulate[rst]", "tests/test_pypistats.py::TestPypiStats::test__tabulate[tsv]", "tests/test_pypistats.py::TestPypiStats::test__sort", "tests/test_pypistats.py::TestPypiStats::test__sort_recent", "tests/test_pypistats.py::TestPypiStats::test__monthly_total", "tests/test_pypistats.py::TestPypiStats::test__total", "tests/test_pypistats.py::TestPypiStats::test__total_recent", "tests/test_pypistats.py::TestPypiStats::test__date_range", "tests/test_pypistats.py::TestPypiStats::test__date_range_no_dates_in_data", "tests/test_pypistats.py::TestPypiStats::test__grand_total", "tests/test_pypistats.py::TestPypiStats::test__grand_total_one_row", "tests/test_pypistats.py::TestPypiStats::test__grand_total_recent", "tests/test_pypistats.py::TestPypiStats::test__percent", "tests/test_pypistats.py::TestPypiStats::test__percent_one_row", "tests/test_pypistats.py::TestPypiStats::test__percent_recent", "tests/test_pypistats.py::TestPypiStats::test_valid_json", "tests/test_pypistats.py::TestPypiStats::test_recent_tabular[markdown]", "tests/test_pypistats.py::TestPypiStats::test_recent_tabular[tsv]", "tests/test_pypistats.py::TestPypiStats::test_overall_tabular_start_date", "tests/test_pypistats.py::TestPypiStats::test_overall_tabular_end_date", "tests/test_pypistats.py::TestPypiStats::test_python_major_json", "tests/test_pypistats.py::TestPypiStats::test_python_minor_json", "tests/test_pypistats.py::TestPypiStats::test_system_tabular", "tests/test_pypistats.py::TestPypiStats::test_python_minor_monthly", "tests/test_pypistats.py::TestPypiStats::test_versions_are_strings", "tests/test_pypistats.py::TestPypiStats::test_format_numpy", "tests/test_pypistats.py::TestPypiStats::test_format_pandas" ]
[]
MIT License
18,552
161
[ "src/pypistats/__init__.py" ]
dstl__Stone-Soup-1033
279f8a5291afa29d2c6fe3316dbb59f18eb7ce85
2024-05-30 07:57:51
279f8a5291afa29d2c6fe3316dbb59f18eb7ce85
diff --git a/stonesoup/metricgenerator/ospametric.py b/stonesoup/metricgenerator/ospametric.py index 26560b9a..c27195af 100644 --- a/stonesoup/metricgenerator/ospametric.py +++ b/stonesoup/metricgenerator/ospametric.py @@ -56,7 +56,7 @@ class GOSPAMetric(MetricGenerator): """ Computes the Generalized Optimal SubPattern Assignment (GOSPA) metric for two sets of :class:`~.Track` objects. This implementation of GOSPA - is based on the auction algorithm. + is based on the modified Jonker-Volgenant algorithm. The GOSPA metric is calculated at each time step in which a :class:`~.Track` object is present @@ -205,14 +205,13 @@ class GOSPAMetric(MetricGenerator): time_range=TimeRange(min(timestamps), max(timestamps)), generator=self) - def compute_assignments(self, cost_matrix, max_iter): - """Compute assignments using Auction Algorithm. + def compute_assignments(self, cost_matrix): + """Compute assignments using modified Jonker-Volgenant algorithm Parameters ---------- cost_matrix: Matrix (size mxn) that denotes the cost of assigning mth truth state to each of the n measured states. - max_iter: Maximum number of iterations to perform Returns ------- @@ -228,78 +227,13 @@ class GOSPAMetric(MetricGenerator): # Index for objects that will be left un-assigned. unassigned_idx = -1 - opt_cost = 0.0 measured_to_truth = np.full((n_measured, ), unassigned_idx) truth_to_measured = np.full((m_truth, ), unassigned_idx) - if m_truth == 1: - # Corner case 1: if there is only one truth state. - max_cost_idx = np.argmax(cost_matrix, axis=1).item() - opt_cost = cost_matrix[0, max_cost_idx] - truth_to_measured[0] = max_cost_idx - measured_to_truth[max_cost_idx] = 0 - - return truth_to_measured, measured_to_truth, opt_cost - - if n_measured == 1: - # Corner case 1: if there is only one measured state. - max_cost_idx = np.argmax(cost_matrix, axis=0).item() - opt_cost = cost_matrix[max_cost_idx, 0] - measured_to_truth[0] = max_cost_idx - truth_to_measured[max_cost_idx] = 0 - - return truth_to_measured, measured_to_truth, opt_cost - - swap_dim_flag = False - epsil = 1. / np.max([m_truth, n_measured]) - - if n_measured < m_truth: - # The implementation only works when - # m_truth <= n_measured - # So swap cost matrix - cost_matrix = cost_matrix.transpose() - m_truth, n_measured = cost_matrix.shape - measured_to_truth, truth_to_measured = truth_to_measured, measured_to_truth - swap_dim_flag = True - - # Initial cost for each measured state - c_measured = np.zeros((n_measured, )) - k_iter = 0 - - while not np.all(truth_to_measured != unassigned_idx) and k_iter <= max_iter: - for i in range(m_truth): - if truth_to_measured[i] == unassigned_idx: - # Unassigned truth object 'i' bids for the best - # measured object j_star - - # Value for each measured object for truth 'i' - tmp_mat = cost_matrix[i, :] - c_measured - j = np.argsort(tmp_mat)[::-1] - # Best measurement for truth 'i' - j_star = j[0] - # 1st and 2nd best value for truth 'i' - v_i_j_star, w_i_j_star = tmp_mat[j[:2]] - - # Bid for measured j_star - if w_i_j_star != -np.inf: - c_measured[j_star] += v_i_j_star - w_i_j_star + epsil - else: - c_measured[j_star] += v_i_j_star + epsil - - # If j_star is unassigned - if measured_to_truth[j_star] != unassigned_idx: - opt_cost -= cost_matrix[measured_to_truth[j_star], j_star] - truth_to_measured[measured_to_truth[j_star]] = unassigned_idx - - measured_to_truth[j_star] = i - truth_to_measured[i] = j_star - - # update the cost of new assignment - opt_cost += cost_matrix[i, j_star] - k_iter += 1 - - if swap_dim_flag: - measured_to_truth, truth_to_measured = truth_to_measured, measured_to_truth + row_ind, col_ind = linear_sum_assignment(-cost_matrix) + opt_cost = cost_matrix[row_ind, col_ind].sum() + truth_to_measured[row_ind] = col_ind + measured_to_truth[col_ind] = row_ind return truth_to_measured, measured_to_truth, opt_cost @@ -391,12 +325,11 @@ class GOSPAMetric(MetricGenerator): if self.alpha == 2: gospa_metric['missed'] = opt_cost else: - # Use auction algorithm when both truth_states + # Use assignment algorithm when both truth_states # and measured_states are non-empty cost_matrix = -1. * np.power(cost_matrix, self.p) truth_to_measured_assignment, measured_to_truth_assignment, _ =\ - self.compute_assignments(cost_matrix, - 10 * num_truth_states * num_measured_states) + self.compute_assignments(cost_matrix) opt_cost -= np.sum(measured_to_truth_assignment == unassigned_index) * dummy_cost if self.alpha == 2:
Low efficiency in GOSPA metric computations I'm using [the GOSPA metric](https://stonesoup.readthedocs.io/en/latest/stonesoup.metricgenerator.ospametric.html#stonesoup.metricgenerator.ospametric.GOSPAMetric) to evaluate the tracking results in a scenario that has generated 40 tracks over 30,000 time steps, and I've been waiting for results for more than a couple of hours. I understand that this isn't a trivial scenario, but it made me think about how efficient is the metric's implementation. The description indicates that the metric relies on the auction algorithm, which may not be the fastest option here. Angel Garcia-Fernandez [provides](https://github.com/Agarciafernandez/MTT/blob/master/GOSPA%20code/GOSPA.m) an improved (MATLAB) implementation that uses the [`assign2D`](https://github.com/schwehr/Tracker-Component-Library/blob/master/Assignment%20Algorithms/2D%20Assignment/assign2D.m) function instead. It would be great to have it in Stone Soup, provided that `assign2D` has already been [implemented](https://stonesoup.readthedocs.io/en/latest/stonesoup.dataassociator.html#stonesoup.dataassociator.neighbour.GNNWith2DAssignment) to speed up the GNN algorithm.
dstl/Stone-Soup
diff --git a/stonesoup/metricgenerator/tests/test_ospametric.py b/stonesoup/metricgenerator/tests/test_ospametric.py index 0dadce50..814b85c7 100644 --- a/stonesoup/metricgenerator/tests/test_ospametric.py +++ b/stonesoup/metricgenerator/tests/test_ospametric.py @@ -51,8 +51,7 @@ def test_gospametric_compute_assignments(num_states): truth_obj.states) neg_cost_matrix = -1.*cost_matrix meas_to_truth, truth_to_meas, opt_cost =\ - generator.compute_assignments(neg_cost_matrix, - 10 * num_states * num_states) + generator.compute_assignments(neg_cost_matrix) assert opt_cost == 0.0 assert np.array_equal(meas_to_truth, truth_to_meas) @@ -64,8 +63,7 @@ def test_gospametric_compute_assignments(num_states): truth_obj.states) neg_cost_matrix = -1.*cost_matrix meas_to_truth, truth_to_meas, opt_cost = \ - generator.compute_assignments(neg_cost_matrix, - 10 * num_states * num_states) + generator.compute_assignments(neg_cost_matrix) assert opt_cost == 0.0 assert np.array_equal(meas_to_truth, truth_to_meas[:-1]) @@ -78,8 +76,7 @@ def test_gospametric_compute_assignments(num_states): truth_obj.states[:-1]) neg_cost_matrix = -1.*cost_matrix meas_to_truth, truth_to_meas, opt_cost = \ - generator.compute_assignments(neg_cost_matrix, - 10 * num_states * num_states) + generator.compute_assignments(neg_cost_matrix) assert opt_cost == 0.0 assert np.array_equal(meas_to_truth[:-1], truth_to_meas)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "pytest-remotedata", "pytest-skip-slow" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
absl-py==2.2.1 alabaster==0.7.16 babel==2.17.0 branca==0.8.1 certifi==2025.1.31 charset-normalizer==3.4.1 confluent-kafka==2.9.0 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 docutils==0.21.2 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work flake8==7.2.0 folium==0.19.5 fonttools==4.56.0 h5py==3.13.0 idna==3.10 imagesize==1.4.1 immutabledict==4.2.1 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 kiwisolver==1.4.7 MarkupSafe==3.0.2 matplotlib==3.9.4 mccabe==0.7.0 mergedeep==1.3.4 narwhals==1.32.0 numpy==2.0.2 ordered-set==4.1.0 ortools==9.12.4544 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pillow==11.1.0 plotly==6.0.1 pluggy @ file:///croot/pluggy_1733169602837/work protobuf==5.29.4 pycodestyle==2.13.0 pyflakes==3.3.2 Pygments==2.19.1 pymap3d==3.1.0 pyparsing==3.2.3 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 pytest-remotedata==0.4.1 pytest-skip-slow==0.0.5 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.32.3 rtree==1.4.0 ruamel.yaml==0.18.10 ruamel.yaml.clib==0.2.12 scipy==1.13.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-gallery==0.19.0 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 -e git+https://github.com/dstl/Stone-Soup.git@279f8a5291afa29d2c6fe3316dbb59f18eb7ce85#egg=stonesoup tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tzdata==2025.2 urllib3==2.3.0 utm==0.8.1 xyzservices==2025.1.0 zipp==3.21.0
name: Stone-Soup channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - absl-py==2.2.1 - alabaster==0.7.16 - babel==2.17.0 - branca==0.8.1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - confluent-kafka==2.9.0 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - docutils==0.21.2 - flake8==7.2.0 - folium==0.19.5 - fonttools==4.56.0 - h5py==3.13.0 - idna==3.10 - imagesize==1.4.1 - immutabledict==4.2.1 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - jinja2==3.1.6 - kiwisolver==1.4.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - mccabe==0.7.0 - mergedeep==1.3.4 - narwhals==1.32.0 - numpy==2.0.2 - ordered-set==4.1.0 - ortools==9.12.4544 - pandas==2.2.3 - pillow==11.1.0 - plotly==6.0.1 - protobuf==5.29.4 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pygments==2.19.1 - pymap3d==3.1.0 - pyparsing==3.2.3 - pytest-cov==6.0.0 - pytest-remotedata==0.4.1 - pytest-skip-slow==0.0.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.32.3 - rtree==1.4.0 - ruamel-yaml==0.18.10 - ruamel-yaml-clib==0.2.12 - scipy==1.13.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-gallery==0.19.0 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - stonesoup==1.3.dev167+g279f8a52 - tzdata==2025.2 - urllib3==2.3.0 - utm==0.8.1 - xyzservices==2025.1.0 - zipp==3.21.0 prefix: /opt/conda/envs/Stone-Soup
[ "stonesoup/metricgenerator/tests/test_ospametric.py::test_gospametric_compute_assignments[2]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_gospametric_compute_assignments[5]" ]
[]
[ "stonesoup/metricgenerator/tests/test_ospametric.py::test_gospametric_extractstates", "stonesoup/metricgenerator/tests/test_ospametric.py::test_gospametric_cost_matrix", "stonesoup/metricgenerator/tests/test_ospametric.py::test_gospametric_compute_gospa_metric", "stonesoup/metricgenerator/tests/test_ospametric.py::test_gospametric_computemetric", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospametric_extractstates", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospametric_computecostmatrix", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospametric_computeospadistance", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospametric_computemetric[p=1]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospametric_computemetric[p=2]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospametric_computemetric[p=inf]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_switching_gospametric_computemetric", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospa_computemetric_cardinality_error[p=1]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospa_computemetric_cardinality_error[p=2]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_ospa_computemetric_cardinality_error[p=inf]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_switching_loss[associations0-expected_losses0]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_switching_loss[associations1-expected_losses1]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_switching_loss[associations2-expected_losses2]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_switching_loss[associations3-expected_losses3]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_switching_loss[associations4-expected_losses4]", "stonesoup/metricgenerator/tests/test_ospametric.py::test_switching_loss[associations5-expected_losses5]" ]
[]
MIT License
18,554
1,396
[ "stonesoup/metricgenerator/ospametric.py" ]
BlueBrain__NeuroM-1128
94951b81f3a71d3fbede7e2255d8446371c5fd8b
2024-05-30 08:09:00
94951b81f3a71d3fbede7e2255d8446371c5fd8b
codecov-commenter: ## [Codecov](https://app.codecov.io/gh/BlueBrain/NeuroM/pull/1128?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=BlueBrain) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 100.00%. Comparing base [(`548e054`)](https://app.codecov.io/gh/BlueBrain/NeuroM/commit/548e054a9d7e1509a301f84cbe6bbd03b446565f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=BlueBrain) to head [(`2182759`)](https://app.codecov.io/gh/BlueBrain/NeuroM/commit/2182759fcd52eb7d405384f291f104fad350e39a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=BlueBrain). > :exclamation: **Current head 2182759 differs from pull request most recent head b21324a** > > Please [upload](https://docs.codecov.com/docs/codecov-uploader) reports for the commit b21324a to get more accurate results. <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## master #1128 +/- ## ========================================= Coverage 100.00% 100.00% ========================================= Files 35 34 -1 Lines 2706 2671 -35 ========================================= - Hits 2706 2671 -35 ``` </details>
diff --git a/neurom/core/morphology.py b/neurom/core/morphology.py index 1431eda..6852aee 100644 --- a/neurom/core/morphology.py +++ b/neurom/core/morphology.py @@ -454,8 +454,10 @@ class Neurite: subtree_types = [next(it).to_morphio().type] for section in it: - if section.type != section.parent.type: - subtree_types.append(NeuriteType(section.to_morphio().type)) + # A subtree can start from a single branch or as a fork of the same type from a parent + # with different type. + if section.type not in (section.parent.type, subtree_types[-1]): + subtree_types.append(section.to_morphio().type) return subtree_types
One test failing with 4.0.0: `Arrays are not almost equal to 5 decimals` While updating the package to 4.0.0 in Fedora rawhide (the dev branch), we see one test failing: ``` > assert_almost_equal(s.volume, 3160.274957542371, decimal=5) tests/core/test_soma.py:263: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ args = (3160.2749000561025, 3160.274957542371), kwds = {'decimal': 5} @wraps(func) def inner(*args, **kwds): with self._recreate_cm(): > return func(*args, **kwds) E AssertionError: E Arrays are not almost equal to 5 decimals E ACTUAL: 3160.2749000561025 E DESIRED: 3160.274957542371 /usr/lib64/python3.12/contextlib.py:81: AssertionError ``` The values are close, but not as close as they should be. How should we handle this please? Complete log is here: [fedora-rawhide-neuroml-build-log.txt](https://github.com/BlueBrain/NeuroM/files/15483281/fedora-rawhide-neuroml-build-log.txt)
BlueBrain/NeuroM
diff --git a/tests/core/test_soma.py b/tests/core/test_soma.py index cef38c1..c6cc305 100644 --- a/tests/core/test_soma.py +++ b/tests/core/test_soma.py @@ -223,7 +223,7 @@ def test_Soma_Cylinders(): # area of a cylinder (excluding end caps) is: # 2*pi*r*h == 4*pi*r^2 == area of a sphere of radius 20 assert s.radius == 20.0 - assert_almost_equal(s.area, 5026.548245743669) + assert_almost_equal(s.area, 5026.548245743669, decimal=5) assert_array_equal(s.center, [0, 0, -10]) assert 'SomaCylinders' in str(s) @@ -241,7 +241,7 @@ def test_Soma_Cylinders(): assert 'SomaNeuromorphoThreePointCylinders' in str(s) assert list(s.center) == [0.0, 0.0, 0.0] - assert_almost_equal(s.area, 1256.6370614) + assert_almost_equal(s.area, 1256.6370614, decimal=5) # some neuromorpho files don't follow the convention # but have (ys + rs) as point 2, and have xs different in each line @@ -260,7 +260,7 @@ def test_Soma_Cylinders(): assert 'SomaNeuromorphoThreePointCylinders' in str(s) assert list(s.center) == [0.0, 0.0, 0.0] assert_almost_equal(s.area, 794.76706126368811, decimal=5) - assert_almost_equal(s.volume, 3160.274957542371, decimal=5) + assert_almost_equal(s.volume, 3160.274957542371, decimal=3) s = load_morphology( StringIO( @@ -276,7 +276,7 @@ def test_Soma_Cylinders(): ).soma assert list(s.center) == [0.0, 0.0, 0.0] - assert_almost_equal(s.area, 444.288293851) # cone area, not including bottom + assert_almost_equal(s.area, 444.288293851, decimal=5) # cone area, not including bottom def test_soma_overlaps(): diff --git a/tests/test_mixed.py b/tests/test_mixed.py index b3bed77..d06177e 100644 --- a/tests/test_mixed.py +++ b/tests/test_mixed.py @@ -1140,3 +1140,26 @@ def test_sholl_frequency_pop(mixed_morph): 2, 0, ] + + +def test_axon_fork_as_axon_carrying_dendrite(): + """Test that a axon subtree starting as a fork is considered an AcD.""" + m = neurom.load_morphology( + """ + 1 1 0 0 0 0.5 -1 + 2 3 0 1 0 0.1 1 + 3 3 1 2 0 0.1 2 + 4 2 1 4 0 0.1 3 + 5 2 1 4 1 0.1 4 + 6 2 1 4 -1 0.1 4 + 7 2 2 3 0 0.1 3 + 8 2 2 4 0 0.1 7 + 9 2 3 3 0 0.1 7 + 10 2 3 3 1 0.1 9 + 11 2 3 3 -1 0.1 9 + """, + reader="swc", + process_subtrees=True, + ) + neurite = m.neurites[0] + assert neurite.type is NeuriteType.axon_carrying_dendrite
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 1 }
4.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[plotly]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cached-property==2.0.1 click==8.1.8 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work fonttools==4.56.0 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work kiwisolver==1.4.7 matplotlib==3.9.4 morphio==3.4.0 narwhals==1.32.0 -e git+https://github.com/BlueBrain/NeuroM.git@94951b81f3a71d3fbede7e2255d8446371c5fd8b#egg=neurom numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pillow==11.1.0 plotly==6.0.1 pluggy @ file:///croot/pluggy_1733169602837/work psutil==7.0.0 pyparsing==3.2.3 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 scipy==1.13.1 six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tqdm==4.67.1 tzdata==2025.2 zipp==3.21.0
name: NeuroM channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cached-property==2.0.1 - click==8.1.8 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - fonttools==4.56.0 - importlib-resources==6.5.2 - kiwisolver==1.4.7 - matplotlib==3.9.4 - morphio==3.4.0 - narwhals==1.32.0 - neurom==4.0.1.dev1 - numpy==2.0.2 - pandas==2.2.3 - pillow==11.1.0 - plotly==6.0.1 - psutil==7.0.0 - pyparsing==3.2.3 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - scipy==1.13.1 - six==1.17.0 - tqdm==4.67.1 - tzdata==2025.2 - zipp==3.21.0 prefix: /opt/conda/envs/NeuroM
[ "tests/test_mixed.py::test_axon_fork_as_axon_carrying_dendrite" ]
[ "tests/core/test_soma.py::test_Soma_ThreePointCylinder" ]
[ "tests/core/test_soma.py::test_no_soma_builder", "tests/core/test_soma.py::test_no_soma", "tests/core/test_soma.py::test_Soma_SinglePoint", "tests/core/test_soma.py::test_Soma_contour", "tests/core/test_soma.py::test_Soma_ThreePointCylinder_invalid_radius", "tests/core/test_soma.py::test_Soma_ThreePointCylinder_invalid", "tests/core/test_soma.py::test_SomaC", "tests/core/test_soma.py::test_soma_points_2", "tests/core/test_soma.py::test_Soma_Cylinders", "tests/core/test_soma.py::test_soma_overlaps", "tests/core/test_soma.py::test_morphio_soma", "tests/core/test_soma.py::test_soma_undefined_area", "tests/test_mixed.py::test_neurite_type__repr[0-<NeuriteType.undefined:", "tests/test_mixed.py::test_neurite_type__repr[32-<NeuriteType.all:", "tests/test_mixed.py::test_neurite_type__repr[value2-<NeuriteType.axon_carrying_dendrite:", "tests/test_mixed.py::test_neurite_type__str[0-NeuriteType.undefined]", "tests/test_mixed.py::test_neurite_type__str[32-NeuriteType.all]", "tests/test_mixed.py::test_neurite_type__str[value2-NeuriteType.axon_carrying_dendrite]", "tests/test_mixed.py::test_int_or_tuple[2-2]", "tests/test_mixed.py::test_int_or_tuple[values1-2]", "tests/test_mixed.py::test_int_or_tuple[NeuriteType.axon-2]", "tests/test_mixed.py::test_int_or_tuple[values3-expected3]", "tests/test_mixed.py::test_int_or_tuple[values4-expected4]", "tests/test_mixed.py::test_int_or_tuple[values5-expected5]", "tests/test_mixed.py::test_neurite_type__call[NeuriteType.axon-NeuriteType.axon]", "tests/test_mixed.py::test_neurite_type__call[values1-NeuriteType.axon]", "tests/test_mixed.py::test_neurite_type__call[2-NeuriteType.axon]", "tests/test_mixed.py::test_neurite_type__call[values3-NeuriteType.axon_carrying_dendrite]", "tests/test_mixed.py::test_neurite_type__call[values4-NeuriteType.axon_carrying_dendrite]", "tests/test_mixed.py::test_create_neurite_type", "tests/test_mixed.py::test_create_neurite_type__mixed", "tests/test_mixed.py::test_neurite_type__eq[0-0-True]", "tests/test_mixed.py::test_neurite_type__eq[0-asdf-False]", "tests/test_mixed.py::test_neurite_type__eq[32-32-True]", "tests/test_mixed.py::test_neurite_type__eq[3-1-False]", "tests/test_mixed.py::test_neurite_type__eq[3-3-True]", "tests/test_mixed.py::test_neurite_type__eq[3-2-False]", "tests/test_mixed.py::test_neurite_type__eq[3-4-False]", "tests/test_mixed.py::test_neurite_type__eq[3-right7-True]", "tests/test_mixed.py::test_neurite_type__eq[left8-right8-True]", "tests/test_mixed.py::test_neurite_type__eq[left9-right9-False]", "tests/test_mixed.py::test_neurite_type__eq[left10-2-True]", "tests/test_mixed.py::test_neurite_type__eq[left11-3-True]", "tests/test_mixed.py::test_neurite_type__eq[left12-4-False]", "tests/test_mixed.py::test_neurite_type__pickle[NeuriteType.axon]", "tests/test_mixed.py::test_neurite_type__pickle[NeuriteType.axon_carrying_dendrite]", "tests/test_mixed.py::test_neurite_type__raises[None]", "tests/test_mixed.py::test_neurite_type__raises[value1]", "tests/test_mixed.py::test_neurite_type__raises[UNKNOWN", "tests/test_mixed.py::test_neurite_type__raises[value3]", "tests/test_mixed.py::test_heterogeneous_neurites", "tests/test_mixed.py::test_iter_sections", "tests/test_mixed.py::test_is_homogeneous_point", "tests/test_mixed.py::test_subtypes", "tests/test_mixed.py::test_number_of_sections", "tests/test_mixed.py::test_multine_neurite_types", "tests/test_mixed.py::test_iter_neurites__heterogeneous", "tests/test_mixed.py::test_iter_neurites__homogeneous", "tests/test_mixed.py::test_core_iter_sections__heterogeneous", "tests/test_mixed.py::test_features_neurite_map_sections__heterogeneous", "tests/test_mixed.py::test_features_neurite_map_sections[ipreorder-NeuriteType.all-9]", "tests/test_mixed.py::test_features_neurite_map_sections[ipreorder-NeuriteType.axon-5]", "tests/test_mixed.py::test_features_neurite_map_sections[ipreorder-NeuriteType.basal_dendrite-4]", "tests/test_mixed.py::test_features_neurite_map_sections[ipreorder-NeuriteType.axon_carrying_dendrite-9]", "tests/test_mixed.py::test_features_neurite_map_sections[ibifurcation_point-NeuriteType.all-4]", "tests/test_mixed.py::test_features_neurite_map_sections[ibifurcation_point-NeuriteType.basal_dendrite-1]", "tests/test_mixed.py::test_features_neurite_map_sections[ibifurcation_point-NeuriteType.axon-2]", "tests/test_mixed.py::test_features_neurite_map_sections[ibifurcation_point-NeuriteType.axon_carrying_dendrite-4]", "tests/test_mixed.py::test_mixed__extract_stats__homogeneous", "tests/test_mixed.py::test_mixed__extract_stats__heterogeneous", "tests/test_mixed.py::test_population__population_features_wout_subtrees[sholl_frequency-kwargs0-expected0]", "tests/test_mixed.py::test_population__population_features_wout_subtrees[sholl_frequency-kwargs1-expected1]", "tests/test_mixed.py::test_population__population_features_wout_subtrees[sholl_frequency-kwargs2-expected2]", "tests/test_mixed.py::test_population__population_features_wout_subtrees[sholl_frequency-kwargs3-expected3]", "tests/test_mixed.py::test_population__population_features_wout_subtrees[sholl_frequency-kwargs4-expected4]", "tests/test_mixed.py::test_population__population_features_with_subtrees[sholl_frequency-kwargs0-expected0]", "tests/test_mixed.py::test_population__population_features_with_subtrees[sholl_frequency-kwargs1-expected1]", "tests/test_mixed.py::test_population__population_features_with_subtrees[sholl_frequency-kwargs2-expected2]", "tests/test_mixed.py::test_population__population_features_with_subtrees[sholl_frequency-kwargs3-expected3]", "tests/test_mixed.py::test_population__population_features_with_subtrees[sholl_frequency-kwargs4-expected4]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[soma_radius-kwargs0-0.5]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[soma_surface_area-kwargs1-3.141592653589793]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[soma_volume-kwargs2-0.5235987755982988]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections_per_neurite-kwargs3-expected3]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections_per_neurite-kwargs4-expected4]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections_per_neurite-kwargs5-expected5]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections_per_neurite-kwargs6-expected6]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections_per_neurite-kwargs7-expected7]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[max_radial_distance-kwargs8-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[max_radial_distance-kwargs9-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[max_radial_distance-kwargs10-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[max_radial_distance-kwargs11-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[max_radial_distance-kwargs12-0.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[max_radial_distance-kwargs13-0.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[max_radial_distance-kwargs14-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length_per_neurite-kwargs15-expected15]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length_per_neurite-kwargs16-expected16]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length_per_neurite-kwargs17-expected17]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length_per_neurite-kwargs18-expected18]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length_per_neurite-kwargs19-expected19]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area_per_neurite-kwargs20-expected20]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area_per_neurite-kwargs21-expected21]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area_per_neurite-kwargs22-expected22]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area_per_neurite-kwargs23-expected23]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area_per_neurite-kwargs24-expected24]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume_per_neurite-kwargs25-expected25]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume_per_neurite-kwargs26-expected26]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume_per_neurite-kwargs27-expected27]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume_per_neurite-kwargs28-expected28]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume_per_neurite-kwargs29-expected29]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_azimuths-kwargs30-expected30]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_azimuths-kwargs31-expected31]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_azimuths-kwargs32-expected32]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_azimuths-kwargs33-expected33]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_azimuths-kwargs34-expected34]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_elevations-kwargs35-expected35]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_elevations-kwargs36-expected36]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_elevations-kwargs37-expected37]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_elevations-kwargs38-expected38]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_elevations-kwargs39-expected39]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_vectors-kwargs40-expected40]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_vectors-kwargs41-expected41]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_vectors-kwargs42-expected42]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_vectors-kwargs43-expected43]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_vectors-kwargs44-expected44]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_angles-kwargs45-expected45]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_angles-kwargs46-expected46]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_angles-kwargs47-expected47]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_angles-kwargs48-expected48]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_angles_from_vector-kwargs49-expected49]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_angles_from_vector-kwargs50-expected50]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_angles_from_vector-kwargs51-expected51]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_angles_inter_types-kwargs52-expected52]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_radii-kwargs53-expected53]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_radii-kwargs54-expected54]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_radii-kwargs55-expected55]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_origin_radii-kwargs56-expected56]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_section_lengths-kwargs57-expected57]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_section_lengths-kwargs58-expected58]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_section_lengths-kwargs59-expected59]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[trunk_section_lengths-kwargs60-expected60]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_neurites-kwargs61-3]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_neurites-kwargs62-2]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_neurites-kwargs63-0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_neurites-kwargs64-1]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[neurite_volume_density-kwargs65-expected65]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[neurite_volume_density-kwargs66-expected66]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[neurite_volume_density-kwargs67-expected67]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[neurite_volume_density-kwargs68-expected68]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sholl_crossings-kwargs69-expected69]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sholl_crossings-kwargs70-expected70]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sholl_crossings-kwargs71-expected71]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sholl_crossings-kwargs72-expected72]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sholl_frequency-kwargs73-expected73]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sholl_frequency-kwargs74-expected74]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sholl_frequency-kwargs75-expected75]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sholl_frequency-kwargs76-expected76]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_width-kwargs77-6.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_width-kwargs78-6.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_width-kwargs79-0.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_width-kwargs80-1.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_height-kwargs81-7.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_height-kwargs82-4.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_height-kwargs83-0.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_height-kwargs84-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_depth-kwargs85-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_depth-kwargs86-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_depth-kwargs87-0.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_depth-kwargs88-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[volume_density-kwargs89-0.01570426]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[volume_density-kwargs90-0.02983588]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[volume_density-kwargs91-nan]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[volume_density-kwargs92-0.23561945]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[aspect_ratio-kwargs93-0.630311]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[aspect_ratio-kwargs94-0.305701]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[aspect_ratio-kwargs95-nan]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[aspect_ratio-kwargs96-0.5]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[circularity-kwargs97-0.739583]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[circularity-kwargs98-0.525588]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[circularity-kwargs99-nan]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[circularity-kwargs100-0.539012]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[shape_factor-kwargs101-0.40566]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[shape_factor-kwargs102-0.21111]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[shape_factor-kwargs103-nan]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[shape_factor-kwargs104-0.25]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[length_fraction_above_soma-kwargs105-0.567898]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[length_fraction_above_soma-kwargs106-0.74729]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_segments-kwargs107-19]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_segments-kwargs108-14]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_segments-kwargs109-0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_segments-kwargs110-5]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_leaves-kwargs111-11]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_leaves-kwargs112-8]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_leaves-kwargs113-0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_leaves-kwargs114-3]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length-kwargs115-20.828427]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length-kwargs116-15.828427]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length-kwargs117-0.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_length-kwargs118-5.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area-kwargs119-13.086887]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area-kwargs120-9.945294]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area-kwargs121-0.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_area-kwargs122-3.141593]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume-kwargs123-0.654344]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume-kwargs124-0.497265]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume-kwargs125-0.0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[total_volume-kwargs126-0.15708]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_lengths-kwargs127-expected127]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_lengths-kwargs128-expected128]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_lengths-kwargs129-expected129]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_lengths-kwargs130-expected130]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_areas-kwargs131-expected131]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_areas-kwargs132-expected132]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_areas-kwargs133-expected133]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_areas-kwargs134-expected134]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_volumes-kwargs135-expected135]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_volumes-kwargs136-expected136]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_volumes-kwargs137-expected137]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_volumes-kwargs138-expected138]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_tortuosity-kwargs139-expected139]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_tortuosity-kwargs140-expected140]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_tortuosity-kwargs141-expected141]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_tortuosity-kwargs142-expected142]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_radial_distances-kwargs143-expected143]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_radial_distances-kwargs144-expected144]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_radial_distances-kwargs145-expected145]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_radial_distances-kwargs146-expected146]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_radial_distances-kwargs147-expected147]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_radial_distances-kwargs148-expected148]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_radial_distances-kwargs149-expected149]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_radial_distances-kwargs150-expected150]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_radial_distances-kwargs151-expected151]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_radial_distances-kwargs152-expected152]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_radial_distances-kwargs153-expected153]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_radial_distances-kwargs154-expected154]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_radial_distances-kwargs155-expected155]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_end_distances-kwargs156-expected156]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_end_distances-kwargs157-expected157]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_end_distances-kwargs158-expected158]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_end_distances-kwargs159-expected159]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_lengths-kwargs160-expected160]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_lengths-kwargs161-expected161]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_lengths-kwargs162-expected162]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_lengths-kwargs163-expected163]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_taper_rates-kwargs164-expected164]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_taper_rates-kwargs165-expected165]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_taper_rates-kwargs166-expected166]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_taper_rates-kwargs167-expected167]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_lengths-kwargs168-expected168]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_lengths-kwargs169-expected169]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_lengths-kwargs170-expected170]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_lengths-kwargs171-expected171]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_lengths-kwargs172-expected172]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_branch_orders-kwargs173-expected173]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_branch_orders-kwargs174-expected174]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_branch_orders-kwargs175-expected175]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_branch_orders-kwargs176-expected176]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_branch_orders-kwargs177-expected177]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_branch_orders-kwargs178-expected178]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_branch_orders-kwargs179-expected179]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_bif_branch_orders-kwargs180-expected180]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_branch_orders-kwargs181-expected181]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_branch_orders-kwargs182-expected182]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_branch_orders-kwargs183-expected183]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_term_branch_orders-kwargs184-expected184]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_strahler_orders-kwargs185-expected185]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_strahler_orders-kwargs186-expected186]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_strahler_orders-kwargs187-expected187]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_strahler_orders-kwargs188-expected188]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_lengths-kwargs189-expected189]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_lengths-kwargs190-expected190]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_lengths-kwargs191-expected191]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_lengths-kwargs192-expected192]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_lengths-kwargs193-expected193]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_areas-kwargs194-expected194]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_areas-kwargs195-expected195]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_areas-kwargs196-expected196]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_areas-kwargs197-expected197]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_volumes-kwargs198-expected198]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_volumes-kwargs199-expected199]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_volumes-kwargs200-expected200]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_volumes-kwargs201-expected201]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_radii-kwargs202-expected202]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_radii-kwargs203-expected203]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_radii-kwargs204-expected204]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_radii-kwargs205-expected205]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_taper_rates-kwargs206-expected206]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_taper_rates-kwargs207-expected207]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_taper_rates-kwargs208-expected208]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_taper_rates-kwargs209-expected209]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_radial_distances-kwargs210-expected210]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_radial_distances-kwargs211-expected211]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_radial_distances-kwargs212-expected212]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_radial_distances-kwargs213-expected213]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_midpoints-kwargs214-expected214]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_midpoints-kwargs215-expected215]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_midpoints-kwargs216-expected216]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_midpoints-kwargs217-expected217]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_meander_angles-kwargs218-expected218]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_meander_angles-kwargs219-expected219]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_meander_angles-kwargs220-expected220]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_meander_angles-kwargs221-expected221]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections-kwargs222-19]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections-kwargs223-14]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections-kwargs224-0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections-kwargs225-5]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_sections-kwargs226-14]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_bifurcations-kwargs227-8]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_bifurcations-kwargs228-6]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_bifurcations-kwargs229-0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_bifurcations-kwargs230-2]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_bifurcations-kwargs231-6]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_forking_points-kwargs232-8]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_forking_points-kwargs233-6]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_forking_points-kwargs234-0]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_forking_points-kwargs235-2]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[number_of_forking_points-kwargs236-6]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[local_bifurcation_angles-kwargs237-expected237]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[local_bifurcation_angles-kwargs238-expected238]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[local_bifurcation_angles-kwargs239-expected239]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[local_bifurcation_angles-kwargs240-expected240]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[remote_bifurcation_angles-kwargs241-expected241]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[remote_bifurcation_angles-kwargs242-expected242]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[remote_bifurcation_angles-kwargs243-expected243]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[remote_bifurcation_angles-kwargs244-expected244]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[remote_bifurcation_angles-kwargs245-expected245]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sibling_ratios-kwargs246-expected246]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sibling_ratios-kwargs247-expected247]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sibling_ratios-kwargs248-expected248]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[sibling_ratios-kwargs249-expected249]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_pairs-kwargs250-expected250]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_pairs-kwargs251-expected251]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_pairs-kwargs252-expected252]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_pairs-kwargs253-expected253]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_pairs-kwargs254-expected254]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[diameter_power_relations-kwargs255-expected255]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[diameter_power_relations-kwargs256-expected256]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[diameter_power_relations-kwargs257-expected257]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[diameter_power_relations-kwargs258-expected258]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[bifurcation_partitions-kwargs259-expected259]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[bifurcation_partitions-kwargs260-expected260]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[bifurcation_partitions-kwargs261-expected261]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[bifurcation_partitions-kwargs262-expected262]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[bifurcation_partitions-kwargs263-expected263]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_path_distances-kwargs264-expected264]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_path_distances-kwargs265-expected265]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[section_path_distances-kwargs266-expected266]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[terminal_path_lengths-kwargs267-expected267]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[terminal_path_lengths-kwargs268-expected268]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[terminal_path_lengths-kwargs269-expected269]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[terminal_path_lengths-kwargs270-expected270]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[principal_direction_extents-kwargs271-expected271]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[principal_direction_extents-kwargs272-expected272]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[principal_direction_extents-kwargs273-expected273]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[principal_direction_extents-kwargs274-expected274]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry-kwargs275-expected275]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry-kwargs276-expected276]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry-kwargs277-expected277]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry-kwargs278-expected278]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry-kwargs279-expected279]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry-kwargs280-expected280]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry-kwargs281-expected281]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry-kwargs282-expected282]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry_length-kwargs283-expected283]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry_length-kwargs284-expected284]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry_length-kwargs285-expected285]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[partition_asymmetry_length-kwargs286-expected286]", "tests/test_mixed.py::test_morphology__morphology_features_wout_subtrees[segment_path_lengths-kwargs287-expected287]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[soma_radius-kwargs0-0.5]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[soma_surface_area-kwargs1-3.141592653589793]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[soma_volume-kwargs2-0.5235987755982988]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections_per_neurite-kwargs3-expected3]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections_per_neurite-kwargs4-expected4]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections_per_neurite-kwargs5-expected5]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections_per_neurite-kwargs6-expected6]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections_per_neurite-kwargs7-expected7]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[max_radial_distance-kwargs8-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[max_radial_distance-kwargs9-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[max_radial_distance-kwargs10-4.24264]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[max_radial_distance-kwargs11-4.242641]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[max_radial_distance-kwargs12-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[max_radial_distance-kwargs13-4.47213595499958]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[max_radial_distance-kwargs14-4.472136]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length_per_neurite-kwargs15-expected15]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length_per_neurite-kwargs16-expected16]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length_per_neurite-kwargs17-expected17]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length_per_neurite-kwargs18-expected18]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length_per_neurite-kwargs19-expected19]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area_per_neurite-kwargs20-expected20]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area_per_neurite-kwargs21-expected21]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area_per_neurite-kwargs22-expected22]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area_per_neurite-kwargs23-expected23]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area_per_neurite-kwargs24-expected24]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume_per_neurite-kwargs25-expected25]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume_per_neurite-kwargs26-expected26]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume_per_neurite-kwargs27-expected27]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume_per_neurite-kwargs28-expected28]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume_per_neurite-kwargs29-expected29]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_azimuths-kwargs30-expected30]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_azimuths-kwargs31-expected31]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_azimuths-kwargs32-expected32]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_azimuths-kwargs33-expected33]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_azimuths-kwargs34-expected34]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_elevations-kwargs35-expected35]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_elevations-kwargs36-expected36]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_elevations-kwargs37-expected37]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_elevations-kwargs38-expected38]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_elevations-kwargs39-expected39]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_vectors-kwargs40-expected40]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_vectors-kwargs41-expected41]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_vectors-kwargs42-expected42]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_vectors-kwargs43-expected43]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_vectors-kwargs44-expected44]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_angles-kwargs45-expected45]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_angles-kwargs46-expected46]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_angles-kwargs47-expected47]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_angles-kwargs48-expected48]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_angles_from_vector-kwargs49-expected49]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_angles_from_vector-kwargs50-expected50]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_angles_from_vector-kwargs51-expected51]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_angles_inter_types-kwargs52-expected52]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_radii-kwargs53-expected53]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_radii-kwargs54-expected54]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_radii-kwargs55-expected55]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_origin_radii-kwargs56-expected56]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_section_lengths-kwargs57-expected57]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_section_lengths-kwargs58-expected58]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_section_lengths-kwargs59-expected59]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[trunk_section_lengths-kwargs60-expected60]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_neurites-kwargs61-3]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_neurites-kwargs62-2]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_neurites-kwargs63-1]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_neurites-kwargs64-1]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[neurite_volume_density-kwargs65-expected65]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[neurite_volume_density-kwargs66-expected66]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[neurite_volume_density-kwargs67-expected67]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[neurite_volume_density-kwargs68-expected68]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sholl_crossings-kwargs69-expected69]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sholl_crossings-kwargs70-expected70]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sholl_crossings-kwargs71-expected71]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sholl_crossings-kwargs72-expected72]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sholl_frequency-kwargs73-expected73]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sholl_frequency-kwargs74-expected74]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sholl_frequency-kwargs75-expected75]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sholl_frequency-kwargs76-expected76]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_width-kwargs77-6.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_width-kwargs78-4.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_width-kwargs79-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_width-kwargs80-1.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_height-kwargs81-7.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_height-kwargs82-4.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_height-kwargs83-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_height-kwargs84-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_depth-kwargs85-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_depth-kwargs86-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_depth-kwargs87-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_depth-kwargs88-2.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[volume_density-kwargs89-0.01570426]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[volume_density-kwargs90-0.04907583]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[volume_density-kwargs91-0.17009254]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[volume_density-kwargs92-0.23561945]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[aspect_ratio-kwargs93-0.630311]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[aspect_ratio-kwargs94-0.284467]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[aspect_ratio-kwargs95-0.666667]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[aspect_ratio-kwargs96-0.5]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[circularity-kwargs97-0.739583]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[circularity-kwargs98-0.483687]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[circularity-kwargs99-0.544013]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[circularity-kwargs100-0.539012]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[shape_factor-kwargs101-0.40566]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[shape_factor-kwargs102-0.1875]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[shape_factor-kwargs103-0.3]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[shape_factor-kwargs104-0.25]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[length_fraction_above_soma-kwargs105-0.567898]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[length_fraction_above_soma-kwargs106-0.61591]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_segments-kwargs107-19]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_segments-kwargs108-9]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_segments-kwargs109-5]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_segments-kwargs110-5]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_leaves-kwargs111-11]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_leaves-kwargs112-5]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_leaves-kwargs113-3]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_leaves-kwargs114-3]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length-kwargs115-20.828427]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length-kwargs116-10.414214]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length-kwargs117-5.414214]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_length-kwargs118-5.0]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area-kwargs119-13.086887]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area-kwargs120-6.543443]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area-kwargs121-3.401851]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_area-kwargs122-3.141593]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume-kwargs123-0.654344]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume-kwargs124-0.327172]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume-kwargs125-0.170093]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[total_volume-kwargs126-0.15708]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_lengths-kwargs127-expected127]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_lengths-kwargs128-expected128]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_lengths-kwargs129-expected129]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_lengths-kwargs130-expected130]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_areas-kwargs131-expected131]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_areas-kwargs132-expected132]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_areas-kwargs133-expected133]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_areas-kwargs134-expected134]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_volumes-kwargs135-expected135]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_volumes-kwargs136-expected136]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_volumes-kwargs137-expected137]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_volumes-kwargs138-expected138]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_tortuosity-kwargs139-expected139]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_tortuosity-kwargs140-expected140]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_tortuosity-kwargs141-expected141]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_tortuosity-kwargs142-expected142]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_radial_distances-kwargs143-expected143]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_radial_distances-kwargs144-expected144]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_radial_distances-kwargs145-expected145]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_radial_distances-kwargs146-expected146]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_radial_distances-kwargs147-expected147]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_radial_distances-kwargs148-expected148]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_radial_distances-kwargs149-expected149]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_radial_distances-kwargs150-expected150]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_radial_distances-kwargs151-expected151]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_radial_distances-kwargs152-expected152]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_radial_distances-kwargs153-expected153]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_radial_distances-kwargs154-expected154]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_radial_distances-kwargs155-expected155]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_end_distances-kwargs156-expected156]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_end_distances-kwargs157-expected157]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_end_distances-kwargs158-expected158]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_end_distances-kwargs159-expected159]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_lengths-kwargs160-expected160]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_lengths-kwargs161-expected161]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_lengths-kwargs162-expected162]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_lengths-kwargs163-expected163]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_taper_rates-kwargs164-expected164]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_taper_rates-kwargs165-expected165]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_taper_rates-kwargs166-expected166]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_taper_rates-kwargs167-expected167]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_lengths-kwargs168-expected168]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_lengths-kwargs169-expected169]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_lengths-kwargs170-expected170]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_lengths-kwargs171-expected171]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_lengths-kwargs172-expected172]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_branch_orders-kwargs173-expected173]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_branch_orders-kwargs174-expected174]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_branch_orders-kwargs175-expected175]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_branch_orders-kwargs176-expected176]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_branch_orders-kwargs177-expected177]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_branch_orders-kwargs178-expected178]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_branch_orders-kwargs179-expected179]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_bif_branch_orders-kwargs180-expected180]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_branch_orders-kwargs181-expected181]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_branch_orders-kwargs182-expected182]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_branch_orders-kwargs183-expected183]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_term_branch_orders-kwargs184-expected184]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_strahler_orders-kwargs185-expected185]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_strahler_orders-kwargs186-expected186]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_strahler_orders-kwargs187-expected187]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_strahler_orders-kwargs188-expected188]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_lengths-kwargs189-expected189]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_lengths-kwargs190-expected190]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_lengths-kwargs191-expected191]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_lengths-kwargs192-expected192]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_lengths-kwargs193-expected193]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_areas-kwargs194-expected194]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_areas-kwargs195-expected195]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_areas-kwargs196-expected196]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_areas-kwargs197-expected197]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_volumes-kwargs198-expected198]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_volumes-kwargs199-expected199]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_volumes-kwargs200-expected200]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_volumes-kwargs201-expected201]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_radii-kwargs202-expected202]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_radii-kwargs203-expected203]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_radii-kwargs204-expected204]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_radii-kwargs205-expected205]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_taper_rates-kwargs206-expected206]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_taper_rates-kwargs207-expected207]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_taper_rates-kwargs208-expected208]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_taper_rates-kwargs209-expected209]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_radial_distances-kwargs210-expected210]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_radial_distances-kwargs211-expected211]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_radial_distances-kwargs212-expected212]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_radial_distances-kwargs213-expected213]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_midpoints-kwargs214-expected214]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_midpoints-kwargs215-expected215]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_midpoints-kwargs216-expected216]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_midpoints-kwargs217-expected217]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_meander_angles-kwargs218-expected218]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_meander_angles-kwargs219-expected219]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_meander_angles-kwargs220-expected220]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_meander_angles-kwargs221-expected221]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections-kwargs222-19]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections-kwargs223-9]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections-kwargs224-5]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections-kwargs225-5]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_sections-kwargs226-14]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_bifurcations-kwargs227-8]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_bifurcations-kwargs228-3]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_bifurcations-kwargs229-2]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_bifurcations-kwargs230-2]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_bifurcations-kwargs231-6]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_forking_points-kwargs232-8]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_forking_points-kwargs233-3]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_forking_points-kwargs234-2]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_forking_points-kwargs235-2]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[number_of_forking_points-kwargs236-6]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[local_bifurcation_angles-kwargs237-expected237]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[local_bifurcation_angles-kwargs238-expected238]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[local_bifurcation_angles-kwargs239-expected239]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[local_bifurcation_angles-kwargs240-expected240]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[remote_bifurcation_angles-kwargs241-expected241]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[remote_bifurcation_angles-kwargs242-expected242]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[remote_bifurcation_angles-kwargs243-expected243]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[remote_bifurcation_angles-kwargs244-expected244]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[remote_bifurcation_angles-kwargs245-expected245]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sibling_ratios-kwargs246-expected246]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sibling_ratios-kwargs247-expected247]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sibling_ratios-kwargs248-expected248]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[sibling_ratios-kwargs249-expected249]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_pairs-kwargs250-expected250]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_pairs-kwargs251-expected251]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_pairs-kwargs252-expected252]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_pairs-kwargs253-expected253]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_pairs-kwargs254-expected254]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[diameter_power_relations-kwargs255-expected255]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[diameter_power_relations-kwargs256-expected256]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[diameter_power_relations-kwargs257-expected257]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[diameter_power_relations-kwargs258-expected258]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[bifurcation_partitions-kwargs259-expected259]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[bifurcation_partitions-kwargs260-expected260]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[bifurcation_partitions-kwargs261-expected261]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[bifurcation_partitions-kwargs262-expected262]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[bifurcation_partitions-kwargs263-expected263]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_path_distances-kwargs264-expected264]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_path_distances-kwargs265-expected265]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[section_path_distances-kwargs266-expected266]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[terminal_path_lengths-kwargs267-expected267]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[terminal_path_lengths-kwargs268-expected268]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[terminal_path_lengths-kwargs269-expected269]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[terminal_path_lengths-kwargs270-expected270]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[principal_direction_extents-kwargs271-expected271]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[principal_direction_extents-kwargs272-expected272]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[principal_direction_extents-kwargs273-expected273]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[principal_direction_extents-kwargs274-expected274]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry-kwargs275-expected275]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry-kwargs276-expected276]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry-kwargs277-expected277]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry-kwargs278-expected278]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry-kwargs279-expected279]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry-kwargs280-expected280]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry-kwargs281-expected281]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry-kwargs282-expected282]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry_length-kwargs283-expected283]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry_length-kwargs284-expected284]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry_length-kwargs285-expected285]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[partition_asymmetry_length-kwargs286-expected286]", "tests/test_mixed.py::test_morphology__morphology_features_with_subtrees[segment_path_lengths-kwargs287-expected287]", "tests/test_mixed.py::test_morphology__neurite_features[max_radial_distance-kwargs0-expected0]", "tests/test_mixed.py::test_morphology__neurite_features[max_radial_distance-kwargs1-expected1]", "tests/test_mixed.py::test_morphology__neurite_features[max_radial_distance-kwargs2-expected2]", "tests/test_mixed.py::test_morphology__neurite_features[max_radial_distance-kwargs3-expected3]", "tests/test_mixed.py::test_morphology__neurite_features[max_radial_distance-kwargs4-expected4]", "tests/test_mixed.py::test_morphology__neurite_features[max_radial_distance-kwargs5-expected5]", "tests/test_mixed.py::test_morphology__neurite_features[volume_density-kwargs6-expected6]", "tests/test_mixed.py::test_morphology__neurite_features[volume_density-kwargs7-expected7]", "tests/test_mixed.py::test_morphology__neurite_features[volume_density-kwargs8-expected8]", "tests/test_mixed.py::test_morphology__neurite_features[volume_density-kwargs9-expected9]", "tests/test_mixed.py::test_morphology__neurite_features[section_radial_distances-kwargs10-expected10]", "tests/test_mixed.py::test_morphology__neurite_features[section_radial_distances-kwargs11-expected11]", "tests/test_mixed.py::test_morphology__neurite_features[section_radial_distances-kwargs12-expected12]", "tests/test_mixed.py::test_morphology__neurite_features[section_radial_distances-kwargs13-expected13]", "tests/test_mixed.py::test_morphology__neurite_features[section_bif_radial_distances-kwargs14-expected14]", "tests/test_mixed.py::test_morphology__neurite_features[section_bif_radial_distances-kwargs15-expected15]", "tests/test_mixed.py::test_morphology__neurite_features[section_bif_radial_distances-kwargs16-expected16]", "tests/test_mixed.py::test_morphology__neurite_features[section_bif_radial_distances-kwargs17-expected17]", "tests/test_mixed.py::test_morphology__neurite_features[section_term_radial_distances-kwargs18-expected18]", "tests/test_mixed.py::test_morphology__neurite_features[section_term_radial_distances-kwargs19-expected19]", "tests/test_mixed.py::test_morphology__neurite_features[section_term_radial_distances-kwargs20-expected20]", "tests/test_mixed.py::test_morphology__neurite_features[section_term_radial_distances-kwargs21-expected21]", "tests/test_mixed.py::test_morphology__neurite_features[segment_radial_distances-kwargs22-expected22]", "tests/test_mixed.py::test_morphology__neurite_features[segment_radial_distances-kwargs23-expected23]", "tests/test_mixed.py::test_morphology__neurite_features[segment_radial_distances-kwargs24-expected24]", "tests/test_mixed.py::test_morphology__neurite_features[segment_radial_distances-kwargs25-expected25]", "tests/test_mixed.py::test_sholl_crossings", "tests/test_mixed.py::test_sholl_frequency", "tests/test_mixed.py::test_sholl_frequency_pop" ]
[]
BSD 3-Clause "New" or "Revised" License
18,555
201
[ "neurom/core/morphology.py" ]
celery__kombu-2016
eae75855e06887250399f793018f97cbd398c90b
2024-05-31 11:41:27
e32f8fc39b3135eca2aa9d70a92e35c1c94b9406
diff --git a/kombu/mixins.py b/kombu/mixins.py index 14c1c1b9..92acee98 100644 --- a/kombu/mixins.py +++ b/kombu/mixins.py @@ -195,10 +195,11 @@ class ConsumerMixin: try: conn.drain_events(timeout=safety_interval) except socket.timeout: - conn.heartbeat_check() - elapsed += safety_interval - if timeout and elapsed >= timeout: - raise + if timeout: + conn.heartbeat_check() + elapsed += safety_interval + if elapsed >= timeout: + raise except OSError: if not self.should_stop: raise
ConsumerMixin consume method should not heartbeat if timeout None <!-- Please fill this template entirely and do not erase parts of it. We reserve the right to close without a response enhancement requests which are incomplete. --> # Checklist <!-- To check an item on the list replace [ ] with [x]. --> - [x] I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Enhancement%22+-label%3A%22Category%3A+Documentation%22) for similar or identical enhancement to an existing feature. - [x] I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22Issue+Type%3A+Enhancement%22+-label%3A%22Category%3A+Documentation%22) for existing proposed enhancements. - [x] I have checked the [commit log](https://github.com/celery/celery/commits/main) to find out if the same enhancement was already implemented in the main branch. - [x] I have included all related issues and possible duplicate issues in this issue (If there are none, check this box anyway). ## Related Issues and Possible Duplicates <!-- Please make sure to search and mention any related issues or possible duplicates to this issue as requested by the checklist above. This may or may not include issues in other repositories that the Celery project maintains or other repositories that are dependencies of Celery. If you don't know how to mention issues, please refer to Github's documentation on the subject: https://help.github.com/en/articles/autolinked-references-and-urls#issues-and-pull-requests --> #### Related Issues - None #### Possible Duplicates - None # Brief Summary the capture method in celery events Receiver. logs broker heartbeats on socket exceptions. this is a helpful feature sometimes but there's no way to disable it as it mostly clutters the terminal with unhelpful messages most of the time which prevents the user from seeing actual task event logs. ![image](https://github.com/celery/celery/assets/36680382/bf6fdf37-9ca6-4aa4-a6f7-2ca80b82d574) # Design ## Architectural Considerations <!-- If more components other than Celery are involved, describe them here and the effect it would have on Celery. --> None ## Proposed Behavior If the timeout argument is None that should disable broker heartbeat_check ![image](https://github.com/celery/celery/assets/36680382/8d633b1b-89d6-414b-9be8-11dad7fafee1) ## Proposed UI/UX <!-- Please provide your ideas for the API, CLI options, configuration key names etc. that will be adjusted for this enhancement. --> ## Diagrams <!-- Please include any diagrams that might be relevant to the implementation of this enhancement such as: * Class Diagrams * Sequence Diagrams * Activity Diagrams You can drag and drop images into the text box to attach them to this issue. --> N/A ## Alternatives <!-- If you have considered any alternative implementations describe them in detail below. --> None
celery/kombu
diff --git a/t/unit/test_mixins.py b/t/unit/test_mixins.py index 7a96091e..a33412eb 100644 --- a/t/unit/test_mixins.py +++ b/t/unit/test_mixins.py @@ -89,6 +89,26 @@ class test_ConsumerMixin: c.connection.drain_events.side_effect = se with pytest.raises(socket.error): next(it) + c.connection.heartbeat_check.assert_called() + + def test_consume_drain_no_heartbeat_check(self): + c, Acons, Bcons = self._context() + c.should_stop = False + it = c.consume(no_ack=True, timeout=None) + + def se(*args, **kwargs): + c.should_stop = True + raise socket.timeout() + c.connection.drain_events.side_effect = se + with pytest.raises(StopIteration): + next(it) + c.connection.heartbeat_check.assert_not_called() + + it = c.consume(no_ack=True, timeout=0) + c.connection.drain_events.side_effect = se + with pytest.raises(StopIteration): + next(it) + c.connection.heartbeat_check.assert_not_called() def test_Consumer_context(self): c, Acons, Bcons = self._context()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
5.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/default.txt", "requirements/dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
amqp @ https://github.com/celery/py-amqp/zipball/main#sha256=bc618e1a51e852a457ee5aca2a8d1b46440d1304ca23f50d250d2fc216e3e499 certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup==1.2.2 execnet==2.1.1 idna==3.10 iniconfig==2.1.0 -e git+https://github.com/celery/kombu.git@eae75855e06887250399f793018f97cbd398c90b#egg=kombu packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 requests==2.31.0 tomli==2.2.1 typing_extensions==4.13.0 urllib3==2.3.0 vine @ https://github.com/celery/vine/zipball/master#sha256=955be2b59aaf8e6b68540d03a5af8dc493f6ef3dacbdcc977907f9909e6c866e
name: kombu channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - amqp==5.3.1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - requests==2.31.0 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 - vine==5.1.0 prefix: /opt/conda/envs/kombu
[ "t/unit/test_mixins.py::test_ConsumerMixin::test_consume_drain_no_heartbeat_check" ]
[]
[ "t/unit/test_mixins.py::test_ConsumerMixin::test_consume", "t/unit/test_mixins.py::test_ConsumerMixin::test_consume_drain_raises_socket_error", "t/unit/test_mixins.py::test_ConsumerMixin::test_consume_drain_raises_socket_timeout", "t/unit/test_mixins.py::test_ConsumerMixin::test_Consumer_context", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_get_consumers", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_on_connection_revived", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_on_consume_ready", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_on_consume_end", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_on_iteration", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_on_decode_error", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_on_connection_error", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_extra_context", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_restart_limit", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_connection_errors", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test__consume_from", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_establish_connection", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_maybe_conn_error", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_run", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_run_restart_rate_limited", "t/unit/test_mixins.py::test_ConsumerMixin_interface::test_run_raises" ]
[]
BSD 3-Clause "New" or "Revised" License
18,562
174
[ "kombu/mixins.py" ]
pyvista__pyvista-6170
ebed4e8e0ed6b0af882c5d75a9d164846c8589f7
2024-05-31 19:09:23
b5d7a8114b128b5890c0e116fcf985d800fca950
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/pyvista/pyvista/pull/6170?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pyvista) Report Attention: Patch coverage is `80.00000%` with `2 lines` in your changes are missing coverage. Please review. > Project coverage is 90.97%. Comparing base [(`f61ecf2`)](https://app.codecov.io/gh/pyvista/pyvista/commit/f61ecf212e88a0fc276b7ba208024777d2bdaec7?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pyvista) to head [(`aa06fa3`)](https://app.codecov.io/gh/pyvista/pyvista/commit/aa06fa381e8954196a8d30c756b89f44a530e167?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pyvista). <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #6170 +/- ## ========================================== - Coverage 97.08% 90.97% -6.12% ========================================== Files 141 141 Lines 25935 25944 +9 ========================================== - Hits 25180 23603 -1577 - Misses 755 2341 +1586 ``` </details> user27182: LGTM. The ImageNoiseSource test is no longer failing.
diff --git a/pyvista/core/_vtk_core.py b/pyvista/core/_vtk_core.py index 3101ea7c..d986dd12 100644 --- a/pyvista/core/_vtk_core.py +++ b/pyvista/core/_vtk_core.py @@ -90,6 +90,7 @@ from vtkmodules.vtkCommonCore import vtkIdList from vtkmodules.vtkCommonCore import vtkIdTypeArray from vtkmodules.vtkCommonCore import vtkLogger from vtkmodules.vtkCommonCore import vtkLookupTable +from vtkmodules.vtkCommonCore import vtkMath from vtkmodules.vtkCommonCore import vtkOutputWindow from vtkmodules.vtkCommonCore import vtkPoints from vtkmodules.vtkCommonCore import vtkSignedCharArray diff --git a/pyvista/core/utilities/image_sources.py b/pyvista/core/utilities/image_sources.py index db842ca7..86a35f89 100644 --- a/pyvista/core/utilities/image_sources.py +++ b/pyvista/core/utilities/image_sources.py @@ -222,7 +222,7 @@ class ImageMandelbrotSource(_vtk.vtkImageMandelbrotSource): @no_new_attr class ImageNoiseSource(_vtk.vtkImageNoiseSource): - """Create a binary image of an ellipsoid class. + """Create an image filled with uniform noise. .. versionadded:: 0.44.0 @@ -237,6 +237,9 @@ class ImageNoiseSource(_vtk.vtkImageNoiseSource): maximum : float The maximum value for the generated noise. + seed : int, optional + Seed the random number generator with a value. + Examples -------- Create an image of noise. @@ -246,13 +249,20 @@ class ImageNoiseSource(_vtk.vtkImageNoiseSource): ... whole_extent=(0, 200, 0, 200, 0, 0), ... minimum=0, ... maximum=255, + ... seed=0, ... ) >>> source.output.plot(cpos="xy") """ _new_attr_exceptions: ClassVar[List[str]] = ['_whole_extent', 'whole_extent'] - def __init__(self, whole_extent=None, minimum=None, maximum=None) -> None: + def __init__( + self, + whole_extent=(0, 255, 0, 255, 0, 0), + minimum=0.0, + maximum=1.0, + seed=None, + ) -> None: super().__init__() if whole_extent is not None: self.whole_extent = whole_extent @@ -260,6 +270,8 @@ class ImageNoiseSource(_vtk.vtkImageNoiseSource): self.minimum = minimum if maximum is not None: self.maximum = maximum + if seed is not None: + self.seed(seed) @property def whole_extent(self) -> Sequence[int]: @@ -328,6 +340,16 @@ class ImageNoiseSource(_vtk.vtkImageNoiseSource): """ self.SetMaximum(maximum) + def seed(self, value: int) -> None: + """Seed the random number generator with a value. + + Parameters + ---------- + value : int + The seed value for the random number generator to use. + """ + _vtk.vtkMath().RandomSeed(value) + @property def output(self): """Get the output image as a ImageData.
Fix failing doc image tests ### Describe the bug, what's wrong, and what you expected. ### Overview Issue to track and investigate failing tests with the documentation images. The failing tests are initially reported in https://github.com/pyvista/pyvista/pull/5712, see the build failure [here](https://github.com/pyvista/pyvista/actions/runs/9278295702). ### Image Diff Here's a diff of 54 failing test images: https://github.com/pyvista/pyvista/compare/main...user27182:doc/failed_images There appears to be two main categories of failed tests: 1. failures from random numbers, i.e. examples that were not captured as part of #6106 but should have been, and 2. failures with MPLCharts, see #6141 ### Software Report Diff Here's a diff between the Software Report from the successful build in https://github.com/pyvista/pyvista/pull/5718 (when the build images in the `doc_image_cache` were first generated) and the failed build linked above: https://www.diffchecker.com/WGONBfLU/ From this diff it doesn't appear as though updates to any packages is the cause of the failures. ### Steps to reproduce the bug. n/a ### System Information ```shell n/a ``` ### Screenshots _No response_
pyvista/pyvista
diff --git a/tests/core/test_image_sources.py b/tests/core/test_image_sources.py index 53e04a60..ef1657f5 100644 --- a/tests/core/test_image_sources.py +++ b/tests/core/test_image_sources.py @@ -1,5 +1,7 @@ from __future__ import annotations +import numpy as np + import pyvista as pv @@ -25,8 +27,10 @@ def test_image_ellip_soid_source(): def test_image_noise_source(): whole_extent = (-10, 10, -10, 10, -10, 10) - source = pv.ImageNoiseSource(whole_extent=whole_extent, minimum=0, maximum=255) + source = pv.ImageNoiseSource(whole_extent=whole_extent, minimum=0, maximum=255, seed=42) assert source.whole_extent == whole_extent + assert source.minimum == 0 + assert source.maximum == 255 whole_extent = (-5, 5, -5, 5, -5, 5) minimum = 100 maximum = 200 @@ -38,6 +42,17 @@ def test_image_noise_source(): assert source.maximum == maximum assert isinstance(source.output, pv.ImageData) + output = pv.ImageNoiseSource().output + assert output.bounds == (0.0, 255.0, 0.0, 255.0, 0.0, 0.0) + assert output.dimensions == (256, 256, 1) + assert np.allclose(output.get_data_range(), (0.0, 1.0), atol=1e-4) + + output_seed = pv.ImageNoiseSource(seed=0).output + assert not np.array_equal(output_seed.active_scalars, output.active_scalars) + + output_same_seed = pv.ImageNoiseSource(seed=0).output + assert np.array_equal(output_same_seed.active_scalars, output_seed.active_scalars) + def test_image_mandelbrot_source(): whole_extent = (0, 20, 0, 20, 0, 0)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
0.43
{ "env_vars": null, "env_yml_path": [ "environment.yml" ], "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "environment.yml", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist" ], "pre_install": [ "apt-get update", "apt-get install -y libosmesa6-dev libgl1-mesa-dev python3-tk pandoc git-restore-mtime" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiohappyeyeballs @ file:///home/conda/feedstock_root/build_artifacts/aiohappyeyeballs_1741775197943/work aiohttp @ file:///home/conda/feedstock_root/build_artifacts/aiohttp_1742268596946/work aiosignal @ file:///home/conda/feedstock_root/build_artifacts/aiosignal_1734342155601/work anyio @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_anyio_1742243108/work argon2-cffi @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi_1733311059102/work argon2-cffi-bindings @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi-bindings_1725356560642/work arrow @ file:///home/conda/feedstock_root/build_artifacts/arrow_1733584251875/work asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1733250440834/work async-lru @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_async-lru_1742153708/work async-timeout @ file:///home/conda/feedstock_root/build_artifacts/async-timeout_1733235340728/work attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1741918516150/work babel @ file:///home/conda/feedstock_root/build_artifacts/babel_1738490167835/work beautifulsoup4 @ file:///home/conda/feedstock_root/build_artifacts/beautifulsoup4_1738740337718/work bleach @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_bleach_1737382993/work Brotli @ file:///home/conda/feedstock_root/build_artifacts/brotli-split_1725267488082/work cached-property @ file:///home/conda/feedstock_root/build_artifacts/cached_property_1615209429212/work certifi @ file:///home/conda/feedstock_root/build_artifacts/certifi_1739515848642/work/certifi cffi @ file:///home/conda/feedstock_root/build_artifacts/cffi_1725571112467/work cftime @ file:///home/conda/feedstock_root/build_artifacts/cftime_1725400455427/work charset-normalizer @ file:///home/conda/feedstock_root/build_artifacts/charset-normalizer_1735929714516/work click @ file:///home/conda/feedstock_root/build_artifacts/click_1734858813237/work cmocean @ file:///home/conda/feedstock_root/build_artifacts/cmocean_1734343940570/work codecov @ file:///home/conda/feedstock_root/build_artifacts/codecov_1734975286850/work colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1733218098505/work colorcet @ file:///home/conda/feedstock_root/build_artifacts/colorcet_1734007314889/work colorspacious @ file:///home/conda/feedstock_root/build_artifacts/colorspacious_1734341944815/work comm @ file:///home/conda/feedstock_root/build_artifacts/comm_1733502965406/work contourpy @ file:///home/conda/feedstock_root/build_artifacts/contourpy_1727293517607/work coverage @ file:///home/conda/feedstock_root/build_artifacts/coverage_1743381224823/work cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1733332471406/work debugpy @ file:///home/conda/feedstock_root/build_artifacts/debugpy_1741148409996/work decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1740384970518/work defusedxml @ file:///home/conda/feedstock_root/build_artifacts/defusedxml_1615232257335/work exceptiongroup @ file:///home/conda/feedstock_root/build_artifacts/exceptiongroup_1733208806608/work execnet @ file:///home/conda/feedstock_root/build_artifacts/execnet_1733230988954/work executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1733569351617/work fastjsonschema @ file:///home/conda/feedstock_root/build_artifacts/python-fastjsonschema_1733235979760/work/dist fonttools @ file:///home/conda/feedstock_root/build_artifacts/fonttools_1738940303262/work fqdn @ file:///home/conda/feedstock_root/build_artifacts/fqdn_1733327382592/work/dist frozenlist @ file:///home/conda/feedstock_root/build_artifacts/frozenlist_1737645236190/work h11 @ file:///home/conda/feedstock_root/build_artifacts/h11_1733327467879/work h2 @ file:///home/conda/feedstock_root/build_artifacts/h2_1738578511449/work h5py @ file:///home/conda/feedstock_root/build_artifacts/h5py_1739952287730/work hpack @ file:///home/conda/feedstock_root/build_artifacts/hpack_1737618293087/work httpcore @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_httpcore_1731707562/work httpx @ file:///home/conda/feedstock_root/build_artifacts/httpx_1733663348460/work hyperframe @ file:///home/conda/feedstock_root/build_artifacts/hyperframe_1737618333194/work hypothesis @ file:///home/conda/feedstock_root/build_artifacts/hypothesis_1742900877539/work idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1733211830134/work imageio @ file:///home/conda/feedstock_root/build_artifacts/imageio_1738273805233/work imageio-ffmpeg @ file:///home/conda/feedstock_root/build_artifacts/imageio-ffmpeg_1737102630951/work importlib_metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1737420181517/work importlib_resources @ file:///home/conda/feedstock_root/build_artifacts/importlib_resources_1736252299705/work iniconfig @ file:///home/conda/feedstock_root/build_artifacts/iniconfig_1733223141826/work ipykernel @ file:///home/conda/feedstock_root/build_artifacts/ipykernel_1719845459717/work ipython @ file:///home/conda/feedstock_root/build_artifacts/ipython_1701831663892/work ipywidgets==8.1.5 isoduration @ file:///home/conda/feedstock_root/build_artifacts/isoduration_1733493628631/work/dist jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1733300866624/work Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1741263328855/work json5 @ file:///home/conda/feedstock_root/build_artifacts/json5_1733272076743/work jsonpointer @ file:///home/conda/feedstock_root/build_artifacts/jsonpointer_1725302957584/work jsonschema @ file:///home/conda/feedstock_root/build_artifacts/jsonschema_1733472696581/work jsonschema-specifications @ file:///tmp/tmpk0f344m9/src jupyter-events @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_jupyter_events_1738765986/work jupyter-lsp @ file:///home/conda/feedstock_root/build_artifacts/jupyter-lsp-meta_1733492907176/work/jupyter-lsp jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1733440914442/work jupyter_core @ file:///home/conda/feedstock_root/build_artifacts/jupyter_core_1727163409502/work jupyter_server @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_1734702637701/work jupyter_server_proxy==4.4.0 jupyter_server_terminals @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_terminals_1733427956852/work jupyterlab @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_1741964057182/work jupyterlab_pygments @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_pygments_1733328101776/work jupyterlab_server @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_server_1733599573484/work jupyterlab_widgets==3.0.13 kiwisolver @ file:///home/conda/feedstock_root/build_artifacts/kiwisolver_1725459266648/work loguru @ file:///home/conda/feedstock_root/build_artifacts/loguru_1725349754278/work markdown-it-py @ file:///home/conda/feedstock_root/build_artifacts/markdown-it-py_1733250460757/work MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1733219680183/work matplotlib==3.9.4 matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1733416936468/work mdurl @ file:///home/conda/feedstock_root/build_artifacts/mdurl_1733255585584/work meshio @ file:///home/conda/feedstock_root/build_artifacts/meshio_1706720595231/work mistune @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_mistune_1742402716/work more-itertools @ file:///home/conda/feedstock_root/build_artifacts/more-itertools_1736883817510/work msgpack @ file:///home/conda/feedstock_root/build_artifacts/msgpack-python_1725975012026/work multidict @ file:///home/conda/feedstock_root/build_artifacts/multidict_1742308123521/work munkres==1.1.4 nbclient @ file:///home/conda/feedstock_root/build_artifacts/nbclient_1734628800805/work nbconvert @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_nbconvert-core_1738067871/work nbformat @ file:///home/conda/feedstock_root/build_artifacts/nbformat_1733402752141/work nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1733325553580/work netCDF4 @ file:///home/conda/feedstock_root/build_artifacts/netcdf4_1733253338730/work notebook_shim @ file:///home/conda/feedstock_root/build_artifacts/notebook-shim_1733408315203/work numpy @ file:///home/conda/feedstock_root/build_artifacts/numpy_1707225342954/work/dist/numpy-1.26.4-cp39-cp39-linux_x86_64.whl#sha256=c799942b5898f6e6c60264d1663a6469a475290e758c654aeeb78e2596463abd overrides @ file:///home/conda/feedstock_root/build_artifacts/overrides_1734587627321/work packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1733203243479/work pandocfilters @ file:///home/conda/feedstock_root/build_artifacts/pandocfilters_1631603243851/work parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1733271261340/work pexpect @ file:///home/conda/feedstock_root/build_artifacts/pexpect_1733301927746/work pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1733327343728/work pillow @ file:///home/conda/feedstock_root/build_artifacts/pillow_1735929703139/work pkgutil_resolve_name @ file:///home/conda/feedstock_root/build_artifacts/pkgutil-resolve-name_1733344503739/work platformdirs @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_platformdirs_1742485085/work pluggy @ file:///home/conda/feedstock_root/build_artifacts/pluggy_1733222765875/work pooch @ file:///home/conda/feedstock_root/build_artifacts/pooch_1733421311631/work prometheus_client @ file:///home/conda/feedstock_root/build_artifacts/prometheus_client_1733327310477/work prompt_toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1737453357274/work propcache @ file:///home/conda/feedstock_root/build_artifacts/propcache_1737635528546/work psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1740663125313/work ptyprocess @ file:///home/conda/feedstock_root/build_artifacts/ptyprocess_1733302279685/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl#sha256=92c32ff62b5fd8cf325bec5ab90d7be3d2a8ca8c8a3813ff487a8d2002630d1f pure_eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1733569405015/work pycparser @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_pycparser_1733195786/work pyembree @ file:///home/conda/feedstock_root/build_artifacts/pyembree_1718702851992/work Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1736243443484/work pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1743089729650/work PySide6==6.8.3 PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1733217236728/work pytest @ file:///home/conda/feedstock_root/build_artifacts/pytest_1740946542080/work pytest-cov @ file:///home/conda/feedstock_root/build_artifacts/pytest-cov_1733223023082/work pytest-memprof==0.2.0 pytest-xdist @ file:///home/conda/feedstock_root/build_artifacts/pytest-xdist_1733240780199/work python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1733215673016/work python-json-logger @ file:///home/conda/feedstock_root/build_artifacts/python-json-logger_1677079630776/work pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1742920838005/work -e git+https://github.com/pyvista/pyvista.git@ebed4e8e0ed6b0af882c5d75a9d164846c8589f7#egg=pyvista PyYAML @ file:///home/conda/feedstock_root/build_artifacts/pyyaml_1737454647378/work pyzmq @ file:///home/conda/feedstock_root/build_artifacts/pyzmq_1741805177758/work referencing @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_referencing_1737836872/work requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1733217035951/work rfc3339_validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3339-validator_1733599910982/work rfc3986-validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3986-validator_1598024191506/work rich @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rich_1743371105/work/dist rpds-py @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rpds-py_1743037693/work rtree @ file:///home/conda/feedstock_root/build_artifacts/rtree_1741378561624/work scooby @ file:///home/conda/feedstock_root/build_artifacts/scooby_1734299019922/work Send2Trash @ file:///home/conda/feedstock_root/build_artifacts/send2trash_1733322040660/work shiboken6==6.8.3 simpervisor==1.0.0 six @ file:///home/conda/feedstock_root/build_artifacts/six_1733380938961/work sniffio @ file:///home/conda/feedstock_root/build_artifacts/sniffio_1733244044561/work sortedcontainers @ file:///home/conda/feedstock_root/build_artifacts/sortedcontainers_1738440353519/work soupsieve @ file:///home/conda/feedstock_root/build_artifacts/soupsieve_1693929250441/work stack_data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1733569443808/work terminado @ file:///home/conda/feedstock_root/build_artifacts/terminado_1710262609923/work tinycss2 @ file:///home/conda/feedstock_root/build_artifacts/tinycss2_1729802851396/work toml @ file:///home/conda/feedstock_root/build_artifacts/toml_1734091811753/work tomli @ file:///home/conda/feedstock_root/build_artifacts/tomli_1733256695513/work tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1732615921868/work tqdm @ file:///home/conda/feedstock_root/build_artifacts/tqdm_1735661334605/work traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1733367359838/work trame @ file:///home/conda/feedstock_root/build_artifacts/trame_1741413642518/work trame-client @ file:///home/conda/feedstock_root/build_artifacts/trame-client_1742874331306/work trame-server @ file:///home/conda/feedstock_root/build_artifacts/trame-server_1741638011360/work trame-vtk @ file:///home/conda/feedstock_root/build_artifacts/trame-vtk_1739145199105/work trame-vuetify @ file:///home/conda/feedstock_root/build_artifacts/trame-vuetify_1743263303319/work trimesh @ file:///home/conda/feedstock_root/build_artifacts/trimesh_1743289679380/work types-python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/types-python-dateutil_1733612335562/work typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_typing_extensions_1743201626/work typing_utils @ file:///home/conda/feedstock_root/build_artifacts/typing_utils_1733331286120/work unicodedata2 @ file:///home/conda/feedstock_root/build_artifacts/unicodedata2_1736692503055/work uri-template @ file:///home/conda/feedstock_root/build_artifacts/uri-template_1733323593477/work/dist urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1734859416348/work vtk==9.3.1 wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1733231326287/work webcolors @ file:///home/conda/feedstock_root/build_artifacts/webcolors_1733359735138/work webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1733236011802/work websocket-client @ file:///home/conda/feedstock_root/build_artifacts/websocket-client_1733157342724/work widgetsnbextension==4.0.13 wslink @ file:///home/conda/feedstock_root/build_artifacts/wslink_1742768409749/work yarl @ file:///home/conda/feedstock_root/build_artifacts/yarl_1737575777699/work zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1732827521216/work zstandard==0.23.0
name: pyvista channels: - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=conda_forge - _openmp_mutex=4.5=2_gnu - aiohappyeyeballs=2.6.1=pyhd8ed1ab_0 - aiohttp=3.11.14=py39h9399b63_0 - aiosignal=1.3.2=pyhd8ed1ab_0 - alsa-lib=1.2.13=hb9d3cd8_0 - anyio=4.9.0=pyh29332c3_0 - aom=3.9.1=hac33072_0 - argon2-cffi=23.1.0=pyhd8ed1ab_1 - argon2-cffi-bindings=21.2.0=py39h8cd3c5a_5 - arrow=1.3.0=pyhd8ed1ab_1 - asttokens=3.0.0=pyhd8ed1ab_1 - async-lru=2.0.5=pyh29332c3_0 - async-timeout=5.0.1=pyhd8ed1ab_1 - attr=2.5.1=h166bdaf_1 - attrs=25.3.0=pyh71513ae_0 - babel=2.17.0=pyhd8ed1ab_0 - beautifulsoup4=4.13.3=pyha770c72_0 - bleach=6.2.0=pyh29332c3_4 - bleach-with-css=6.2.0=h82add2a_4 - blosc=1.21.6=he440d0b_1 - brotli=1.1.0=hb9d3cd8_2 - brotli-bin=1.1.0=hb9d3cd8_2 - brotli-python=1.1.0=py39hf88036b_2 - bzip2=1.0.8=h4bc722e_7 - c-ares=1.34.4=hb9d3cd8_0 - ca-certificates=2025.1.31=hbcca054_0 - cached-property=1.5.2=hd8ed1ab_1 - cached_property=1.5.2=pyha770c72_1 - cairo=1.18.4=h3394656_0 - certifi=2025.1.31=pyhd8ed1ab_0 - cffi=1.17.1=py39h15c3d72_0 - cftime=1.6.4=py39hf3d9206_1 - charset-normalizer=3.4.1=pyhd8ed1ab_0 - click=8.1.8=pyh707e725_0 - cmocean=4.0.3=pyhd8ed1ab_1 - codecov=2.1.13=pyhd8ed1ab_1 - colorama=0.4.6=pyhd8ed1ab_1 - colorcet=3.1.0=pyhd8ed1ab_1 - colorspacious=1.1.2=pyhecae5ae_1 - comm=0.2.2=pyhd8ed1ab_1 - contourpy=1.3.0=py39h74842e3_2 - coverage=7.8.0=py39h9399b63_0 - cycler=0.12.1=pyhd8ed1ab_1 - cyrus-sasl=2.1.27=h54b06d7_7 - dav1d=1.2.1=hd590300_0 - dbus=1.13.6=h5008d03_3 - debugpy=1.8.13=py39hf88036b_0 - decorator=5.2.1=pyhd8ed1ab_0 - defusedxml=0.7.1=pyhd8ed1ab_0 - double-conversion=3.3.1=h5888daf_0 - embree=2.17.7=ha770c72_3 - exceptiongroup=1.2.2=pyhd8ed1ab_1 - execnet=2.1.1=pyhd8ed1ab_1 - executing=2.1.0=pyhd8ed1ab_1 - expat=2.6.4=h5888daf_0 - ffmpeg=7.1.1=gpl_h0b79d52_704 - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 - font-ttf-inconsolata=3.000=h77eed37_0 - font-ttf-source-code-pro=2.038=h77eed37_0 - font-ttf-ubuntu=0.83=h77eed37_3 - fontconfig=2.15.0=h7e30c49_1 - fonts-conda-ecosystem=1=0 - fonts-conda-forge=1=0 - fonttools=4.56.0=py39h9399b63_0 - fqdn=1.5.1=pyhd8ed1ab_1 - freetype=2.13.3=h48d6fc4_0 - fribidi=1.0.10=h36c2ea0_0 - frozenlist=1.5.0=py39h9399b63_1 - gdk-pixbuf=2.42.12=hb9ae30d_0 - gettext=0.23.1=h5888daf_0 - gettext-tools=0.23.1=h5888daf_0 - gl2ps=1.4.2=hae5d5c5_1 - glew=2.1.0=h9c3ff4c_2 - gmp=6.3.0=hac33072_2 - graphite2=1.3.13=h59595ed_1003 - h11=0.14.0=pyhd8ed1ab_1 - h2=4.2.0=pyhd8ed1ab_0 - h5py=3.13.0=nompi_py39h30a5a8d_100 - harfbuzz=11.0.0=h76408a6_0 - hdf4=4.2.15=h2a13503_7 - hdf5=1.14.3=nompi_h2d575fe_109 - hpack=4.1.0=pyhd8ed1ab_0 - httpcore=1.0.7=pyh29332c3_1 - httpx=0.28.1=pyhd8ed1ab_0 - hyperframe=6.1.0=pyhd8ed1ab_0 - hypothesis=6.130.4=pyha770c72_0 - icu=75.1=he02047a_0 - idna=3.10=pyhd8ed1ab_1 - imageio=2.37.0=pyhfb79c49_0 - imageio-ffmpeg=0.6.0=pyhd8ed1ab_0 - importlib-metadata=8.6.1=pyha770c72_0 - importlib-resources=6.5.2=pyhd8ed1ab_0 - importlib_metadata=8.6.1=hd8ed1ab_0 - importlib_resources=6.5.2=pyhd8ed1ab_0 - iniconfig=2.0.0=pyhd8ed1ab_1 - ipykernel=6.29.5=pyh3099207_0 - ipython=8.18.1=pyh707e725_3 - isoduration=20.11.0=pyhd8ed1ab_1 - jack=1.9.22=h7c63dc7_2 - jedi=0.19.2=pyhd8ed1ab_1 - jinja2=3.1.6=pyhd8ed1ab_0 - json5=0.10.0=pyhd8ed1ab_1 - jsoncpp=1.9.6=hf42df4d_1 - jsonpointer=3.0.0=py39hf3d152e_1 - jsonschema=4.23.0=pyhd8ed1ab_1 - jsonschema-specifications=2024.10.1=pyhd8ed1ab_1 - jsonschema-with-format-nongpl=4.23.0=hd8ed1ab_1 - jupyter-lsp=2.2.5=pyhd8ed1ab_1 - jupyter_client=8.6.3=pyhd8ed1ab_1 - jupyter_core=5.7.2=pyh31011fe_1 - jupyter_events=0.12.0=pyh29332c3_0 - jupyter_server=2.15.0=pyhd8ed1ab_0 - jupyter_server_terminals=0.5.3=pyhd8ed1ab_1 - jupyterlab=4.3.6=pyhd8ed1ab_0 - jupyterlab_pygments=0.3.0=pyhd8ed1ab_2 - jupyterlab_server=2.27.3=pyhd8ed1ab_1 - keyutils=1.6.1=h166bdaf_0 - kiwisolver=1.4.7=py39h74842e3_0 - krb5=1.21.3=h659f571_0 - lame=3.100=h166bdaf_1003 - lcms2=2.17=h717163a_0 - ld_impl_linux-64=2.43=h712a8e2_4 - lerc=4.0.0=h27087fc_0 - level-zero=1.21.6=h84d6215_0 - libabseil=20250127.1=cxx17_hbbce691_0 - libaec=1.1.3=h59595ed_0 - libasprintf=0.23.1=h8e693c7_0 - libasprintf-devel=0.23.1=h8e693c7_0 - libass=0.17.3=h52826cd_2 - libblas=3.9.0=31_h59b9bed_openblas - libbrotlicommon=1.1.0=hb9d3cd8_2 - libbrotlidec=1.1.0=hb9d3cd8_2 - libbrotlienc=1.1.0=hb9d3cd8_2 - libcap=2.75=h39aace5_0 - libcblas=3.9.0=31_he106b2a_openblas - libclang-cpp20.1=20.1.1=default_hb5137d0_0 - libclang13=20.1.1=default_h9c6a7e4_0 - libcups=2.3.3=h4637d8d_4 - libcurl=8.12.1=h332b0f4_0 - libdb=6.2.32=h9c3ff4c_0 - libdeflate=1.23=h4ddbbb0_0 - libdrm=2.4.124=hb9d3cd8_0 - libedit=3.1.20250104=pl5321h7949ede_0 - libegl=1.7.0=ha4b6fd6_2 - libev=4.33=hd590300_2 - libexpat=2.6.4=h5888daf_0 - libffi=3.4.6=h2dba641_0 - libflac=1.4.3=h59595ed_0 - libgcc=14.2.0=h767d61c_2 - libgcc-ng=14.2.0=h69a702a_2 - libgcrypt-lib=1.11.0=hb9d3cd8_2 - libgettextpo=0.23.1=h5888daf_0 - libgettextpo-devel=0.23.1=h5888daf_0 - libgfortran=14.2.0=h69a702a_2 - libgfortran5=14.2.0=hf1ad2bd_2 - libgl=1.7.0=ha4b6fd6_2 - libglib=2.84.0=h2ff4ddf_0 - libglu=9.0.3=h03adeef_0 - libglvnd=1.7.0=ha4b6fd6_2 - libglx=1.7.0=ha4b6fd6_2 - libgomp=14.2.0=h767d61c_2 - libgpg-error=1.51=hbd13f7d_1 - libhwloc=2.11.2=default_h0d58e46_1001 - libiconv=1.18=h4ce23a2_1 - libjpeg-turbo=3.0.0=hd590300_1 - liblapack=3.9.0=31_h7ac8fdf_openblas - libllvm20=20.1.1=ha7bfdaf_0 - liblzma=5.6.4=hb9d3cd8_0 - libnetcdf=4.9.2=nompi_h00e09a9_116 - libnghttp2=1.64.0=h161d5f1_0 - libnsl=2.0.1=hd590300_0 - libntlm=1.8=hb9d3cd8_0 - libogg=1.3.5=h4ab18f5_0 - libopenblas=0.3.29=pthreads_h94d23a6_0 - libopengl=1.7.0=ha4b6fd6_2 - libopenvino=2025.0.0=hdc3f47d_3 - libopenvino-auto-batch-plugin=2025.0.0=h4d9b6c2_3 - libopenvino-auto-plugin=2025.0.0=h4d9b6c2_3 - libopenvino-hetero-plugin=2025.0.0=h981d57b_3 - libopenvino-intel-cpu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-intel-gpu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-intel-npu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-ir-frontend=2025.0.0=h981d57b_3 - libopenvino-onnx-frontend=2025.0.0=h0e684df_3 - libopenvino-paddle-frontend=2025.0.0=h0e684df_3 - libopenvino-pytorch-frontend=2025.0.0=h5888daf_3 - libopenvino-tensorflow-frontend=2025.0.0=h684f15b_3 - libopenvino-tensorflow-lite-frontend=2025.0.0=h5888daf_3 - libopus=1.3.1=h7f98852_1 - libpciaccess=0.18=hd590300_0 - libpng=1.6.47=h943b412_0 - libpq=17.4=h27ae623_0 - libprotobuf=5.29.3=h501fc15_0 - librsvg=2.58.4=he92a37e_3 - libsndfile=1.2.2=hc60ed4a_1 - libsodium=1.0.20=h4ab18f5_0 - libspatialindex=2.1.0=he57a185_0 - libsqlite=3.49.1=hee588c1_2 - libssh2=1.11.1=hf672d98_0 - libstdcxx=14.2.0=h8f9b012_2 - libstdcxx-ng=14.2.0=h4852527_2 - libsystemd0=257.4=h4e0b6ca_1 - libtheora=1.1.1=h4ab18f5_1006 - libtiff=4.7.0=hd9ff511_3 - libudev1=257.4=hbe16f8c_1 - libunwind=1.6.2=h9c3ff4c_0 - liburing=2.9=h84d6215_0 - libusb=1.0.28=hb9d3cd8_0 - libuuid=2.38.1=h0b41bf4_0 - libva=2.22.0=h4f16b4b_2 - libvorbis=1.3.7=h9c3ff4c_0 - libvpx=1.14.1=hac33072_0 - libwebp-base=1.5.0=h851e524_0 - libxcb=1.17.0=h8a09558_0 - libxcrypt=4.4.36=hd590300_1 - libxkbcommon=1.8.1=hc4a0caf_0 - libxml2=2.13.7=h8d12d68_0 - libxslt=1.1.39=h76b75d6_0 - libzip=1.11.2=h6991a6a_0 - libzlib=1.3.1=hb9d3cd8_2 - loguru=0.7.2=py39hf3d152e_2 - lz4-c=1.10.0=h5888daf_1 - markdown-it-py=3.0.0=pyhd8ed1ab_1 - markupsafe=3.0.2=py39h9399b63_1 - matplotlib=3.9.4=py39hf3d152e_0 - matplotlib-base=3.9.4=py39h16632d1_0 - matplotlib-inline=0.1.7=pyhd8ed1ab_1 - mdurl=0.1.2=pyhd8ed1ab_1 - meshio=5.3.5=pyhd8ed1ab_0 - mistune=3.1.3=pyh29332c3_0 - more-itertools=10.6.0=pyhd8ed1ab_0 - mpg123=1.32.9=hc50e24c_0 - msgpack-python=1.1.0=py39h74842e3_0 - multidict=6.2.0=py39h9399b63_0 - munkres=1.1.4=pyh9f0ad1d_0 - mysql-common=9.0.1=h266115a_5 - mysql-libs=9.0.1=he0572af_5 - nbclient=0.10.2=pyhd8ed1ab_0 - nbconvert-core=7.16.6=pyh29332c3_0 - nbformat=5.10.4=pyhd8ed1ab_1 - ncurses=6.5=h2d0b736_3 - nest-asyncio=1.6.0=pyhd8ed1ab_1 - netcdf4=1.7.2=nompi_py39h9d02bfe_101 - nlohmann_json=3.11.3=he02047a_1 - notebook-shim=0.2.4=pyhd8ed1ab_1 - numpy=1.26.4=py39h474f0d3_0 - ocl-icd=2.3.2=hb9d3cd8_2 - opencl-headers=2024.10.24=h5888daf_0 - openh264=2.6.0=hc22cd8d_0 - openjpeg=2.5.3=h5fbd93e_0 - openldap=2.6.9=he970967_0 - openssl=3.4.1=h7b32b05_0 - overrides=7.7.0=pyhd8ed1ab_1 - packaging=24.2=pyhd8ed1ab_2 - pandocfilters=1.5.0=pyhd8ed1ab_0 - pango=1.56.3=h9ac818e_1 - parso=0.8.4=pyhd8ed1ab_1 - pcre2=10.44=hba22ea6_2 - pexpect=4.9.0=pyhd8ed1ab_1 - pickleshare=0.7.5=pyhd8ed1ab_1004 - pillow=11.1.0=py39h15c0740_0 - pip=25.0.1=pyh8b19718_0 - pixman=0.44.2=h29eaf8c_0 - pkgutil-resolve-name=1.3.10=pyhd8ed1ab_2 - platformdirs=4.3.7=pyh29332c3_0 - pluggy=1.5.0=pyhd8ed1ab_1 - pooch=1.8.2=pyhd8ed1ab_1 - proj=9.5.1=h0054346_0 - prometheus_client=0.21.1=pyhd8ed1ab_0 - prompt-toolkit=3.0.50=pyha770c72_0 - propcache=0.2.1=py39h9399b63_1 - psutil=7.0.0=py39h8cd3c5a_0 - pthread-stubs=0.4=hb9d3cd8_1002 - ptyprocess=0.7.0=pyhd8ed1ab_1 - pugixml=1.15=h3f63f65_0 - pulseaudio-client=17.0=hac146a9_1 - pure_eval=0.2.3=pyhd8ed1ab_1 - pycparser=2.22=pyh29332c3_1 - pyembree=0.1.6=py39hddac248_4 - pygments=2.19.1=pyhd8ed1ab_0 - pyparsing=3.2.3=pyhd8ed1ab_1 - pyside6=6.8.3=py39h0383914_0 - pysocks=1.7.1=pyha55dd90_7 - pytest=8.3.5=pyhd8ed1ab_0 - pytest-cov=6.0.0=pyhd8ed1ab_1 - pytest-xdist=3.6.1=pyhd8ed1ab_1 - python=3.9.21=h9c0c6dc_1_cpython - python-dateutil=2.9.0.post0=pyhff2d567_1 - python-fastjsonschema=2.21.1=pyhd8ed1ab_0 - python-json-logger=2.0.7=pyhd8ed1ab_0 - python_abi=3.9=5_cp39 - pytz=2025.2=pyhd8ed1ab_0 - pyyaml=6.0.2=py39h9399b63_2 - pyzmq=26.3.0=py39h4e4fb57_0 - qhull=2020.2=h434a139_5 - qt6-main=6.8.3=h6441bc3_1 - readline=8.2=h8c095d6_2 - referencing=0.36.2=pyh29332c3_0 - requests=2.32.3=pyhd8ed1ab_1 - rfc3339-validator=0.1.4=pyhd8ed1ab_1 - rfc3986-validator=0.1.1=pyh9f0ad1d_0 - rich=14.0.0=pyh29332c3_0 - rpds-py=0.24.0=py39h3506688_0 - rtree=1.4.0=pyh11ca60a_1 - scooby=0.10.0=pyhd8ed1ab_1 - sdl2=2.32.50=h9b8e6db_1 - sdl3=3.2.8=h3083f51_0 - send2trash=1.8.3=pyh0d859eb_1 - setuptools=75.8.2=pyhff2d567_0 - six=1.17.0=pyhd8ed1ab_0 - snappy=1.2.1=h8bd8927_1 - sniffio=1.3.1=pyhd8ed1ab_1 - sortedcontainers=2.4.0=pyhd8ed1ab_1 - soupsieve=2.5=pyhd8ed1ab_1 - sqlite=3.49.1=h9eae976_2 - stack_data=0.6.3=pyhd8ed1ab_1 - svt-av1=3.0.2=h5888daf_0 - tbb=2022.0.0=hceb3a55_0 - terminado=0.18.1=pyh0d859eb_0 - tinycss2=1.4.0=pyhd8ed1ab_0 - tk=8.6.13=noxft_h4845f30_101 - toml=0.10.2=pyhd8ed1ab_1 - tomli=2.2.1=pyhd8ed1ab_1 - tornado=6.4.2=py39h8cd3c5a_0 - tqdm=4.67.1=pyhd8ed1ab_1 - traitlets=5.14.3=pyhd8ed1ab_1 - trame=3.8.1=pyhd8ed1ab_0 - trame-client=3.6.1=pyhd8ed1ab_0 - trame-server=3.4.0=pyhd8ed1ab_0 - trame-vtk=2.8.15=pyhb419c8b_0 - trame-vuetify=2.9.0=pyhd8ed1ab_0 - trimesh=4.6.6=pyh7b2049a_0 - types-python-dateutil=2.9.0.20241206=pyhd8ed1ab_0 - typing-extensions=4.13.0=h9fa5a19_1 - typing_extensions=4.13.0=pyh29332c3_1 - typing_utils=0.1.0=pyhd8ed1ab_1 - tzdata=2025b=h78e105d_0 - unicodedata2=16.0.0=py39h8cd3c5a_0 - uri-template=1.3.0=pyhd8ed1ab_1 - urllib3=2.3.0=pyhd8ed1ab_0 - utfcpp=4.0.6=h005c6e1_0 - vtk=9.3.1=qt_py39h71fb23e_216 - vtk-base=9.3.1=qt_py39habd23de_216 - vtk-io-ffmpeg=9.3.1=qt_py39h71fb23e_216 - wayland=1.23.1=h3e06ad9_0 - wayland-protocols=1.42=hd8ed1ab_0 - wcwidth=0.2.13=pyhd8ed1ab_1 - webcolors=24.11.1=pyhd8ed1ab_0 - webencodings=0.5.1=pyhd8ed1ab_3 - websocket-client=1.8.0=pyhd8ed1ab_1 - wheel=0.45.1=pyhd8ed1ab_1 - wslink=2.3.3=pyhd8ed1ab_0 - x264=1!164.3095=h166bdaf_2 - x265=3.5=h924138e_3 - xcb-util=0.4.1=hb711507_2 - xcb-util-cursor=0.1.5=hb9d3cd8_0 - xcb-util-image=0.4.0=hb711507_2 - xcb-util-keysyms=0.4.1=hb711507_0 - xcb-util-renderutil=0.3.10=hb711507_0 - xcb-util-wm=0.4.2=hb711507_0 - xkeyboard-config=2.43=hb9d3cd8_0 - xorg-libice=1.1.2=hb9d3cd8_0 - xorg-libsm=1.2.6=he73a12e_0 - xorg-libx11=1.8.12=h4f16b4b_0 - xorg-libxau=1.0.12=hb9d3cd8_0 - xorg-libxcomposite=0.4.6=hb9d3cd8_2 - xorg-libxcursor=1.2.3=hb9d3cd8_0 - xorg-libxdamage=1.1.6=hb9d3cd8_0 - xorg-libxdmcp=1.1.5=hb9d3cd8_0 - xorg-libxext=1.3.6=hb9d3cd8_0 - xorg-libxfixes=6.0.1=hb9d3cd8_0 - xorg-libxi=1.8.2=hb9d3cd8_0 - xorg-libxrandr=1.5.4=hb9d3cd8_0 - xorg-libxrender=0.9.12=hb9d3cd8_0 - xorg-libxscrnsaver=1.2.4=hb9d3cd8_0 - xorg-libxt=1.3.1=hb9d3cd8_0 - xorg-libxtst=1.2.5=hb9d3cd8_3 - xorg-libxxf86vm=1.1.6=hb9d3cd8_0 - yaml=0.2.5=h7f98852_2 - yarl=1.18.3=py39h9399b63_1 - zeromq=4.3.5=h3b0a872_7 - zipp=3.21.0=pyhd8ed1ab_1 - zlib=1.3.1=hb9d3cd8_2 - zstandard=0.23.0=py39h8cd3c5a_1 - zstd=1.5.7=hb8e6e7a_2 - pip: - ipywidgets==8.1.5 - jupyter-server-proxy==4.4.0 - jupyterlab-widgets==3.0.13 - pytest-memprof==0.2.0 - pyvista==0.44.dev0 - simpervisor==1.0.0 - widgetsnbextension==4.0.13 prefix: /opt/conda/envs/pyvista
[ "tests/core/test_image_sources.py::test_image_noise_source" ]
[]
[ "tests/core/test_image_sources.py::test_image_ellip_soid_source", "tests/core/test_image_sources.py::test_image_mandelbrot_source", "tests/core/test_image_sources.py::test_image_gradient_source", "tests/core/test_image_sources.py::test_image_sinusolid_source" ]
[]
MIT License
18,565
831
[ "pyvista/core/_vtk_core.py", "pyvista/core/utilities/image_sources.py" ]
lincc-frameworks__nested-pandas-102
82fe541fd7b56c7b37ede4cff9be84da8820a757
2024-05-31 21:33:56
975fbc88de84b6d8d9ae309f71ae3f0b96831818
diff --git a/src/nested_pandas/__init__.py b/src/nested_pandas/__init__.py index f1a0430..c19ba67 100644 --- a/src/nested_pandas/__init__.py +++ b/src/nested_pandas/__init__.py @@ -1,3 +1,4 @@ +from ._version import __version__ # noqa from .nestedframe import NestedFrame from .nestedframe.io import read_parquet @@ -5,4 +6,5 @@ from .nestedframe.io import read_parquet from .series.accessor import NestSeriesAccessor # noqa: F401 from .series.dtype import NestedDtype + __all__ = ["NestedDtype", "NestedFrame", "read_parquet"]
Add `__version__` We should add the ability to see the package version.
lincc-frameworks/nested-pandas
diff --git a/tests/nested_pandas/test_packaging.py b/tests/nested_pandas/test_packaging.py new file mode 100644 index 0000000..2e92c2d --- /dev/null +++ b/tests/nested_pandas/test_packaging.py @@ -0,0 +1,6 @@ +import nested_pandas + + +def test_version(): + """Check to see that the version property returns something""" + assert nested_pandas.__version__ is not None
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
accessible-pygments==0.0.5 alabaster==0.7.16 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 astroid==3.3.9 asttokens==3.0.0 asv==0.6.3 asv_runner==0.2.1 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 bleach==6.2.0 build==1.2.2.post1 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 comm==0.2.2 coverage==7.8.0 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fqdn==1.5.1 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 identify==2.6.9 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 jupytext==1.16.7 markdown-it-py==3.0.0 MarkupSafe==3.0.2 matplotlib-inline==0.1.7 mdit-py-plugins==0.4.2 mdurl==0.1.2 mistune==3.1.3 mypy==1.15.0 mypy-extensions==1.0.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbsphinx==0.9.7 nest-asyncio==1.6.0 -e git+https://github.com/lincc-frameworks/nested-pandas.git@82fe541fd7b56c7b37ede4cff9be84da8820a757#egg=nested_pandas nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pycparser==2.22 pydata-sphinx-theme==0.15.4 Pygments==2.19.1 Pympler==1.1 pyproject_hooks==1.2.0 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 ruff==0.11.2 Send2Trash==1.8.3 six==1.17.0 sniffio==1.3.1 snowballstemmer==2.2.0 soupsieve==2.6 Sphinx==7.4.7 sphinx-autoapi==3.6.0 sphinx-book-theme==1.1.4 sphinx-copybutton==0.5.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 stack-data==0.6.3 stdlib-list==0.11.1 tabulate==0.9.0 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 zipp==3.21.0
name: nested-pandas channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - accessible-pygments==0.0.5 - alabaster==0.7.16 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - astroid==3.3.9 - asttokens==3.0.0 - asv==0.6.3 - asv-runner==0.2.1 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - build==1.2.2.post1 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - comm==0.2.2 - coverage==7.8.0 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fqdn==1.5.1 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - jupytext==1.16.7 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - matplotlib-inline==0.1.7 - mdit-py-plugins==0.4.2 - mdurl==0.1.2 - mistune==3.1.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbsphinx==0.9.7 - nest-asyncio==1.6.0 - nested-pandas==0.1.1 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pycparser==2.22 - pydata-sphinx-theme==0.15.4 - pygments==2.19.1 - pympler==1.1 - pyproject-hooks==1.2.0 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - ruff==0.11.2 - send2trash==1.8.3 - six==1.17.0 - sniffio==1.3.1 - snowballstemmer==2.2.0 - soupsieve==2.6 - sphinx==7.4.7 - sphinx-autoapi==3.6.0 - sphinx-book-theme==1.1.4 - sphinx-copybutton==0.5.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - stack-data==0.6.3 - stdlib-list==0.11.1 - tabulate==0.9.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - zipp==3.21.0 prefix: /opt/conda/envs/nested-pandas
[ "tests/nested_pandas/test_packaging.py::test_version" ]
[]
[]
[]
MIT License
18,568
177
[ "src/nested_pandas/__init__.py" ]
streamlink__streamlink-6016
6f78ab12df402b801628b4fa1b2071b0a7a01bb2
2024-06-02 20:15:04
f41a3ffc9c1ceaac18e0a19d49223126cd25eb39
diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py index 32666d04..ac73b52e 100644 --- a/src/streamlink/plugins/twitch.py +++ b/src/streamlink/plugins/twitch.py @@ -71,6 +71,15 @@ class TwitchM3U8Parser(M3U8Parser[TwitchM3U8, TwitchHLSSegment, HLSPlaylist]): __m3u8__: ClassVar[Type[TwitchM3U8]] = TwitchM3U8 __segment__: ClassVar[Type[TwitchHLSSegment]] = TwitchHLSSegment + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._twitch_live_sequence: Optional[int] = None + + # additional metadata available on prefetch segments, indicating live content + @parse_tag("EXT-X-TWITCH-LIVE-SEQUENCE") + def parse_ext_x_twitch_live_sequence(self, value): + self._twitch_live_sequence = int(value) + @parse_tag("EXT-X-TWITCH-PREFETCH") def parse_tag_ext_x_twitch_prefetch(self, value): segments = self.m3u8.segments @@ -84,19 +93,23 @@ class TwitchM3U8Parser(M3U8Parser[TwitchM3U8, TwitchHLSSegment, HLSPlaylist]): # Use the last duration for extrapolating the start time of the prefetch segment, which is needed for checking # whether it is an ad segment and matches the parsed date ranges or not date = last.date + timedelta(seconds=last.duration) - # Always treat prefetch segments after a discontinuity as ad segments - ad = self._discontinuity or self._is_segment_ad(date) + ad = self._is_segment_ad(date) segment = dataclass_replace( last, uri=self.uri(value), duration=duration, title=None, + discontinuity=self._discontinuity and self._twitch_live_sequence is None, date=date, ad=ad, prefetch=True, ) segments.append(segment) + # Reset state + self._discontinuity = False + self._twitch_live_sequence = None + @parse_tag("EXT-X-DATERANGE") def parse_tag_ext_x_daterange(self, value): super().parse_tag_ext_x_daterange(value) @@ -108,6 +121,18 @@ class TwitchM3U8Parser(M3U8Parser[TwitchM3U8, TwitchHLSSegment, HLSPlaylist]): ad = self._is_segment_ad(self._date, self._extinf.title if self._extinf else None) segment: TwitchHLSSegment = super().get_segment(uri, ad=ad, prefetch=False) # type: ignore[assignment] + # Special case where Twitch incorrectly inserts discontinuity tags between segments of the live content + if ( + segment.discontinuity + and not segment.ad + and self.m3u8.segments + and not self.m3u8.segments[-1].ad + ): + segment.discontinuity = False + + # Reset state + self._twitch_live_sequence = None + return segment def _is_segment_ad(self, date: Optional[datetime], title: Optional[str] = None) -> bool:
plugins.twitch: incorrect discontinuity tags lead to warnings being spammed ### Checklist - [X] This is a [plugin issue](https://streamlink.github.io/plugins.html) and not [a different kind of issue](https://github.com/streamlink/streamlink/issues/new/choose) - [X] [I have read the contribution guidelines](https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink) - [X] [I have checked the list of open and recently closed plugin issues](https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22) - [X] [I have checked the commit log of the master branch](https://github.com/streamlink/streamlink/commits/master) ### Streamlink version streamlink 6.7.4 ### Description Recently, I've noticed constant warnings about stream discontinuities despite not seeing any actually happen. According to the verbose log the playlists seem to keep having the X-DISCONTINUITY tag in them even though I'm not getting served some sort of mid-roll or pre-roll due to having a subscription to the channel in question. I'm still receiving the live broadcast. There are also instances of repetitively getting this warning even after getting past the initial pre-roll in the event I don't have a subscription to a particular streamer. I'm not sure what's going on in the Twitch side of things, is this some attempt at trying to break streamlink usage again? The verbose log is too large for the issue report so I'm attaching it as a file: [streamlink.txt.gz](https://github.com/user-attachments/files/15524324/streamlink.txt.gz) ### Debug log ```text https://github.com/user-attachments/files/15524324/streamlink.txt.gz ```
streamlink/streamlink
diff --git a/tests/plugins/test_twitch.py b/tests/plugins/test_twitch.py index 89ea494f..1d2984a0 100644 --- a/tests/plugins/test_twitch.py +++ b/tests/plugins/test_twitch.py @@ -341,12 +341,12 @@ class TestTwitchHLSStream(TestMixinStreamHLS, unittest.TestCase): Seg, Pre = Segment, SegmentPrefetch ads = [ Tag("EXT-X-DISCONTINUITY"), - TagDateRangeAd(start=DATETIME_BASE + timedelta(seconds=3), duration=4), + TagDateRangeAd(start=DATETIME_BASE + timedelta(seconds=2.5), duration=4), ] # noinspection PyTypeChecker segments = self.subject([ # regular stream data with prefetch segments - Playlist(0, [Seg(0), Seg(1, duration=0.5), Pre(2), Pre(3)]), + Playlist(0, [Seg(0), Seg(1, duration=0.5), Pre(2), *ads, Pre(3)]), # three prefetch segments, one regular (2) and two ads (3 and 4) Playlist(1, [Seg(1, duration=0.5), Pre(2), *ads, Pre(3), Pre(4)]), # all prefetch segments are gone once regular prefetch segments have shifted @@ -395,6 +395,33 @@ class TestTwitchHLSStream(TestMixinStreamHLS, unittest.TestCase): self.await_read(read_all=True) assert self.thread.reader.worker.playlist_reload_time == pytest.approx(23 / 3) + @patch("streamlink.stream.hls.hls.log") + def test_hls_incorrect_discontinuity(self, mock_log): + discontinuity = Tag("EXT-X-DISCONTINUITY") + self.subject([ + Playlist(0, [Segment(0), Segment(1), discontinuity, Segment(2), Segment(3)]), + Playlist(4, [Segment(4), discontinuity, Segment(5), Segment(6), Segment(7)], end=True), + ], streamoptions={"disable_ads": True, "low_latency": True}) + + self.await_write(6) + self.await_read(read_all=True) + assert mock_log.warning.mock_calls == [] + + @patch("streamlink.stream.hls.hls.log") + def test_hls_incorrect_discontinuity_prefetch(self, mock_log): + Seg, Pre = Segment, SegmentPrefetch + discontinuity = Tag("EXT-X-DISCONTINUITY") + tls = Tag("EXT-X-TWITCH-LIVE-SEQUENCE", 1234) # value is irrelevant + self.subject([ + Playlist(0, [Seg(0), Seg(1), discontinuity, tls, Pre(2), discontinuity, tls, Pre(3)]), + Playlist(1, [Seg(1), discontinuity, tls, Seg(2), discontinuity, tls, Pre(3), Pre(4)]), + Playlist(2, [Seg(2), discontinuity, tls, Seg(3), discontinuity, tls, Pre(4), Pre(5)], end=True), + ], streamoptions={"disable_ads": True, "low_latency": True}) + + self.await_write(4) + self.await_read(read_all=True) + assert mock_log.warning.mock_calls == [] + class TestTwitchAPIAccessToken: @pytest.fixture(autouse=True)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
6.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
async-generator==1.10 attrs==25.3.0 certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup==1.2.2 freezegun==1.5.1 h11==0.14.0 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 isodate==0.7.2 lxml==5.3.1 lxml-stubs==0.5.1 mypy==1.10.0 mypy-extensions==1.0.0 outcome==1.3.0.post0 packaging==24.2 pluggy==1.5.0 pycountry==24.6.1 pycryptodome==3.22.0 PySocks==1.7.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-trio==0.8.0 python-dateutil==2.9.0.post0 requests==2.32.3 requests-mock==1.12.1 ruff==0.4.5 six==1.17.0 sniffio==1.3.1 sortedcontainers==2.4.0 -e git+https://github.com/streamlink/streamlink.git@6f78ab12df402b801628b4fa1b2071b0a7a01bb2#egg=streamlink tomli==2.2.1 trio==0.29.0 trio-typing==0.10.0 trio-websocket==0.12.2 types-freezegun==1.1.10 types-requests==2.32.0.20250328 types-setuptools==78.1.0.20250329 types-urllib3==1.26.25.14 typing_extensions==4.13.0 urllib3==2.3.0 versioningit==3.1.2 websocket-client==1.8.0 wsproto==1.2.0 zipp==3.21.0
name: streamlink channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - async-generator==1.10 - attrs==25.3.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - exceptiongroup==1.2.2 - freezegun==1.5.1 - h11==0.14.0 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - isodate==0.7.2 - lxml==5.3.1 - lxml-stubs==0.5.1 - mypy==1.10.0 - mypy-extensions==1.0.0 - outcome==1.3.0.post0 - packaging==24.2 - pluggy==1.5.0 - pycountry==24.6.1 - pycryptodome==3.22.0 - pysocks==1.7.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-trio==0.8.0 - python-dateutil==2.9.0.post0 - requests==2.32.3 - requests-mock==1.12.1 - ruff==0.4.5 - six==1.17.0 - sniffio==1.3.1 - sortedcontainers==2.4.0 - streamlink==6.7.4+9.g6f78ab12 - tomli==2.2.1 - trio==0.29.0 - trio-typing==0.10.0 - trio-websocket==0.12.2 - types-freezegun==1.1.10 - types-requests==2.32.0.20250328 - types-setuptools==78.1.0.20250329 - types-urllib3==1.26.25.14 - typing-extensions==4.13.0 - urllib3==2.3.0 - versioningit==3.1.2 - websocket-client==1.8.0 - wsproto==1.2.0 - zipp==3.21.0 prefix: /opt/conda/envs/streamlink
[ "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_incorrect_discontinuity", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_low_latency_has_prefetch_disable_ads_no_preroll_with_prefetch_ads" ]
[]
[ "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_class_setup", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_class_name", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_all_matchers_match[#0]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_positive_unnamed[https://www.twitch.tv/twitch]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_positive_unnamed[https://www.twitch.tv/videos/150942279]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_positive_unnamed[https://clips.twitch.tv/ObservantBenevolentCarabeefPhilosoraptor]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_positive_unnamed[https://www.twitch.tv/weplaydota/clip/FurryIntelligentDonutAMPEnergyCherry-akPRxv7Y3w58WmFq]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_positive_unnamed[https://www.twitch.tv/twitch/video/292713971]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_positive_unnamed[https://www.twitch.tv/twitch/v/292713971]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_groups_unnamed[URL=https://www.twitch.tv/twitch", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_groups_unnamed[URL=https://www.twitch.tv/videos/150942279", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_groups_unnamed[URL=https://clips.twitch.tv/ObservantBenevolentCarabeefPhilosoraptor", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_groups_unnamed[URL=https://www.twitch.tv/weplaydota/clip/FurryIntelligentDonutAMPEnergyCherry-akPRxv7Y3w58WmFq", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_groups_unnamed[URL=https://www.twitch.tv/twitch/video/292713971", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_groups_unnamed[URL=https://www.twitch.tv/twitch/v/292713971", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_negative[https://www.twitch.tv]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_negative[https://www.twitch.tv/]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_negative[http://example.com/]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_negative[https://example.com/]", "tests/plugins/test_twitch.py::TestPluginCanHandleUrlTwitch::test_url_matches_negative[https://example.com/index.html]", "tests/plugins/test_twitch.py::test_stream_weight", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_disable_ads_daterange_by_attr", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_disable_ads_daterange_by_class", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_disable_ads_daterange_by_id", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_disable_ads_daterange_unknown", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_disable_ads_has_midstream", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_disable_ads_has_preroll", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_incorrect_discontinuity_prefetch", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_low_latency_has_prefetch", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_low_latency_has_prefetch_disable_ads_has_preroll", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_low_latency_has_prefetch_has_preroll", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_low_latency_no_ads_reload_time", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_low_latency_no_prefetch", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_low_latency_no_prefetch_disable_ads_has_preroll", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_no_disable_ads_has_preroll", "tests/plugins/test_twitch.py::TestTwitchHLSStream::test_hls_no_low_latency_has_prefetch", "tests/plugins/test_twitch.py::TestTwitchAPIAccessToken::test_plugin_options[plugin0-exp_headers0-exp_variables0]", "tests/plugins/test_twitch.py::TestTwitchAPIAccessToken::test_plugin_options[plugin1-exp_headers1-exp_variables1]", "tests/plugins/test_twitch.py::TestTwitchAPIAccessToken::test_live_success[mock0]", "tests/plugins/test_twitch.py::TestTwitchAPIAccessToken::test_live_failure[mock0]", "tests/plugins/test_twitch.py::TestTwitchAPIAccessToken::test_vod_success[mock0]", "tests/plugins/test_twitch.py::TestTwitchAPIAccessToken::test_vod_failure[mock0]", "tests/plugins/test_twitch.py::TestTwitchAPIAccessToken::test_auth_failure[plugin0-mock0]", "tests/plugins/test_twitch.py::TestTwitchAPIAccessToken::test_failed_integrity_check[plugin0-mock0]", "tests/plugins/test_twitch.py::TestTwitchHLSMultivariantResponse::test_multivariant_response[success]", "tests/plugins/test_twitch.py::TestTwitchHLSMultivariantResponse::test_multivariant_response[invalid", "tests/plugins/test_twitch.py::TestTwitchHLSMultivariantResponse::test_multivariant_response[offline]", "tests/plugins/test_twitch.py::TestTwitchHLSMultivariantResponse::test_multivariant_response[geo", "tests/plugins/test_twitch.py::TestTwitchHLSMultivariantResponse::test_multivariant_response[non-json", "tests/plugins/test_twitch.py::TestTwitchMetadata::test_metadata_channel[True-https://twitch.tv/foo]", "tests/plugins/test_twitch.py::TestTwitchMetadata::test_metadata_channel_no_data[False-https://twitch.tv/foo]", "tests/plugins/test_twitch.py::TestTwitchMetadata::test_metadata_video[True-https://twitch.tv/videos/1337]", "tests/plugins/test_twitch.py::TestTwitchMetadata::test_metadata_video_no_data[False-https://twitch.tv/videos/1337]", "tests/plugins/test_twitch.py::TestTwitchMetadata::test_metadata_clip[True-https://clips.twitch.tv/foo]", "tests/plugins/test_twitch.py::TestTwitchMetadata::test_metadata_clip_no_data[False-https://clips.twitch.tv/foo]" ]
[]
BSD 2-Clause "Simplified" License
18,580
775
[ "src/streamlink/plugins/twitch.py" ]
googleapis__python-bigquery-1944
3e7a48d36e3c7bf6abe1b5550097178f6ca6e174
2024-06-04 01:18:00
3e7a48d36e3c7bf6abe1b5550097178f6ca6e174
diff --git a/google/cloud/bigquery/job/query.py b/google/cloud/bigquery/job/query.py index a8530271..8049b748 100644 --- a/google/cloud/bigquery/job/query.py +++ b/google/cloud/bigquery/job/query.py @@ -1585,6 +1585,11 @@ class QueryJob(_AsyncJob): self._retry_do_query = retry_do_query self._job_retry = job_retry + # If the job hasn't been created, create it now. Related: + # https://github.com/googleapis/python-bigquery/issues/1940 + if self.state is None: + self._begin(retry=retry, **done_kwargs) + # Refresh the job status with jobs.get because some of the # exceptions thrown by jobs.getQueryResults like timeout and # rateLimitExceeded errors are ambiguous. We want to know if
QueryJob class break flow after upgrade to 3.21.0 Affect version: >=3.21.0, <=3.23.1 #### Steps to reproduce ``` python from google.cloud import bigquery import uuid client = bigquery.Client() from google.cloud.bigquery import QueryJob QueryJob(job_id=str(uuid.uuid4()), query="select 1", client=client).result() # return 404 error, work with version 3.20.1 ```
googleapis/python-bigquery
diff --git a/tests/unit/job/test_query.py b/tests/unit/job/test_query.py index 66055dee..5b69c98c 100644 --- a/tests/unit/job/test_query.py +++ b/tests/unit/job/test_query.py @@ -1037,6 +1037,86 @@ class TestQueryJob(_Base): self.assertIsNone(result.job_id) self.assertIsNone(result.query_id) + # If the job doesn't exist, create the job first. Issue: + # https://github.com/googleapis/python-bigquery/issues/1940 + def test_result_begin_job_if_not_exist(self): + begun_resource = self._make_resource() + query_running_resource = { + "jobComplete": True, + "jobReference": { + "projectId": self.PROJECT, + "jobId": self.JOB_ID, + "location": "US", + }, + "schema": {"fields": [{"name": "col1", "type": "STRING"}]}, + "status": {"state": "RUNNING"}, + } + query_done_resource = { + "jobComplete": True, + "jobReference": { + "projectId": self.PROJECT, + "jobId": self.JOB_ID, + "location": "US", + }, + "schema": {"fields": [{"name": "col1", "type": "STRING"}]}, + "status": {"state": "DONE"}, + } + done_resource = copy.deepcopy(begun_resource) + done_resource["status"] = {"state": "DONE"} + connection = make_connection( + begun_resource, + query_running_resource, + query_done_resource, + done_resource, + ) + client = _make_client(project=self.PROJECT, connection=connection) + job = self._make_one(self.JOB_ID, self.QUERY, client) + job._properties["jobReference"]["location"] = "US" + + job.result() + + create_job_call = mock.call( + method="POST", + path=f"/projects/{self.PROJECT}/jobs", + data={ + "jobReference": { + "jobId": self.JOB_ID, + "projectId": self.PROJECT, + "location": "US", + }, + "configuration": { + "query": {"useLegacySql": False, "query": self.QUERY}, + }, + }, + timeout=None, + ) + reload_call = mock.call( + method="GET", + path=f"/projects/{self.PROJECT}/jobs/{self.JOB_ID}", + query_params={"projection": "full", "location": "US"}, + timeout=DEFAULT_GET_JOB_TIMEOUT, + ) + get_query_results_call = mock.call( + method="GET", + path=f"/projects/{self.PROJECT}/queries/{self.JOB_ID}", + query_params={ + "maxResults": 0, + "location": "US", + }, + timeout=None, + ) + + connection.api_request.assert_has_calls( + [ + # Make sure we start a job that hasn't started yet. See: + # https://github.com/googleapis/python-bigquery/issues/1940 + create_job_call, + reload_call, + get_query_results_call, + reload_call, + ] + ) + def test_result_with_done_job_calls_get_query_results(self): query_resource_done = { "jobComplete": True, @@ -1379,6 +1459,7 @@ class TestQueryJob(_Base): client = _make_client(project=self.PROJECT, connection=connection) job = self._make_one(self.JOB_ID, self.QUERY, client) job._properties["jobReference"]["location"] = "US" + job._properties["status"] = {"state": "RUNNING"} with freezegun.freeze_time("1970-01-01 00:00:00", tick=False): job.result( @@ -1429,6 +1510,7 @@ class TestQueryJob(_Base): client = _make_client(project=self.PROJECT, connection=connection) job = self._make_one(self.JOB_ID, self.QUERY, client) job._properties["jobReference"]["location"] = "US" + job._properties["status"] = {"state": "RUNNING"} with freezegun.freeze_time( "1970-01-01 00:00:00", auto_tick_seconds=1.0 @@ -2319,5 +2401,6 @@ class TestQueryJob(_Base): connection = make_connection(begun_resource, query_resource, done_resource) client = _make_client(project=self.PROJECT, connection=connection) job = self._make_one(self.JOB_ID, self.QUERY, client) + job._properties["status"] = {"state": "RUNNING"} self.assertIsInstance(iter(job), types.GeneratorType)
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
3.23
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "freezegun" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asttokens==3.0.0 attrs==25.3.0 cachetools==5.5.2 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 comm==0.2.2 coverage==7.8.0 db-dtypes==1.4.2 debugpy==1.8.13 decorator==5.2.1 Deprecated==1.2.18 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fiona==1.10.1 freezegun==1.5.1 geopandas==0.14.4 google-api-core==2.24.2 google-auth==2.38.0 -e git+https://github.com/googleapis/python-bigquery.git@3e7a48d36e3c7bf6abe1b5550097178f6ca6e174#egg=google_cloud_bigquery google-cloud-bigquery-storage==2.30.0 google-cloud-core==2.4.3 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 grpcio==1.71.0 grpcio-status==1.63.0rc1 idna==3.10 importlib_metadata==8.6.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 jedi==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyterlab_widgets==3.0.13 matplotlib-inline==0.1.7 nest-asyncio==1.6.0 numpy==2.0.2 opentelemetry-api==1.31.1 opentelemetry-instrumentation==0.52b1 opentelemetry-sdk==1.31.1 opentelemetry-semantic-conventions==0.52b1 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 parso==0.8.4 pexpect==4.9.0 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==4.25.6 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 Pygments==2.19.1 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==26.3.0 requests==2.32.3 rsa==4.9 shapely==2.0.7 six==1.17.0 stack-data==0.6.3 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 wcwidth==0.2.13 widgetsnbextension==4.0.13 wrapt==1.17.2 zipp==3.21.0
name: python-bigquery channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asttokens==3.0.0 - attrs==25.3.0 - cachetools==5.5.2 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - comm==0.2.2 - coverage==7.8.0 - db-dtypes==1.4.2 - debugpy==1.8.13 - decorator==5.2.1 - deprecated==1.2.18 - executing==2.2.0 - fiona==1.10.1 - freezegun==1.5.1 - geopandas==0.14.4 - google-api-core==2.24.2 - google-auth==2.38.0 - google-cloud-bigquery-storage==2.30.0 - google-cloud-core==2.4.3 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - grpcio==1.71.0 - grpcio-status==1.63.0rc1 - idna==3.10 - importlib-metadata==8.6.1 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - jedi==0.19.2 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyterlab-widgets==3.0.13 - matplotlib-inline==0.1.7 - nest-asyncio==1.6.0 - numpy==2.0.2 - opentelemetry-api==1.31.1 - opentelemetry-instrumentation==0.52b1 - opentelemetry-sdk==1.31.1 - opentelemetry-semantic-conventions==0.52b1 - pandas==2.2.3 - parso==0.8.4 - pexpect==4.9.0 - platformdirs==4.3.7 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==4.25.6 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pygments==2.19.1 - pyproj==3.6.1 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==26.3.0 - requests==2.32.3 - rsa==4.9 - shapely==2.0.7 - six==1.17.0 - stack-data==0.6.3 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - wcwidth==0.2.13 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - zipp==3.21.0 prefix: /opt/conda/envs/python-bigquery
[ "tests/unit/job/test_query.py::TestQueryJob::test_result_begin_job_if_not_exist" ]
[]
[ "tests/unit/job/test_query.py::TestQueryJob::test__begin_error", "tests/unit/job/test_query.py::TestQueryJob::test__begin_w_timeout", "tests/unit/job/test_query.py::TestQueryJob::test_begin_w_alternate_client", "tests/unit/job/test_query.py::TestQueryJob::test_begin_w_bound_client", "tests/unit/job/test_query.py::TestQueryJob::test_begin_w_named_query_parameter", "tests/unit/job/test_query.py::TestQueryJob::test_begin_w_positional_query_parameter", "tests/unit/job/test_query.py::TestQueryJob::test_begin_w_table_defs", "tests/unit/job/test_query.py::TestQueryJob::test_begin_w_udf", "tests/unit/job/test_query.py::TestQueryJob::test_bi_engine_stats", "tests/unit/job/test_query.py::TestQueryJob::test_billing_tier", "tests/unit/job/test_query.py::TestQueryJob::test_cache_hit", "tests/unit/job/test_query.py::TestQueryJob::test_cancelled", "tests/unit/job/test_query.py::TestQueryJob::test_ctor_defaults", "tests/unit/job/test_query.py::TestQueryJob::test_ctor_w_query_parameters", "tests/unit/job/test_query.py::TestQueryJob::test_ctor_w_udf_resources", "tests/unit/job/test_query.py::TestQueryJob::test_ddl_operation_performed", "tests/unit/job/test_query.py::TestQueryJob::test_ddl_target_routine", "tests/unit/job/test_query.py::TestQueryJob::test_ddl_target_table", "tests/unit/job/test_query.py::TestQueryJob::test_dml_stats", "tests/unit/job/test_query.py::TestQueryJob::test_dry_run_query", "tests/unit/job/test_query.py::TestQueryJob::test_estimated_bytes_processed", "tests/unit/job/test_query.py::TestQueryJob::test_exists_hit_w_alternate_client", "tests/unit/job/test_query.py::TestQueryJob::test_exists_miss_w_bound_client", "tests/unit/job/test_query.py::TestQueryJob::test_from_api_repr_bare", "tests/unit/job/test_query.py::TestQueryJob::test_from_api_repr_w_properties", "tests/unit/job/test_query.py::TestQueryJob::test_from_api_repr_with_dml_stats", "tests/unit/job/test_query.py::TestQueryJob::test_from_api_repr_with_encryption", "tests/unit/job/test_query.py::TestQueryJob::test_from_api_repr_with_transaction_info", "tests/unit/job/test_query.py::TestQueryJob::test_iter", "tests/unit/job/test_query.py::TestQueryJob::test_no_schema", "tests/unit/job/test_query.py::TestQueryJob::test_num_dml_affected_rows", "tests/unit/job/test_query.py::TestQueryJob::test_query_plan", "tests/unit/job/test_query.py::TestQueryJob::test_referenced_tables", "tests/unit/job/test_query.py::TestQueryJob::test_reload_query_results_uses_transport_timeout", "tests/unit/job/test_query.py::TestQueryJob::test_reload_w_alternate_client", "tests/unit/job/test_query.py::TestQueryJob::test_reload_w_bound_client", "tests/unit/job/test_query.py::TestQueryJob::test_reload_w_timeout", "tests/unit/job/test_query.py::TestQueryJob::test_result_dry_run", "tests/unit/job/test_query.py::TestQueryJob::test_result_error", "tests/unit/job/test_query.py::TestQueryJob::test_result_reloads_job_state_until_done", "tests/unit/job/test_query.py::TestQueryJob::test_result_transport_timeout_error", "tests/unit/job/test_query.py::TestQueryJob::test_result_w_custom_retry", "tests/unit/job/test_query.py::TestQueryJob::test_result_w_empty_schema", "tests/unit/job/test_query.py::TestQueryJob::test_result_w_page_size", "tests/unit/job/test_query.py::TestQueryJob::test_result_w_timeout_doesnt_raise", "tests/unit/job/test_query.py::TestQueryJob::test_result_w_timeout_raises_concurrent_futures_timeout", "tests/unit/job/test_query.py::TestQueryJob::test_result_with_done_job_calls_get_query_results", "tests/unit/job/test_query.py::TestQueryJob::test_result_with_done_jobs_query_response_doesnt_call_get_query_results", "tests/unit/job/test_query.py::TestQueryJob::test_result_with_max_results", "tests/unit/job/test_query.py::TestQueryJob::test_result_with_none_timeout", "tests/unit/job/test_query.py::TestQueryJob::test_result_with_start_index", "tests/unit/job/test_query.py::TestQueryJob::test_schema", "tests/unit/job/test_query.py::TestQueryJob::test_search_stats", "tests/unit/job/test_query.py::TestQueryJob::test_slot_millis", "tests/unit/job/test_query.py::TestQueryJob::test_statement_type", "tests/unit/job/test_query.py::TestQueryJob::test_timeline", "tests/unit/job/test_query.py::TestQueryJob::test_total_bytes_billed", "tests/unit/job/test_query.py::TestQueryJob::test_total_bytes_processed", "tests/unit/job/test_query.py::TestQueryJob::test_undeclared_query_parameters" ]
[]
Apache License 2.0
18,587
212
[ "google/cloud/bigquery/job/query.py" ]
python-pillow__Pillow-8104
48a921b31f4d1b84ed9b93d3ba2a8061366e8229
2024-06-04 08:58:00
d87c1c148778be35ec29194434315e39eb33bedc
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py index d723c1992..d2834929b 100644 --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -1115,7 +1115,7 @@ class _fdat: def _write_multiple_frames(im, fp, chunk, mode, rawmode, default_image, append_images): - duration = im.encoderinfo.get("duration", im.info.get("duration", 0)) + duration = im.encoderinfo.get("duration") loop = im.encoderinfo.get("loop", im.info.get("loop", 0)) disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE)) blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE)) @@ -1136,6 +1136,8 @@ def _write_multiple_frames(im, fp, chunk, mode, rawmode, default_image, append_i encoderinfo = im.encoderinfo.copy() if isinstance(duration, (list, tuple)): encoderinfo["duration"] = duration[frame_count] + elif duration is None and "duration" in im_frame.info: + encoderinfo["duration"] = im_frame.info["duration"] if isinstance(disposal, (list, tuple)): encoderinfo["disposal"] = disposal[frame_count] if isinstance(blend, (list, tuple)): @@ -1170,15 +1172,12 @@ def _write_multiple_frames(im, fp, chunk, mode, rawmode, default_image, append_i not bbox and prev_disposal == encoderinfo.get("disposal") and prev_blend == encoderinfo.get("blend") + and "duration" in encoderinfo ): - previous["encoderinfo"]["duration"] += encoderinfo.get( - "duration", duration - ) + previous["encoderinfo"]["duration"] += encoderinfo["duration"] continue else: bbox = None - if "duration" not in encoderinfo: - encoderinfo["duration"] = duration im_frames.append({"im": im_frame, "bbox": bbox, "encoderinfo": encoderinfo}) if len(im_frames) == 1 and not default_image: @@ -1208,7 +1207,7 @@ def _write_multiple_frames(im, fp, chunk, mode, rawmode, default_image, append_i im_frame = im_frame.crop(bbox) size = im_frame.size encoderinfo = frame_data["encoderinfo"] - frame_duration = int(round(encoderinfo["duration"])) + frame_duration = int(round(encoderinfo.get("duration", 0))) frame_disposal = encoderinfo.get("disposal", disposal) frame_blend = encoderinfo.get("blend", blend) # frame control
Saving to apng has wrong durations Using https://github.com/python-pillow/Pillow/blob/main/Tests/images/apng/different_durations.png ```python from PIL import Image, ImageSequence ddp = Image.open('different_durations.png') print([frame.info.get('duration') for frame in ImageSequence.Iterator(ddp)]) # [4000.0, 1000.0] ddp.save('different_durations.gif',save_all=True) ddg = Image.open('different_durations.gif') print([frame.info.get('duration') for frame in ImageSequence.Iterator(ddg)]) # [4000, 1000] ddg.save('same_durations.png',save_all=True) sdp = Image.open('same_durations.png') print([frame.info.get('duration') for frame in ImageSequence.Iterator(sdp)]) # [1000.0, 1000.0] ``` Also, ImageMagick (version 7.1.1-33) says the duration of the second frame is actually 990, not 1000. ```sh > magick identify -format %T\n apng:different_durations.png 400 99 ``` I'm not sure what's going on there though, because the duration parsing isn't complicated. https://github.com/python-pillow/Pillow/blob/219add02393d6e63276286908ecd9014271c941c/src/PIL/PngImagePlugin.py#L669-L672
python-pillow/Pillow
diff --git a/Tests/test_file_apng.py b/Tests/test_file_apng.py index 1b393a3ff..e95850212 100644 --- a/Tests/test_file_apng.py +++ b/Tests/test_file_apng.py @@ -706,10 +706,21 @@ def test_different_modes_in_later_frames( assert reloaded.mode == mode -def test_apng_repeated_seeks_give_correct_info() -> None: +def test_different_durations(tmp_path: Path) -> None: + test_file = str(tmp_path / "temp.png") + with Image.open("Tests/images/apng/different_durations.png") as im: - for i in range(3): + for _ in range(3): im.seek(0) assert im.info["duration"] == 4000 + im.seek(1) assert im.info["duration"] == 1000 + + im.save(test_file, save_all=True) + + with Image.open(test_file) as reloaded: + assert reloaded.info["duration"] == 4000 + + reloaded.seek(1) + assert reloaded.info["duration"] == 1000
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_media", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
10.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest pytest-cov pytest-timeout", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc libjpeg-dev zlib1g-dev libtiff5-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev libharfbuzz-dev libfribidi-dev libxcb1-dev" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work -e git+https://github.com/python-pillow/Pillow.git@48a921b31f4d1b84ed9b93d3ba2a8061366e8229#egg=pillow pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 pytest-timeout==2.3.1 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: Pillow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - pillow==10.4.0.dev0 - pytest-cov==6.0.0 - pytest-timeout==2.3.1 prefix: /opt/conda/envs/Pillow
[ "Tests/test_file_apng.py::test_different_durations" ]
[]
[ "Tests/test_file_apng.py::test_apng_basic", "Tests/test_file_apng.py::test_apng_fdat[Tests/images/apng/split_fdat.png]", "Tests/test_file_apng.py::test_apng_fdat[Tests/images/apng/split_fdat_zero_chunk.png]", "Tests/test_file_apng.py::test_apng_dispose", "Tests/test_file_apng.py::test_apng_dispose_region", "Tests/test_file_apng.py::test_apng_dispose_op_previous_frame", "Tests/test_file_apng.py::test_apng_dispose_op_background_p_mode", "Tests/test_file_apng.py::test_apng_blend", "Tests/test_file_apng.py::test_apng_blend_transparency", "Tests/test_file_apng.py::test_apng_chunk_order", "Tests/test_file_apng.py::test_apng_delay", "Tests/test_file_apng.py::test_apng_num_plays", "Tests/test_file_apng.py::test_apng_mode", "Tests/test_file_apng.py::test_apng_chunk_errors", "Tests/test_file_apng.py::test_apng_syntax_errors", "Tests/test_file_apng.py::test_apng_sequence_errors[sequence_start.png]", "Tests/test_file_apng.py::test_apng_sequence_errors[sequence_gap.png]", "Tests/test_file_apng.py::test_apng_sequence_errors[sequence_repeat.png]", "Tests/test_file_apng.py::test_apng_sequence_errors[sequence_repeat_chunk.png]", "Tests/test_file_apng.py::test_apng_sequence_errors[sequence_reorder.png]", "Tests/test_file_apng.py::test_apng_sequence_errors[sequence_reorder_chunk.png]", "Tests/test_file_apng.py::test_apng_sequence_errors[sequence_fdat_fctl.png]", "Tests/test_file_apng.py::test_apng_save", "Tests/test_file_apng.py::test_apng_save_alpha", "Tests/test_file_apng.py::test_apng_save_split_fdat", "Tests/test_file_apng.py::test_apng_save_duration_loop", "Tests/test_file_apng.py::test_apng_save_disposal", "Tests/test_file_apng.py::test_apng_save_disposal_previous", "Tests/test_file_apng.py::test_apng_save_blend", "Tests/test_file_apng.py::test_apng_save_size", "Tests/test_file_apng.py::test_seek_after_close", "Tests/test_file_apng.py::test_different_modes_in_later_frames[True-True-RGBA]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[True-True-RGB]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[True-True-P]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[True-False-RGBA]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[True-False-RGB]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[True-False-P]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[False-True-RGBA]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[False-True-RGB]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[False-True-P]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[False-False-RGBA]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[False-False-RGB]", "Tests/test_file_apng.py::test_different_modes_in_later_frames[False-False-P]" ]
[]
MIT-CMU License
18,591
651
[ "src/PIL/PngImagePlugin.py" ]
googleapis__python-bigquery-1945
cc7b3995eef4f357f031e06389db07f949987eeb
2024-06-04 23:23:11
7e522eea776cd9a74f8078c4236f63d5ff11f20e
Linchin: > QUESTION: Would we consider this a breaking change since we are moving to having a default setting of `True` instead of `False` which is what I feel like the current setting is. > > I am approving this, pending an answer to the above question. Would be happy to get in a chat OR a meeting to discuss, as need. be. Thanks for the question! The default behavior in the past is `True`. As in https://github.com/googleapis/python-bigquery/issues/1920, the customer couldn't disable the storage client unless they uninstall the package altogether.
diff --git a/google/cloud/bigquery/dbapi/connection.py b/google/cloud/bigquery/dbapi/connection.py index 66dee7df..a1a69b8f 100644 --- a/google/cloud/bigquery/dbapi/connection.py +++ b/google/cloud/bigquery/dbapi/connection.py @@ -35,12 +35,18 @@ class Connection(object): A client that uses the faster BigQuery Storage API to fetch rows from BigQuery. If not passed, it is created using the same credentials as ``client`` (provided that BigQuery Storage dependencies are installed). - - If both clients are available, ``bqstorage_client`` is used for - fetching query results. + prefer_bqstorage_client (Optional[bool]): + Prefer the BigQuery Storage client over the REST client. If Storage + client isn't available, fall back to the REST client. Defaults to + ``True``. """ - def __init__(self, client=None, bqstorage_client=None): + def __init__( + self, + client=None, + bqstorage_client=None, + prefer_bqstorage_client=True, + ): if client is None: client = bigquery.Client() self._owns_client = True @@ -49,7 +55,10 @@ class Connection(object): # A warning is already raised by the BQ Storage client factory factory if # instantiation fails, or if the given BQ Storage client instance is outdated. - if bqstorage_client is None: + if not prefer_bqstorage_client: + bqstorage_client = None + self._owns_bqstorage_client = False + elif bqstorage_client is None: bqstorage_client = client._ensure_bqstorage_client() self._owns_bqstorage_client = bqstorage_client is not None else: @@ -95,7 +104,7 @@ class Connection(object): return new_cursor -def connect(client=None, bqstorage_client=None): +def connect(client=None, bqstorage_client=None, prefer_bqstorage_client=True): """Construct a DB-API connection to Google BigQuery. Args: @@ -108,11 +117,12 @@ def connect(client=None, bqstorage_client=None): A client that uses the faster BigQuery Storage API to fetch rows from BigQuery. If not passed, it is created using the same credentials as ``client`` (provided that BigQuery Storage dependencies are installed). - - If both clients are available, ``bqstorage_client`` is used for - fetching query results. + prefer_bqstorage_client (Optional[bool]): + Prefer the BigQuery Storage client over the REST client. If Storage + client isn't available, fall back to the REST client. Defaults to + ``True``. Returns: google.cloud.bigquery.dbapi.Connection: A new DB-API connection to BigQuery. """ - return Connection(client, bqstorage_client) + return Connection(client, bqstorage_client, prefer_bqstorage_client)
Allow enabling/disabling the storage API on a per-connection basis In #16, support was added for the BigQuery storage API in the form of a `bqstorage_client` which is passed to or created by [`connect()`](https://github.com/googleapis/python-bigquery/blob/b739596f37b8c00b375cc811c316b618097d761a/google/cloud/bigquery/dbapi/connection.py#L98). Yet there is no way, other than installing or uninstalling the storage API itself, to toggle whether the storage API is enabled/disabled. Since use of the storage API does affect [pricing](https://cloud.google.com/bigquery/pricing), it would be preferable to enable or disable on a per-connection basis, perhaps as a `use_storage_api: bool` parameter on `connect()`. This way, callers could choose at will whether to use the storage API without having to change the Python environment the code is running in. As a hack to workaround this issue, I attempted calling `connect` passing a normal `Client` object rather than a `BigQueryReadClient` in the `bqstorage_client` parameter, but this does not create a functioning usable connection.
googleapis/python-bigquery
diff --git a/tests/unit/test_dbapi_connection.py b/tests/unit/test_dbapi_connection.py index 4071e57e..f5c77c44 100644 --- a/tests/unit/test_dbapi_connection.py +++ b/tests/unit/test_dbapi_connection.py @@ -122,6 +122,26 @@ class TestConnection(unittest.TestCase): self.assertIs(connection._client, mock_client) self.assertIs(connection._bqstorage_client, mock_bqstorage_client) + def test_connect_prefer_bqstorage_client_false(self): + pytest.importorskip("google.cloud.bigquery_storage") + from google.cloud.bigquery.dbapi import connect + from google.cloud.bigquery.dbapi import Connection + + mock_client = self._mock_client() + mock_bqstorage_client = self._mock_bqstorage_client() + mock_client._ensure_bqstorage_client.return_value = mock_bqstorage_client + + connection = connect( + client=mock_client, + bqstorage_client=mock_bqstorage_client, + prefer_bqstorage_client=False, + ) + + mock_client._ensure_bqstorage_client.assert_not_called() + self.assertIsInstance(connection, Connection) + self.assertIs(connection._client, mock_client) + self.assertIs(connection._bqstorage_client, None) + def test_raises_error_if_closed(self): from google.cloud.bigquery.dbapi.exceptions import ProgrammingError
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
3.24
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asttokens==3.0.0 attrs==25.3.0 cachetools==5.5.2 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 comm==0.2.2 coverage==7.8.0 db-dtypes==1.4.2 debugpy==1.8.13 decorator==5.2.1 Deprecated==1.2.18 exceptiongroup==1.2.2 execnet==2.1.1 executing==2.2.0 fiona==1.10.1 geopandas==0.14.4 google-api-core==2.24.2 google-auth==2.38.0 -e git+https://github.com/googleapis/python-bigquery.git@cc7b3995eef4f357f031e06389db07f949987eeb#egg=google_cloud_bigquery google-cloud-bigquery-storage==2.30.0 google-cloud-core==2.4.3 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 grpcio==1.71.0 grpcio-status==1.63.0rc1 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 jedi==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyterlab_widgets==3.0.13 matplotlib-inline==0.1.7 nest-asyncio==1.6.0 numpy==2.0.2 opentelemetry-api==1.31.1 opentelemetry-instrumentation==0.52b1 opentelemetry-sdk==1.31.1 opentelemetry-semantic-conventions==0.52b1 packaging==24.2 pandas==2.2.3 parso==0.8.4 pexpect==4.9.0 platformdirs==4.3.7 pluggy==1.5.0 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==4.25.6 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 Pygments==2.19.1 pyproj==3.6.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==26.3.0 requests==2.32.3 rsa==4.9 shapely==2.0.7 six==1.17.0 stack-data==0.6.3 tomli==2.2.1 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 wcwidth==0.2.13 widgetsnbextension==4.0.13 wrapt==1.17.2 zipp==3.21.0
name: python-bigquery channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asttokens==3.0.0 - attrs==25.3.0 - cachetools==5.5.2 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - comm==0.2.2 - coverage==7.8.0 - db-dtypes==1.4.2 - debugpy==1.8.13 - decorator==5.2.1 - deprecated==1.2.18 - exceptiongroup==1.2.2 - execnet==2.1.1 - executing==2.2.0 - fiona==1.10.1 - geopandas==0.14.4 - google-api-core==2.24.2 - google-auth==2.38.0 - google-cloud-bigquery-storage==2.30.0 - google-cloud-core==2.4.3 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - grpcio==1.71.0 - grpcio-status==1.63.0rc1 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - jedi==0.19.2 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyterlab-widgets==3.0.13 - matplotlib-inline==0.1.7 - nest-asyncio==1.6.0 - numpy==2.0.2 - opentelemetry-api==1.31.1 - opentelemetry-instrumentation==0.52b1 - opentelemetry-sdk==1.31.1 - opentelemetry-semantic-conventions==0.52b1 - packaging==24.2 - pandas==2.2.3 - parso==0.8.4 - pexpect==4.9.0 - platformdirs==4.3.7 - pluggy==1.5.0 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==4.25.6 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pygments==2.19.1 - pyproj==3.6.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==26.3.0 - requests==2.32.3 - rsa==4.9 - shapely==2.0.7 - six==1.17.0 - stack-data==0.6.3 - tomli==2.2.1 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - wcwidth==0.2.13 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - zipp==3.21.0 prefix: /opt/conda/envs/python-bigquery
[ "tests/unit/test_dbapi_connection.py::TestConnection::test_connect_prefer_bqstorage_client_false" ]
[]
[ "tests/unit/test_dbapi_connection.py::TestConnection::test_close_closes_all_created_bigquery_clients", "tests/unit/test_dbapi_connection.py::TestConnection::test_close_closes_all_created_cursors", "tests/unit/test_dbapi_connection.py::TestConnection::test_close_closes_only_open_created_cursors", "tests/unit/test_dbapi_connection.py::TestConnection::test_close_does_not_close_bigquery_clients_passed_to_it", "tests/unit/test_dbapi_connection.py::TestConnection::test_commit", "tests/unit/test_dbapi_connection.py::TestConnection::test_connect_w_both_clients", "tests/unit/test_dbapi_connection.py::TestConnection::test_connect_w_client", "tests/unit/test_dbapi_connection.py::TestConnection::test_connect_wo_client", "tests/unit/test_dbapi_connection.py::TestConnection::test_ctor_w_bqstorage_client", "tests/unit/test_dbapi_connection.py::TestConnection::test_ctor_wo_bqstorage_client", "tests/unit/test_dbapi_connection.py::TestConnection::test_cursor", "tests/unit/test_dbapi_connection.py::TestConnection::test_does_not_keep_cursor_instances_alive", "tests/unit/test_dbapi_connection.py::TestConnection::test_raises_error_if_closed" ]
[]
Apache License 2.0
18,599
681
[ "google/cloud/bigquery/dbapi/connection.py" ]
tobymao__sqlglot-3605
ff55ec1ca8c259f3c304aa7f6039c033f1fe728c
2024-06-05 19:52:07
ff55ec1ca8c259f3c304aa7f6039c033f1fe728c
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py index ec32a92c..8c3c471c 100644 --- a/sqlglot/dialects/snowflake.py +++ b/sqlglot/dialects/snowflake.py @@ -714,7 +714,7 @@ class Snowflake(Dialect): def _parse_file_location(self) -> t.Optional[exp.Expression]: # Parse either a subquery or a staged file return ( - self._parse_select(table=True) + self._parse_select(table=True, parse_subquery_alias=False) if self._match(TokenType.L_PAREN, advance=False) else self._parse_table_parts() ) diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py index ee403a71..ab49d08c 100644 --- a/sqlglot/dialects/tsql.py +++ b/sqlglot/dialects/tsql.py @@ -994,9 +994,13 @@ class TSQL(Dialect): elif kind == "TABLE": assert table where = exp.and_( - exp.column("table_name").eq(table.name), - exp.column("table_schema").eq(table.db) if table.db else None, - exp.column("table_catalog").eq(table.catalog) if table.catalog else None, + exp.column("table_name").eq(exp.Literal.string(table.name)), + exp.column("table_schema").eq(exp.Literal.string(table.db)) + if table.db + else None, + exp.column("table_catalog").eq(exp.Literal.string(table.catalog)) + if table.catalog + else None, ) sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})""" elif kind == "INDEX": diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index a74b7521..84133a3f 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -832,7 +832,7 @@ class Expression(metaclass=_Expression): def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E: this = self.copy() - other = convert(other, copy=True) + other = maybe_parse(other, copy=True) if not isinstance(this, klass) and not isinstance(other, klass): this = _wrap(this, Binary) other = _wrap(other, Binary)
Parsing issue for Snowflake COPY INTO with subqueries and FILE_FORMAT Hi! This issue sounds like an extension of previously reported: https://github.com/tobymao/sqlglot/issues/3434 where support for COPY INTO with subqueries was added. Looks like the library is facing an issue when FILE_FORMAT is being added to the query: ``` from sqlglot import parse_one query = "COPY INTO @my_stage/result/data FROM (SELECT * FROM orderstiny) file_format=(type='csv');" parse_one(query, read='snowflake') ``` above is producing following error: ``` sqlglot.errors.ParseError: Required keyword: 'this' missing for <class 'sqlglot.expressions.CopyParameter'>. Line 1, Col: 77 ``` Please let me know in case of any additional information is needed.
tobymao/sqlglot
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py index ba857191..9d9371db 100644 --- a/tests/dialects/test_snowflake.py +++ b/tests/dialects/test_snowflake.py @@ -1934,6 +1934,9 @@ STORAGE_ALLOWED_LOCATIONS=('s3://mybucket1/path1/', 's3://mybucket2/path2/')""", self.validate_identity( """COPY INTO mytable (col1, col2) FROM 's3://mybucket/data/files' STORAGE_INTEGRATION = "storage" ENCRYPTION = (TYPE='NONE' MASTER_KEY='key') FILES = ('file1', 'file2') PATTERN = 'pattern' FILE_FORMAT = (FORMAT_NAME=my_csv_format NULL_IF=('')) PARSE_HEADER = TRUE""" ) + self.validate_identity( + """COPY INTO @my_stage/result/data FROM (SELECT * FROM orderstiny) FILE_FORMAT = (TYPE='csv')""" + ) self.validate_all( """COPY INTO 's3://example/data.csv' FROM EXTRA.EXAMPLE.TABLE diff --git a/tests/test_build.py b/tests/test_build.py index 150bb42e..523dcc0a 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -67,16 +67,17 @@ class TestBuild(unittest.TestCase): (lambda: 1 + x * 2 + 3, "1 + (x * 2) + 3"), (lambda: x * 1 * 2 + 3, "(x * 1 * 2) + 3"), (lambda: 1 + (x * 2) / 3, "1 + ((x * 2) / 3)"), - (lambda: x & "y", "x AND 'y'"), - (lambda: x | "y", "x OR 'y'"), + (lambda: x & "'y'", "x AND 'y'"), + (lambda: x | "'y'", "x OR 'y'"), (lambda: -x, "-x"), (lambda: ~x, "NOT x"), (lambda: x[1], "x[1]"), (lambda: x[1, 2], "x[1, 2]"), (lambda: x["y"] + 1, "x['y'] + 1"), - (lambda: x.like("y"), "x LIKE 'y'"), - (lambda: x.ilike("y"), "x ILIKE 'y'"), - (lambda: x.rlike("y"), "REGEXP_LIKE(x, 'y')"), + (lambda: x.like("y"), "x LIKE y"), + (lambda: x.like("'y'"), "x LIKE 'y'"), + (lambda: x.ilike("'y'"), "x ILIKE 'y'"), + (lambda: x.rlike("'y'"), "REGEXP_LIKE(x, 'y')"), ( lambda: case().when("x = 1", "x").else_("bar"), "CASE WHEN x = 1 THEN x ELSE bar END",
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 3 }
24.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 coverage==7.8.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 Pygments==2.19.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@ff55ec1ca8c259f3c304aa7f6039c033f1fe728c#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - coverage==7.8.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pygments==2.19.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_copy", "tests/test_build.py::TestBuild::test_build" ]
[]
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_alter_set_unset", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_describe_table", "tests/dialects/test_snowflake.py::TestSnowflake::test_flatten", "tests/dialects/test_snowflake.py::TestSnowflake::test_historical_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_snowflake.py::TestSnowflake::test_minus", "tests/dialects/test_snowflake.py::TestSnowflake::test_null_treatment", "tests/dialects/test_snowflake.py::TestSnowflake::test_parse_like_any", "tests/dialects/test_snowflake.py::TestSnowflake::test_querying_semi_structured_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_replace", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_substr", "tests/dialects/test_snowflake.py::TestSnowflake::test_sample", "tests/dialects/test_snowflake.py::TestSnowflake::test_semi_structured_types", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_columns", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_imported_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_objects", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_primary_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_schemas", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_sequences", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_tables", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_unique_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_users", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_views", "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake", "tests/dialects/test_snowflake.py::TestSnowflake::test_staged_files", "tests/dialects/test_snowflake.py::TestSnowflake::test_storage_integration", "tests/dialects/test_snowflake.py::TestSnowflake::test_stored_procedures", "tests/dialects/test_snowflake.py::TestSnowflake::test_swap", "tests/dialects/test_snowflake.py::TestSnowflake::test_table_literal", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/dialects/test_snowflake.py::TestSnowflake::test_try_cast", "tests/dialects/test_snowflake.py::TestSnowflake::test_user_defined_functions", "tests/dialects/test_snowflake.py::TestSnowflake::test_values" ]
[]
MIT License
18,607
612
[ "sqlglot/dialects/snowflake.py", "sqlglot/dialects/tsql.py", "sqlglot/expressions.py" ]
conan-io__conan-16415
a474e3d67c1a0acfc4f8fa7db2f71de4bd089466
2024-06-06 07:59:48
3c72e2a83b468bb0d18e958c7e160fbb324b146e
diff --git a/conan/cli/command.py b/conan/cli/command.py index 7a074dc7c..b2b50f1c7 100644 --- a/conan/cli/command.py +++ b/conan/cli/command.py @@ -98,6 +98,12 @@ class BaseConanCommand: formatter(info) + def _dispatch_errors(self, info): + if info and isinstance(info, dict): + if info.get("conan_error"): + raise ConanException(info["conan_error"]) + if info.get("conan_warning"): + ConanOutput().warning(info["conan_warning"]) class ConanArgumentParser(argparse.ArgumentParser): @@ -179,6 +185,7 @@ class ConanCommand(BaseConanCommand): else: sub.set_parser(subcommand_parser, conan_api) sub.run(conan_api, parser, *args) + self._dispatch_errors(info) @property def group(self): @@ -198,6 +205,7 @@ class ConanSubCommand(BaseConanCommand): info = self._method(conan_api, parent_parser, self._parser, *args) # It is necessary to do it after calling the "method" otherwise parser not complete self._format(parent_parser, info, *args) + self._dispatch_errors(info) def set_name(self, parent_name): self._name = self._subcommand_name.replace(f'{parent_name}-', '', 1) diff --git a/conan/cli/commands/graph.py b/conan/cli/commands/graph.py index 8f4124744..690be8869 100644 --- a/conan/cli/commands/graph.py +++ b/conan/cli/commands/graph.py @@ -45,8 +45,9 @@ def graph(conan_api, parser, *args): """ -def cli_build_order(build_order): +def cli_build_order(result): # TODO: Very simple cli output, probably needs to be improved + build_order = result["build_order"] build_order = build_order["order"] if isinstance(build_order, dict) else build_order for level in build_order: for item in level: @@ -59,8 +60,8 @@ def cli_build_order(build_order): cli_out_write(f"{item['ref']}:{item['package_id']} - {item['binary']}") -def json_build_order(build_order): - cli_out_write(json.dumps(build_order, indent=4)) +def json_build_order(result): + cli_out_write(json.dumps(result["build_order"], indent=4)) @conan_subcommand(formatters={"text": cli_build_order, "json": json_build_order, @@ -128,7 +129,9 @@ def graph_build_order(conan_api, parser, subparser, *args): clean=args.lockfile_clean) conan_api.lockfile.save_lockfile(lockfile, args.lockfile_out, cwd) - return install_order_serialized + return {"build_order": install_order_serialized, + "conan_error": install_graph.get_errors()} + @conan_subcommand(formatters={"text": cli_build_order, "json": json_build_order, @@ -159,7 +162,9 @@ def graph_build_order_merge(conan_api, parser, subparser, *args): install_order_serialized = result.install_build_order() if getattr(result, "legacy"): install_order_serialized = install_order_serialized["order"] - return install_order_serialized + + return {"build_order": install_order_serialized, + "conan_error": result.get_errors()} @conan_subcommand(formatters={"text": format_graph_info, @@ -237,7 +242,10 @@ def graph_info(conan_api, parser, subparser, *args): return {"graph": deps_graph, "field_filter": args.filter, "package_filter": args.package_filter, - "conan_api": conan_api} + "conan_api": conan_api, + "conan_error": str(deps_graph.error) if deps_graph.error else None, + # Do not compute graph errors if there are dependency errors + "conan_warning": InstallGraph(deps_graph).get_errors() if not deps_graph.error else None} @conan_subcommand(formatters={"text": explain_formatter_text, diff --git a/conan/cli/formatters/graph/build_order_html.py b/conan/cli/formatters/graph/build_order_html.py index e785bb01b..07d6af46e 100644 --- a/conan/cli/formatters/graph/build_order_html.py +++ b/conan/cli/formatters/graph/build_order_html.py @@ -266,7 +266,8 @@ def _render_build_order(build_order, template): return template.render(context) -def format_build_order_html(build_order): +def format_build_order_html(result): + build_order = result["build_order"] build_order = build_order["order"] if isinstance(build_order, dict) else build_order template = Template(build_order_html, autoescape=select_autoescape(['html', 'xml'])) cli_out_write(_render_build_order(build_order, template)) diff --git a/conan/cli/formatters/graph/graph.py b/conan/cli/formatters/graph/graph.py index 5ebfd23dd..7bec8ba65 100644 --- a/conan/cli/formatters/graph/graph.py +++ b/conan/cli/formatters/graph/graph.py @@ -126,8 +126,6 @@ def format_graph_html(result): error["type"] = "conflict" error["should_highlight_node"] = lambda node: node.id == graph.error.node.id cli_out_write(_render_graph(graph, error, template, template_folder)) - if graph.error: - raise graph.error def format_graph_dot(result): @@ -138,8 +136,6 @@ def format_graph_dot(result): user_template = os.path.join(template_folder, "graph.dot") template = load(user_template) if os.path.isfile(user_template) else graph_info_dot cli_out_write(_render_graph(graph, None, template, template_folder)) - if graph.error: - raise graph.error def format_graph_json(result): @@ -150,5 +146,3 @@ def format_graph_json(result): serial = filter_graph(serial, package_filter=package_filter, field_filter=field_filter) json_result = json.dumps({"graph": serial}, indent=4) cli_out_write(json_result) - if graph.error: - raise graph.error diff --git a/conan/cli/formatters/graph/graph_info_text.py b/conan/cli/formatters/graph/graph_info_text.py index 055496f54..aa431cd85 100644 --- a/conan/cli/formatters/graph/graph_info_text.py +++ b/conan/cli/formatters/graph/graph_info_text.py @@ -33,8 +33,6 @@ def format_graph_info(result): for n in serial["nodes"].values(): cli_out_write(f"{n['ref']}:") # FIXME: This can be empty for consumers and it is ugly ":" _serial_pretty_printer(n, indent=" ") - if graph.error: - raise graph.error def _serial_pretty_printer(data, indent=""): diff --git a/conan/tools/gnu/gnutoolchain.py b/conan/tools/gnu/gnutoolchain.py index 9848e18fc..d154f1cfb 100644 --- a/conan/tools/gnu/gnutoolchain.py +++ b/conan/tools/gnu/gnutoolchain.py @@ -1,3 +1,5 @@ +import os + from conan.internal import check_duplicated_generator from conan.internal.internal_tools import raise_on_universal_arch from conan.tools.apple.apple import is_apple_os, resolve_apple_flags @@ -9,6 +11,7 @@ from conan.tools.build.flags import architecture_flag, build_type_flags, cppstd_ from conan.tools.env import Environment from conan.tools.gnu.get_gnu_triplet import _get_gnu_triplet from conan.tools.microsoft import VCVars, msvc_runtime_flag, unix_path, check_min_vs, is_msvc +from conans.errors import ConanException from conans.model.pkg_type import PackageType @@ -18,6 +21,8 @@ class GnuToolchain: Note: it's based on legacy AutotoolsToolchain but with a more modern and usable UX """ + script_name = "conangnutoolchain" + def __init__(self, conanfile, namespace=None, prefix="/"): """ :param conanfile: The current recipe object. Always use ``self``. @@ -63,8 +68,8 @@ class GnuToolchain: "host": {"triplet": self._conanfile.conf.get("tools.gnu:host_triplet")}, "build": {"triplet": self._conanfile.conf.get("tools.gnu:build_triplet")} } - is_cross_building = cross_building(self._conanfile) - if is_cross_building: + self._is_cross_building = cross_building(self._conanfile) + if self._is_cross_building: compiler = self._conanfile.settings.get_safe("compiler") # Host triplet if not self.triplets_info["host"]["triplet"]: @@ -88,7 +93,7 @@ class GnuToolchain: self.configure_args.update(self._get_default_configure_install_flags()) self.configure_args.update(self._get_default_triplets()) # Apple stuff - is_cross_building_osx = (is_cross_building + is_cross_building_osx = (self._is_cross_building and conanfile.settings_build.get_safe('os') == "Macos" and is_apple_os(conanfile)) min_flag, arch_flag, isysroot_flag = ( @@ -99,7 +104,7 @@ class GnuToolchain: # -isysroot makes all includes for your library relative to the build directory self.apple_isysroot_flag = isysroot_flag self.apple_min_version_flag = min_flag - # MSVC common stuff + # Default initial environment flags self._initialize_default_extra_env() def yes_no(self, option_name, default=None, negated=False): @@ -116,31 +121,99 @@ class GnuToolchain: option_value = not option_value if negated else option_value return "yes" if option_value else "no" - def _initialize_default_extra_env(self): - """Initialize the default environment variables.""" - extra_env_vars = dict() - # Normally, these are the most common default flags used by MSVC in Windows - if is_msvc(self._conanfile): - extra_env_vars = {"CC": "cl -nologo", - "CXX": "cl -nologo", - "NM": "dumpbin -symbols", - "OBJDUMP": ":", - "RANLIB": ":", - "STRIP": ":"} + def _resolve_android_cross_compilation(self): + # Issue related: https://github.com/conan-io/conan/issues/13443 + ret = {} + if not self._is_cross_building or not self._conanfile.settings.get_safe("os") == "Android": + return ret + + ndk_path = self._conanfile.conf.get("tools.android:ndk_path", check_type=str) + if not ndk_path: + raise ConanException("You must provide a NDK path. Use 'tools.android:ndk_path' " + "configuration field.") + + if ndk_path: + arch = self._conanfile.settings.get_safe("arch") + os_build = self._conanfile.settings_build.get_safe("os") + ndk_os_folder = { + 'Macos': 'darwin', + 'iOS': 'darwin', + 'watchOS': 'darwin', + 'tvOS': 'darwin', + 'visionOS': 'darwin', + 'FreeBSD': 'linux', + 'Linux': 'linux', + 'Windows': 'windows', + 'WindowsCE': 'windows', + 'WindowsStore': 'windows' + }.get(os_build, "linux") + ndk_bin = os.path.join(ndk_path, "toolchains", "llvm", "prebuilt", + f"{ndk_os_folder}-x86_64", "bin") + android_api_level = self._conanfile.settings.get_safe("os.api_level") + android_target = {'armv7': 'armv7a-linux-androideabi', + 'armv8': 'aarch64-linux-android', + 'x86': 'i686-linux-android', + 'x86_64': 'x86_64-linux-android'}.get(arch) + os_build = self._conanfile.settings_build.get_safe('os') + ext = ".cmd" if os_build == "Windows" else "" + ret = { + "CC": os.path.join(ndk_bin, f"{android_target}{android_api_level}-clang{ext}"), + "CXX": os.path.join(ndk_bin, f"{android_target}{android_api_level}-clang++{ext}"), + "LD": os.path.join(ndk_bin, "ld"), + "STRIP": os.path.join(ndk_bin, "llvm-strip"), + "RANLIB": os.path.join(ndk_bin, "llvm-ranlib"), + "AS": os.path.join(ndk_bin, f"{android_target}{android_api_level}-clang{ext}"), + "AR": os.path.join(ndk_bin, "llvm-ar"), + } + # Overriding host triplet + self.triplets_info["host"]["triplet"] = android_target + return ret + + def _resolve_compilers_mapping_variables(self): + ret = {} # Configuration map compilers_mapping = {"c": "CC", "cpp": "CXX", "cuda": "NVCC", "fortran": "FC", "rc": "RC", "nm": "NM", "ranlib": "RANLIB", "objdump": "OBJDUMP", "strip": "STRIP"} # Compiler definitions by conf - compilers_by_conf = self._conanfile.conf.get("tools.build:compiler_executables", default={}, - check_type=dict) + compilers_by_conf = self._conanfile.conf.get("tools.build:compiler_executables", + default={}, check_type=dict) if compilers_by_conf: for comp, env_var in compilers_mapping.items(): if comp in compilers_by_conf: compiler = compilers_by_conf[comp] # https://github.com/conan-io/conan/issues/13780 compiler = unix_path(self._conanfile, compiler) - extra_env_vars[env_var] = compiler # User/tools ones have precedence + ret[env_var] = compiler # User/tools ones have precedence + # Issue related: https://github.com/conan-io/conan/issues/15486 + if self._is_cross_building and self._conanfile.conf_build: + compilers_build_mapping = ( + self._conanfile.conf_build.get("tools.build:compiler_executables", default={}, + check_type=dict) + ) + if "c" in compilers_build_mapping: + ret["CC_FOR_BUILD"] = compilers_build_mapping["c"] + if "cpp" in compilers_build_mapping: + ret["CXX_FOR_BUILD"] = compilers_build_mapping["cpp"] + return ret + + def _initialize_default_extra_env(self): + """Initialize the default environment variables.""" + # If it's an Android cross-compilation + extra_env_vars = self._resolve_android_cross_compilation() + if not extra_env_vars: + # Normally, these are the most common default flags used by MSVC in Windows + if is_msvc(self._conanfile): + extra_env_vars = {"CC": "cl -nologo", + "CXX": "cl -nologo", + "LD": "link -nologo", + "AR": "lib", + "NM": "dumpbin -symbols", + "OBJDUMP": ":", + "RANLIB": ":", + "STRIP": ":"} + extra_env_vars.update(self._resolve_compilers_mapping_variables()) + # Update the extra_env attribute with all the compiler values for env_var, env_value in extra_env_vars.items(): self.extra_env.define(env_var, env_value) @@ -252,7 +325,7 @@ class GnuToolchain: check_duplicated_generator(self, self._conanfile) # Composing both environments. User extra_env definitions has precedence env_vars = self._environment.vars(self._conanfile) - env_vars.save_script("conanautotoolstoolchain") + env_vars.save_script(GnuToolchain.script_name) # Converts all the arguments into strings args = { "configure_args": cmd_args_to_string(self._dict_to_list(self.configure_args)), diff --git a/conans/client/graph/install_graph.py b/conans/client/graph/install_graph.py index 65befe30d..312ba57e7 100644 --- a/conans/client/graph/install_graph.py +++ b/conans/client/graph/install_graph.py @@ -454,27 +454,62 @@ class InstallGraph: "order": [[n.serialize() for n in level] for level in install_order]} return result - def raise_errors(self): + def _get_missing_invalid_packages(self): missing, invalid = [], [] - for ref, install_node in self._nodes.items(): - for package in install_node.packages.values(): - if package.binary == BINARY_MISSING: - missing.append(package) - elif package.binary == BINARY_INVALID: - invalid.append(package) + def analyze_package(package): + if package.binary == BINARY_MISSING: + missing.append(package) + elif package.binary == BINARY_INVALID: + invalid.append(package) + for _, install_node in self._nodes.items(): + if self._order == "recipe": + for package in install_node.packages.values(): + analyze_package(package) + elif self._order == "configuration": + analyze_package(install_node) + + return missing, invalid + def raise_errors(self): + missing, invalid = self._get_missing_invalid_packages() + if invalid: + self._raise_invalid(invalid) + if missing: + self._raise_missing(missing) + + def get_errors(self): + missing, invalid = self._get_missing_invalid_packages() + errors = [] + tab = " " + if invalid or missing: + errors.append("There are some error(s) in the graph:") if invalid: - msg = ["There are invalid packages:"] for package in invalid: node = package.nodes[0] if node.cant_build and node.should_build: binary, reason = "Cannot build for this configuration", node.cant_build else: binary, reason = "Invalid", node.conanfile.info.invalid - msg.append("{}: {}: {}".format(node.conanfile, binary, reason)) - raise ConanInvalidConfiguration("\n".join(msg)) + errors.append(f"{tab}- {node.ref}: {binary}: {reason}") if missing: - self._raise_missing(missing) + missing_prefs = set(n.nodes[0].pref for n in missing) # avoid duplicated + for pref in list(sorted([str(pref) for pref in missing_prefs])): + errors.append(f"{tab}- {pref}: Missing binary") + if errors: + return "\n".join(errors) + return None + + def _raise_invalid(self, invalid): + msg = ["There are invalid packages:"] + for package in invalid: + node = package.nodes[0] + if node.cant_build and node.should_build: + binary, reason = "Cannot build for this configuration", node.cant_build + else: + binary, reason = "Invalid", node.conanfile.info.invalid + msg.append("{}: {}: {}".format(node.conanfile, binary, reason)) + raise ConanInvalidConfiguration("\n".join(msg)) + def _raise_missing(self, missing): # TODO: Remove out argument
[bug] Consistent command results and error messages accross install/create and graph ### What is your suggestion? When a dependency is `missing` or `invalid`, CLI commands `install`, `create`, etc, will output pertinent error messages and the exit code of the application will be `!=0`, meaning the command failed. Making some tests, we have found an inconsistency all along `conan graph` subcommands. `conan graph info` and `conan graph build-order` should output the same errors as `install` does and should fail in the same way. This does not imply when an error is found not generating the graph output. Commands should generate same graph output but they should fail. ## Example ```sh conan install --requires "unleash-client-cpp/1.3.0" ``` <details> ``` ======== Input profiles ======== Profile host: [settings] arch=armv8 build_type=Release compiler=apple-clang compiler.cppstd=gnu17 compiler.libcxx=libc++ compiler.version=15 os=Macos Profile build: [settings] arch=armv8 build_type=Release compiler=apple-clang compiler.cppstd=gnu17 compiler.libcxx=libc++ compiler.version=15 os=Macos ======== Computing dependency graph ======== Graph root cli Requirements cpr/1.10.5#a227f2a4f0deed3ee1f8b8237477129e - Cache libcurl/8.6.0#752cd9c3df0e9487b72301862f15a965 - Cache nlohmann_json/3.11.3#45828be26eb619a2e04ca517bb7b828d - Cache unleash-client-cpp/1.3.0#a4354a616cd5bdb81354825229954522 - Cache zlib/1.3.1#f52e03ae3d251dec704634230cd806a2 - Cache Build requirements autoconf/2.71#f9307992909d7fb3df459340f1932809 - Cache automake/1.16.5#058bda3e21c36c9aa8425daf3c1faf50 - Cache gnu-config/cci.20210814#dc430d754f465e8c74463019672fb97b - Cache libtool/2.4.7#08316dad5c72c541ed21e039e4cf217b - Cache m4/1.4.19#b38ced39a01e31fef5435bc634461fd2 - Cache meson/1.2.2#04bdfb85d665c82b08a3510aee3ffd19 - Cache ninja/1.11.1#77587f8c8318662ac8e5a7867eb4be21 - Cache pkgconf/2.1.0#27f44583701117b571307cf5b5fe5605 - Cache Resolved version ranges libcurl/[>=7.78.0 <9]: libcurl/8.6.0 zlib/[>=1.2.11 <2]: zlib/1.3.1 ======== Computing necessary packages ======== cpr/1.10.5: Compatible package ID 01269d344dd5584f4884dfbce8b9b77ae08480e6 equal to the default package ID: Skipping it. cpr/1.10.5: Checking 5 compatible configurations cpr/1.10.5: Compatible configurations not found in cache, checking servers cpr/1.10.5: 'dfee4b06bfe93e4207413fffd653ec0bb2ef0d5c': compiler.cppstd=17 cpr/1.10.5: '1b581912b6a996992095ec289d8a10caf974e2df': compiler.cppstd=20 cpr/1.10.5: 'b59d6a6f26a2d7f87370035527ef219122bb9093': compiler.cppstd=gnu20 cpr/1.10.5: '7b4224207f3ce01b81f5d00add4296667a22e2ba': compiler.cppstd=23 cpr/1.10.5: '839343c67d23729138e2ac0c4c4386e281cd1ffc': compiler.cppstd=gnu23 unleash-client-cpp/1.3.0: Compatible package ID e73661f3afc6efaa3f8ba17b9263163c204f8c52 equal to the default package ID: Skipping it. unleash-client-cpp/1.3.0: Checking 5 compatible configurations unleash-client-cpp/1.3.0: Compatible configurations not found in cache, checking servers unleash-client-cpp/1.3.0: '6332c366c6c529367a2b716abd77f657b96d3c47': compiler.cppstd=17 unleash-client-cpp/1.3.0: '9194788030461f5d772c319ed4b3d745e75e2d47': compiler.cppstd=20 unleash-client-cpp/1.3.0: 'ee3dc95e09fa0d284e807bdf988a10a5cc6e59c9': compiler.cppstd=gnu20 unleash-client-cpp/1.3.0: '4ff0d71ebb4d6a0900ca4e36b2b780168848c458': compiler.cppstd=23 unleash-client-cpp/1.3.0: 'dafb9907f23cc61560a25535b18340c225627896': compiler.cppstd=gnu23 Requirements cpr/1.10.5#a227f2a4f0deed3ee1f8b8237477129e:01269d344dd5584f4884dfbce8b9b77ae08480e6 - Missing libcurl/8.6.0#752cd9c3df0e9487b72301862f15a965:267b943cf33985f9448f72c97e42fcdb5094fcf5 - Missing unleash-client-cpp/1.3.0#a4354a616cd5bdb81354825229954522:e73661f3afc6efaa3f8ba17b9263163c204f8c52 - Missing zlib/1.3.1#f52e03ae3d251dec704634230cd806a2:2ee39e692ca4177b4b689b15bc1f2cfdf8f83706 - Missing Build requirements Skipped binaries nlohmann_json/3.11.3, autoconf/2.71, automake/1.16.5, gnu-config/cci.20210814, libtool/2.4.7, m4/1.4.19, meson/1.2.2, ninja/1.11.1, pkgconf/2.1.0 ERROR: Missing binary: cpr/1.10.5:01269d344dd5584f4884dfbce8b9b77ae08480e6 ERROR: Missing binary: libcurl/8.6.0:267b943cf33985f9448f72c97e42fcdb5094fcf5 ERROR: Missing binary: unleash-client-cpp/1.3.0:e73661f3afc6efaa3f8ba17b9263163c204f8c52 ERROR: Missing binary: zlib/1.3.1:2ee39e692ca4177b4b689b15bc1f2cfdf8f83706 zlib/1.3.1: WARN: Can't find a 'zlib/1.3.1' package binary '2ee39e692ca4177b4b689b15bc1f2cfdf8f83706' for the configuration: [settings] arch=armv8 build_type=Release compiler=apple-clang compiler.version=15 os=Macos [options] fPIC=True shared=False ERROR: Missing prebuilt package for 'cpr/1.10.5', 'libcurl/8.6.0', 'unleash-client-cpp/1.3.0', 'zlib/1.3.1'. You can try: - List all available packages using 'conan list zlib/1.3.1:* -r=remote' - Explain missing binaries: replace 'conan install ...' with 'conan graph explain ...' - Try to build locally from sources using the '--build=cpr/1.10.5 --build=libcurl/8.6.0 --build=unleash-client-cpp/1.3.0 --build=zlib/1.3.1' argument More Info at 'https://docs.conan.io/2/knowledge/faq.html#error-missing-prebuilt-package' ``` </details> ```sh conan graph info --requires "unleash-client-cpp/1.3.0" > /dev/null ``` <details> ``` ======== Computing dependency graph ======== Graph root cli Requirements cpr/1.10.5#a227f2a4f0deed3ee1f8b8237477129e - Cache libcurl/8.6.0#752cd9c3df0e9487b72301862f15a965 - Cache nlohmann_json/3.11.3#45828be26eb619a2e04ca517bb7b828d - Cache unleash-client-cpp/1.3.0#a4354a616cd5bdb81354825229954522 - Cache zlib/1.3.1#f52e03ae3d251dec704634230cd806a2 - Cache Build requirements autoconf/2.71#f9307992909d7fb3df459340f1932809 - Cache automake/1.16.5#058bda3e21c36c9aa8425daf3c1faf50 - Cache gnu-config/cci.20210814#dc430d754f465e8c74463019672fb97b - Cache libtool/2.4.7#08316dad5c72c541ed21e039e4cf217b - Cache m4/1.4.19#b38ced39a01e31fef5435bc634461fd2 - Cache meson/1.2.2#04bdfb85d665c82b08a3510aee3ffd19 - Cache ninja/1.11.1#77587f8c8318662ac8e5a7867eb4be21 - Cache pkgconf/2.1.0#27f44583701117b571307cf5b5fe5605 - Cache Resolved version ranges libcurl/[>=7.78.0 <9]: libcurl/8.6.0 zlib/[>=1.2.11 <2]: zlib/1.3.1 ======== Computing necessary packages ======== cpr/1.10.5: Compatible package ID 01269d344dd5584f4884dfbce8b9b77ae08480e6 equal to the default package ID: Skipping it. cpr/1.10.5: Checking 5 compatible configurations cpr/1.10.5: Compatible configurations not found in cache, checking servers cpr/1.10.5: 'dfee4b06bfe93e4207413fffd653ec0bb2ef0d5c': compiler.cppstd=17 cpr/1.10.5: '1b581912b6a996992095ec289d8a10caf974e2df': compiler.cppstd=20 cpr/1.10.5: 'b59d6a6f26a2d7f87370035527ef219122bb9093': compiler.cppstd=gnu20 cpr/1.10.5: '7b4224207f3ce01b81f5d00add4296667a22e2ba': compiler.cppstd=23 cpr/1.10.5: '839343c67d23729138e2ac0c4c4386e281cd1ffc': compiler.cppstd=gnu23 unleash-client-cpp/1.3.0: Compatible package ID e73661f3afc6efaa3f8ba17b9263163c204f8c52 equal to the default package ID: Skipping it. unleash-client-cpp/1.3.0: Checking 5 compatible configurations unleash-client-cpp/1.3.0: Compatible configurations not found in cache, checking servers unleash-client-cpp/1.3.0: '6332c366c6c529367a2b716abd77f657b96d3c47': compiler.cppstd=17 unleash-client-cpp/1.3.0: '9194788030461f5d772c319ed4b3d745e75e2d47': compiler.cppstd=20 unleash-client-cpp/1.3.0: 'ee3dc95e09fa0d284e807bdf988a10a5cc6e59c9': compiler.cppstd=gnu20 unleash-client-cpp/1.3.0: '4ff0d71ebb4d6a0900ca4e36b2b780168848c458': compiler.cppstd=23 unleash-client-cpp/1.3.0: 'dafb9907f23cc61560a25535b18340c225627896': compiler.cppstd=gnu23 Requirements cpr/1.10.5#a227f2a4f0deed3ee1f8b8237477129e:01269d344dd5584f4884dfbce8b9b77ae08480e6 - Missing libcurl/8.6.0#752cd9c3df0e9487b72301862f15a965:267b943cf33985f9448f72c97e42fcdb5094fcf5 - Missing unleash-client-cpp/1.3.0#a4354a616cd5bdb81354825229954522:e73661f3afc6efaa3f8ba17b9263163c204f8c52 - Missing zlib/1.3.1#f52e03ae3d251dec704634230cd806a2:2ee39e692ca4177b4b689b15bc1f2cfdf8f83706 - Missing Build requirements Skipped binaries nlohmann_json/3.11.3, autoconf/2.71, automake/1.16.5, gnu-config/cci.20210814, libtool/2.4.7, m4/1.4.19, meson/1.2.2, ninja/1.11.1, pkgconf/2.1.0 -------- Basic graph information -------- ``` </details> ```sh conan graph build-order --order-by=recipe --requires "unleash-client-cpp/1.3.0" > /dev/null ``` <details> ``` ======== Computing dependency graph ======== Graph root cli Requirements cpr/1.10.5#a227f2a4f0deed3ee1f8b8237477129e - Cache libcurl/8.8.0#9170903d66d6f6e6795fbb566a403129 - Cache nlohmann_json/3.11.3#45828be26eb619a2e04ca517bb7b828d - Cache unleash-client-cpp/1.3.0#a4354a616cd5bdb81354825229954522 - Cache zlib/1.3.1#f52e03ae3d251dec704634230cd806a2 - Cache Build requirements autoconf/2.71#f9307992909d7fb3df459340f1932809 - Cache automake/1.16.5#058bda3e21c36c9aa8425daf3c1faf50 - Cache gnu-config/cci.20210814#dc430d754f465e8c74463019672fb97b - Cache libtool/2.4.7#08316dad5c72c541ed21e039e4cf217b - Cache m4/1.4.19#b38ced39a01e31fef5435bc634461fd2 - Cache meson/1.2.2#04bdfb85d665c82b08a3510aee3ffd19 - Cache ninja/1.11.1#77587f8c8318662ac8e5a7867eb4be21 - Cache pkgconf/2.1.0#27f44583701117b571307cf5b5fe5605 - Cache Resolved version ranges libcurl/[>=7.78.0 <9]: libcurl/8.8.0 zlib/[>=1.2.11 <2]: zlib/1.3.1 ======== Computing necessary packages ======== cpr/1.10.5: Compatible package ID 6da29aec5517b05e82cc36e7f0cea25b756592a1 equal to the default package ID: Skipping it. cpr/1.10.5: Checking 5 compatible configurations cpr/1.10.5: Compatible configurations not found in cache, checking servers cpr/1.10.5: '7c482b127e0f60686b2846e9000db88c8e11666f': compiler.cppstd=17 cpr/1.10.5: '8190a0a48706aaa6e73601f80ccad90dfb634831': compiler.cppstd=20 cpr/1.10.5: '033edebf48b9a193f4775cf79a226f42000d28f2': compiler.cppstd=gnu20 cpr/1.10.5: '4e3c016827f1e0890c20a8270f1157bc59399749': compiler.cppstd=23 cpr/1.10.5: 'a938cbada2ed4cf609e1017660a982a2d845dfe8': compiler.cppstd=gnu23 unleash-client-cpp/1.3.0: Compatible package ID 31826f3ddae6dc65d0a7c1f89aee57b356b02c35 equal to the default package ID: Skipping it. unleash-client-cpp/1.3.0: Checking 5 compatible configurations unleash-client-cpp/1.3.0: Compatible configurations not found in cache, checking servers unleash-client-cpp/1.3.0: '075884ad7d4ee0b37c12ff00532b073d1d95a6ed': compiler.cppstd=17 unleash-client-cpp/1.3.0: 'd1b62f23ae496268defae946797d055b11f8ad07': compiler.cppstd=20 unleash-client-cpp/1.3.0: '1d89d0c5293777c413984d998ab350e8c256ff3f': compiler.cppstd=gnu20 unleash-client-cpp/1.3.0: '8dbe067233297ceac6a97a9cfdc6f0511d43e42d': compiler.cppstd=23 unleash-client-cpp/1.3.0: '0d0154f2b3f41e640700de62e84302ebd7f3ad54': compiler.cppstd=gnu23 Requirements cpr/1.10.5#a227f2a4f0deed3ee1f8b8237477129e:6da29aec5517b05e82cc36e7f0cea25b756592a1 - Missing libcurl/8.8.0#9170903d66d6f6e6795fbb566a403129:da91ff7ebbce6962ceee923568a6793fa42e7ebe - Missing unleash-client-cpp/1.3.0#a4354a616cd5bdb81354825229954522:31826f3ddae6dc65d0a7c1f89aee57b356b02c35 - Missing zlib/1.3.1#f52e03ae3d251dec704634230cd806a2:2ee39e692ca4177b4b689b15bc1f2cfdf8f83706 - Missing Build requirements Skipped binaries nlohmann_json/3.11.3, autoconf/2.71, automake/1.16.5, gnu-config/cci.20210814, libtool/2.4.7, m4/1.4.19, meson/1.2.2, ninja/1.11.1, pkgconf/2.1.0 ======== Computing the build order ======== zlib/1.3.1#f52e03ae3d251dec704634230cd806a2:2ee39e692ca4177b4b689b15bc1f2cfdf8f83706 - Missing libcurl/8.8.0#9170903d66d6f6e6795fbb566a403129:da91ff7ebbce6962ceee923568a6793fa42e7ebe - Missing cpr/1.10.5#a227f2a4f0deed3ee1f8b8237477129e:6da29aec5517b05e82cc36e7f0cea25b756592a1 - Missing unleash-client-cpp/1.3.0#a4354a616cd5bdb81354825229954522:31826f3ddae6dc65d0a7c1f89aee57b356b02c35 - Missing ``` </details> As it can be easily seen, the graph info and build-order commands does not output the expected errors. ### Have you read the CONTRIBUTING guide? - [X] I've read the CONTRIBUTING guide
conan-io/conan
diff --git a/test/functional/toolchains/gnu/autotools/test_android.py b/test/functional/toolchains/gnu/autotools/test_android.py index dc0fc4308..665ece684 100644 --- a/test/functional/toolchains/gnu/autotools/test_android.py +++ b/test/functional/toolchains/gnu/autotools/test_android.py @@ -4,7 +4,6 @@ import textwrap import pytest -from conan.test.assets.sources import gen_function_cpp, gen_function_h from conan.test.utils.tools import TestClient from test.conftest import tools_locations @@ -17,7 +16,7 @@ from test.conftest import tools_locations @pytest.mark.tool("android_ndk") @pytest.mark.tool("autotools") @pytest.mark.skipif(platform.system() != "Darwin", reason="NDK only installed on MAC") -def test_android_meson_toolchain_cross_compiling(arch, expected_arch): +def test_android_autotools_toolchain_cross_compiling(arch, expected_arch): profile_host = textwrap.dedent(""" include(default) diff --git a/test/functional/toolchains/gnu/test_gnutoolchain_android.py b/test/functional/toolchains/gnu/test_gnutoolchain_android.py new file mode 100644 index 000000000..53f38407d --- /dev/null +++ b/test/functional/toolchains/gnu/test_gnutoolchain_android.py @@ -0,0 +1,49 @@ +import os +import platform +import textwrap + +import pytest + +from conan.test.utils.mocks import ConanFileMock +from conan.test.utils.tools import TestClient +from conan.tools.files import replace_in_file +from test.conftest import tools_locations + + [email protected]("arch, expected_arch", [('armv8', 'aarch64'), + ('armv7', 'arm'), + ('x86', 'i386'), + ('x86_64', 'x86_64') + ]) [email protected]("android_ndk") [email protected]("autotools") [email protected](platform.system() != "Darwin", reason="NDK only installed on MAC") +def test_android_gnutoolchain_cross_compiling(arch, expected_arch): + profile_host = textwrap.dedent(""" + include(default) + + [settings] + os = Android + os.api_level = 21 + arch = {arch} + + [conf] + tools.android:ndk_path={ndk_path} + """) + ndk_path = tools_locations["android_ndk"]["system"]["path"][platform.system()] + profile_host = profile_host.format( + arch=arch, + ndk_path=ndk_path + ) + + client = TestClient(path_with_spaces=False) + # FIXME: Change this when we have gnu_lib as template in the new command + client.run("new autotools_lib -d name=hello -d version=1.0") + replace_in_file(ConanFileMock(), os.path.join(client.current_folder, "conanfile.py"), + "AutotoolsToolchain", "GnuToolchain") + client.save({"profile_host": profile_host}) + client.run("build . --profile:build=default --profile:host=profile_host") + libhello = os.path.join("build-release", "src", ".libs", "libhello.a") + # Check binaries architecture + client.run_command('objdump -f "%s"' % libhello) + assert "architecture: %s" % expected_arch in client.out diff --git a/test/integration/command_v2/test_info_build_order.py b/test/integration/command_v2/test_info_build_order.py index b735920e1..24ea16427 100644 --- a/test/integration/command_v2/test_info_build_order.py +++ b/test/integration/command_v2/test_info_build_order.py @@ -76,9 +76,9 @@ def test_info_build_order(): # test html format c.run("graph build-order consumer --build=missing --format=html") assert "<body>" in c.stdout - c.run("graph build-order consumer --order-by=recipe --format=html") + c.run("graph build-order consumer --order-by=recipe --build=missing --format=html") assert "<body>" in c.stdout - c.run("graph build-order consumer --order-by=configuration --format=html") + c.run("graph build-order consumer --order-by=configuration --build=missing --format=html") assert "<body>" in c.stdout @@ -540,6 +540,58 @@ def test_info_build_order_lockfile_location(): assert os.path.exists(os.path.join(c.current_folder, "myconan2.lock")) +def test_build_order_missing_package_check_error(): + c = TestClient() + c.save({"dep/conanfile.py": GenConanfile(), + "pkg/conanfile.py": GenConanfile().with_requires("dep/0.1"), + "consumer/conanfile.txt": "[requires]\npkg/0.1"}) + c.run("export dep --name=dep --version=0.1") + c.run("export pkg --name=pkg --version=0.1") + + exit_code = c.run("graph build-order consumer --build='pkg/*' --order=configuration --format=json", assert_error=True) + bo_json = json.loads(c.stdout) + assert bo_json["order_by"] == "configuration" + assert exit_code != 0 + assert "dep/0.1:da39a3ee5e6b4b0d3255bfef95601890afd80709: Missing binary" in c.out + + result = [ + [ + { + "ref": "dep/0.1#4d670581ccb765839f2239cc8dff8fbd", + "pref": "dep/0.1#4d670581ccb765839f2239cc8dff8fbd:da39a3ee5e6b4b0d3255bfef95601890afd80709", + "package_id": "da39a3ee5e6b4b0d3255bfef95601890afd80709", + "prev": None, + "context": "host", + "binary": "Missing", + "options": [], + "filenames": [], + "depends": [], + "overrides": {}, + "build_args": None, + } + ], + [ + { + "ref": "pkg/0.1#1ac8dd17c0f9f420935abd3b6a8fa032", + "pref": "pkg/0.1#1ac8dd17c0f9f420935abd3b6a8fa032:59205ba5b14b8f4ebc216a6c51a89553021e82c1", + "package_id": "59205ba5b14b8f4ebc216a6c51a89553021e82c1", + "prev": None, + "context": "host", + "binary": "Build", + "options": [], + "filenames": [], + "depends": [ + "dep/0.1#4d670581ccb765839f2239cc8dff8fbd:da39a3ee5e6b4b0d3255bfef95601890afd80709" + ], + "overrides": {}, + "build_args": "--requires=pkg/0.1 --build=pkg/0.1", + } + ], + ] + + assert bo_json["order"] == result + + def test_info_build_order_broken_recipe(): # https://github.com/conan-io/conan/issues/14104 c = TestClient() diff --git a/test/integration/conanfile/conan_data_test.py b/test/integration/conanfile/conan_data_test.py index f81e144e0..64aa2a86f 100644 --- a/test/integration/conanfile/conan_data_test.py +++ b/test/integration/conanfile/conan_data_test.py @@ -442,3 +442,35 @@ def test_trim_conandata_as_hook_without_conandata(raise_if_missing): else: c.run("export . --version=1.0") assert c.exported_recipe_revision() == "a9ec2e5fbb166568d4670a9cd1ef4b26" + + +def test_trim_conandata_anchors(): + """Anchors load correctly, because trim_conandata loads the yaml instead of replacing in place""" + tc = TestClient(light=True) + tc.save({"conanfile.py": textwrap.dedent(""" + from conan import ConanFile + from conan.tools.files import trim_conandata + + class Pkg(ConanFile): + name = "pkg" + def export(self): + trim_conandata(self) + + def generate(self): + self.output.info("x: {}".format(self.conan_data["mapping"][self.version]["x"])) + """), + "conandata.yml": textwrap.dedent(""" + mapping: + "1.0": &anchor + "x": "foo" + "2.0": *anchor + """)}) + tc.run("create . --version=2.0") + assert "x: foo" in tc.out + pkg_layout = tc.exported_layout() + conandata = tc.load(pkg_layout.conandata()) + assert conandata == textwrap.dedent("""\ + mapping: + '2.0': + x: foo + """) diff --git a/test/integration/graph/test_replace_requires.py b/test/integration/graph/test_replace_requires.py index 3d2c385ed..31edd82f2 100644 --- a/test/integration/graph/test_replace_requires.py +++ b/test/integration/graph/test_replace_requires.py @@ -147,3 +147,13 @@ def test_replace_requires_json_format(): assert "pkg/0.1: pkg/0.2" in c.out # The replacement happens graph = json.loads(c.stdout) assert graph["graph"]["replaced_requires"] == {"pkg/0.1": "pkg/0.2"} + + +def test_replace_requires_test_requires(): + c = TestClient(light=True) + c.save({"gtest/conanfile.py": GenConanfile("gtest", "0.2"), + "app/conanfile.py": GenConanfile().with_test_requires("gtest/0.1"), + "profile": f"[replace_requires]\ngtest/0.1: gtest/0.2"}) + c.run("create gtest") + c.run("install app -pr=profile") + assert "gtest/0.1: gtest/0.2" in c.out # The replacement happens diff --git a/test/integration/toolchains/gnu/test_gnutoolchain.py b/test/integration/toolchains/gnu/test_gnutoolchain.py index d35d45b04..e93583ec5 100644 --- a/test/integration/toolchains/gnu/test_gnutoolchain.py +++ b/test/integration/toolchains/gnu/test_gnutoolchain.py @@ -37,7 +37,7 @@ def test_extra_flags_via_conf(os_): "profile": profile}) client.run("install . --profile:build=profile --profile:host=profile") toolchain = client.load( - "conanautotoolstoolchain{}".format('.bat' if os_ == "Windows" else '.sh')) + "conangnutoolchain{}".format('.bat' if os_ == "Windows" else '.sh')) if os_ == "Windows": assert 'set "CPPFLAGS=%CPPFLAGS% -DNDEBUG -DDEF1 -DDEF2"' in toolchain assert 'set "CXXFLAGS=%CXXFLAGS% -O3 --flag1 --flag2"' in toolchain @@ -88,7 +88,7 @@ def test_extra_flags_order(): client.save({"conanfile.py": conanfile, "profile": profile}) client.run('install . -pr=./profile') toolchain = client.load( - "conanautotoolstoolchain{}".format('.bat' if platform.system() == "Windows" else '.sh')) + "conangnutoolchain{}".format('.bat' if platform.system() == "Windows" else '.sh')) assert '-Dextra_defines -Ddefines' in toolchain assert 'extra_cxxflags cxxflags' in toolchain @@ -113,7 +113,7 @@ def test_autotools_custom_environment(): client.save({"conanfile.py": conanfile}) client.run("install . -s:b os=Linux -s:h os=Linux") - content = load(os.path.join(client.current_folder, "conanautotoolstoolchain.sh")) + content = load(os.path.join(client.current_folder, "conangnutoolchain.sh")) assert 'export FOO="BAR"' in content @@ -141,7 +141,7 @@ def test_linker_scripts_via_conf(os_): "profile": profile}) client.run("install . --profile:build=profile --profile:host=profile") toolchain = client.load( - "conanautotoolstoolchain{}".format('.bat' if os_ == "Windows" else '.sh')) + "conangnutoolchain{}".format('.bat' if os_ == "Windows" else '.sh')) if os_ == "Windows": assert 'set "LDFLAGS=%LDFLAGS% --flag5 --flag6 -T\'/linker/scripts/flash.ld\' -T\'/linker/scripts/extra_data.ld\'"' in toolchain else: @@ -255,7 +255,7 @@ def test_toolchain_and_compilers_build_context(): generators = "GnuToolchain" def build(self): - toolchain = os.path.join(self.generators_folder, "conanautotoolstoolchain.sh") + toolchain = os.path.join(self.generators_folder, "conangnutoolchain.sh") content = load(self, toolchain) assert 'export CC="clang"' in content assert 'export CXX="clang++"' in content @@ -274,11 +274,14 @@ def test_toolchain_and_compilers_build_context(): tool_requires = "tool/1.0" def build(self): - toolchain = os.path.join(self.generators_folder, "conanautotoolstoolchain.sh") + toolchain = os.path.join(self.generators_folder, "conangnutoolchain.sh") content = load(self, toolchain) assert 'export CC="gcc"' in content assert 'export CXX="g++"' in content assert 'export RC="windres"' in content + # Issue: https://github.com/conan-io/conan/issues/15486 + assert 'export CC_FOR_BUILD="clang"' in content + assert 'export CXX_FOR_BUILD="clang++"' in content """) client = TestClient() client.save({ @@ -376,7 +379,7 @@ def test_msvc_profile_defaults(): generators = "GnuToolchain" def build(self): - toolchain = os.path.join(self.generators_folder, "conanautotoolstoolchain.bat") + toolchain = os.path.join(self.generators_folder, "conangnutoolchain.bat") content = load(self, toolchain) # Default values and conf ones assert r'set "CC=clang"' in content # conf value has precedence @@ -415,7 +418,7 @@ def test_msvc_profile_defaults(): tc.generate() def build(self): - toolchain = os.path.join(self.generators_folder, "conanautotoolstoolchain.bat") + toolchain = os.path.join(self.generators_folder, "conangnutoolchain.bat") content = load(self, toolchain) # Default values assert r'set "CC=compile clang"' in content
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 7 }
2.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "conans/requirements.txt", "conans/requirements_server.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
beautifulsoup4==4.13.3 bottle==0.12.25 certifi==2025.1.31 charset-normalizer==3.4.1 colorama==0.4.6 -e git+https://github.com/conan-io/conan.git@a474e3d67c1a0acfc4f8fa7db2f71de4bd089466#egg=conan distro==1.8.0 docker==5.0.3 exceptiongroup==1.2.2 execnet==2.1.1 fasteners==0.19 idna==3.10 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 mock==1.3.0 packaging==24.2 parameterized==0.9.0 patch-ng==1.17.4 pbr==6.1.1 pluggy==1.5.0 pluginbase==1.0.1 PyJWT==2.10.1 pytest==7.4.4 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 six==1.17.0 soupsieve==2.6 tomli==2.2.1 typing_extensions==4.13.0 urllib3==1.26.20 waitress==3.0.2 WebOb==1.8.9 websocket-client==1.8.0 WebTest==2.0.35
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - beautifulsoup4==4.13.3 - bottle==0.12.25 - certifi==2025.1.31 - charset-normalizer==3.4.1 - colorama==0.4.6 - conan==2.6.0.dev0 - distro==1.8.0 - docker==5.0.3 - exceptiongroup==1.2.2 - execnet==2.1.1 - fasteners==0.19 - idna==3.10 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - mock==1.3.0 - packaging==24.2 - parameterized==0.9.0 - patch-ng==1.17.4 - pbr==6.1.1 - pluggy==1.5.0 - pluginbase==1.0.1 - pyjwt==2.10.1 - pytest==7.4.4 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - six==1.17.0 - soupsieve==2.6 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==1.26.20 - waitress==3.0.2 - webob==1.8.9 - websocket-client==1.8.0 - webtest==2.0.35 prefix: /opt/conda/envs/conan
[ "test/integration/command_v2/test_info_build_order.py::test_build_order_missing_package_check_error", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_extra_flags_via_conf[Macos]", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_extra_flags_via_conf[Linux]", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_extra_flags_via_conf[Windows]", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_extra_flags_order", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_autotools_custom_environment", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_linker_scripts_via_conf[Linux]", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_linker_scripts_via_conf[Windows]", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_toolchain_and_compilers_build_context", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_msvc_profile_defaults" ]
[]
[ "test/integration/command_v2/test_info_build_order.py::test_info_build_order", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_configuration", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_configuration_text_formatter", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_build_require", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_options", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_merge_multi_product", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_merge_multi_product_configurations", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_merge_conditionals", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_lockfile_location", "test/integration/command_v2/test_info_build_order.py::test_info_build_order_broken_recipe", "test/integration/command_v2/test_info_build_order.py::TestBuildOrderReduce::test_build_order_reduce[recipe]", "test/integration/command_v2/test_info_build_order.py::TestBuildOrderReduce::test_build_order_reduce[configuration]", "test/integration/command_v2/test_info_build_order.py::TestBuildOrderReduce::test_build_order_merge_reduce[recipe]", "test/integration/command_v2/test_info_build_order.py::TestBuildOrderReduce::test_build_order_merge_reduce[configuration]", "test/integration/command_v2/test_info_build_order.py::TestBuildOrderReduce::test_error_reduced", "test/integration/command_v2/test_info_build_order.py::TestBuildOrderReduce::test_error_different_orders", "test/integration/conanfile/conan_data_test.py::ConanDataTest::test_conan_data_as_source_newtools", "test/integration/conanfile/conan_data_test.py::ConanDataTest::test_conan_data_development_flow", "test/integration/conanfile/conan_data_test.py::ConanDataTest::test_conan_data_everywhere", "test/integration/conanfile/conan_data_test.py::ConanDataTest::test_conan_exports_kept", "test/integration/conanfile/conan_data_test.py::ConanDataTest::test_invalid_yml", "test/integration/conanfile/conan_data_test.py::TestConanDataUpdate::test_conandata_update", "test/integration/conanfile/conan_data_test.py::TestConanDataUpdate::test_conandata_update_error", "test/integration/conanfile/conan_data_test.py::TestConanDataUpdate::test_conandata_create_if_not_exist", "test/integration/conanfile/conan_data_test.py::test_conandata_trim", "test/integration/conanfile/conan_data_test.py::test_trim_conandata_as_hook", "test/integration/conanfile/conan_data_test.py::test_trim_conandata_as_hook_without_conandata[True]", "test/integration/conanfile/conan_data_test.py::test_trim_conandata_as_hook_without_conandata[False]", "test/integration/conanfile/conan_data_test.py::test_trim_conandata_anchors", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/1.3-dep/*-dep/1.1-dep/1.1]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/[>=1.0", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/1.3-dep/*-dep/*@system-dep/1.3@system]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/1.3@comp/stable-dep/*@*/*-dep/*@system/*-dep/1.3@system/stable]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/1.1-dep/1.1-dep/1.1@system-dep/1.1@system]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/1.1@comp-dep/1.1@*-dep/1.1@*/stable-dep/1.1@comp/stable]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/1.0-dep/*-depng/*-depng/1.0]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/1.3-dep/1.1-dep/1.1@system-dep/1.3]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/1.3-dep/*@comp-dep/*@system-dep/1.3]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[False-dep/[>=1.3", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/1.3-dep/*-dep/1.1-dep/1.1]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/[>=1.0", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/1.3-dep/*-dep/*@system-dep/1.3@system]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/1.3@comp/stable-dep/*@*/*-dep/*@system/*-dep/1.3@system/stable]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/1.1-dep/1.1-dep/1.1@system-dep/1.1@system]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/1.1@comp-dep/1.1@*-dep/1.1@*/stable-dep/1.1@comp/stable]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/1.0-dep/*-depng/*-depng/1.0]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/1.3-dep/1.1-dep/1.1@system-dep/1.3]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/1.3-dep/*@comp-dep/*@system-dep/1.3]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_alternative[True-dep/[>=1.3", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/1.3-dep/*-dep/1.1-dep/1.1]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/[>=1.0", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/1.3-dep/*-dep/*@system-dep/1.3@system]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/1.3@comp/stable-dep/*@*/*-dep/*@system/*-dep/1.3@system/stable]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/1.1-dep/1.1-dep/1.1@system-dep/1.1@system]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/1.1@comp-dep/1.1@*-dep/1.1@*/stable-dep/1.1@comp/stable]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/1.0-dep/*-depng/*-depng/1.0]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/1.3-dep/1.1-dep/1.1@system-dep/1.3]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/1.3-dep/*@comp-dep/*@system-dep/1.3]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[False-dep/[>=1.3", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/1.3-dep/*-dep/1.1-dep/1.1]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/[>=1.0", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/1.3-dep/*-dep/*@system-dep/1.3@system]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/1.3@comp/stable-dep/*@*/*-dep/*@system/*-dep/1.3@system/stable]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/1.1-dep/1.1-dep/1.1@system-dep/1.1@system]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/1.1@comp-dep/1.1@*-dep/1.1@*/stable-dep/1.1@comp/stable]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/1.0-dep/*-depng/*-depng/1.0]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/1.3-dep/1.1-dep/1.1@system-dep/1.3]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/1.3-dep/*@comp-dep/*@system-dep/1.3]", "test/integration/graph/test_replace_requires.py::TestReplaceRequires::test_diamond[True-dep/[>=1.3", "test/integration/graph/test_replace_requires.py::test_replace_requires_errors[pkg-pkg/0.1]", "test/integration/graph/test_replace_requires.py::test_replace_requires_errors[pkg/*-pkg]", "test/integration/graph/test_replace_requires.py::test_replace_requires_errors[pkg/*:pid1-pkg/0.1]", "test/integration/graph/test_replace_requires.py::test_replace_requires_errors[pkg/*:pid1-pkg/0.1:pid2]", "test/integration/graph/test_replace_requires.py::test_replace_requires_errors[pkg/*-pkg/0.1:pid2]", "test/integration/graph/test_replace_requires.py::test_replace_requires_errors[:-]", "test/integration/graph/test_replace_requires.py::test_replace_requires_errors[pkg/version:pid-]", "test/integration/graph/test_replace_requires.py::test_replace_requires_errors[pkg/version:pid-:]", "test/integration/graph/test_replace_requires.py::test_replace_requires_invalid_requires_errors", "test/integration/graph/test_replace_requires.py::test_replace_requires_json_format", "test/integration/graph/test_replace_requires.py::test_replace_requires_test_requires", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_not_none_values", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_set_prefix", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_unknown_compiler", "test/integration/toolchains/gnu/test_gnutoolchain.py::test_autotools_crossbuild_ux" ]
[]
MIT License
18,610
4,639
[ "conan/cli/command.py", "conan/cli/commands/graph.py", "conan/cli/formatters/graph/build_order_html.py", "conan/cli/formatters/graph/graph.py", "conan/cli/formatters/graph/graph_info_text.py", "conan/tools/gnu/gnutoolchain.py", "conans/client/graph/install_graph.py" ]
python-pillow__Pillow-8110
e7c1da3cc8a26b821e0a4ec2d4651d62271f00c5
2024-06-06 11:18:28
d87c1c148778be35ec29194434315e39eb33bedc
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index 1629c090f..ac5b63c1b 100644 --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -1663,10 +1663,14 @@ def _save(im, fp, filename): legacy_ifd = im.tag.to_v2() supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})} - if SAMPLEFORMAT in supplied_tags: - # SAMPLEFORMAT is determined by the image format and should not be copied - # from legacy_ifd. - del supplied_tags[SAMPLEFORMAT] + for tag in ( + # IFD offset that may not be correct in the saved image + EXIFIFD, + # Determined by the image format and should not be copied from legacy_ifd. + SAMPLEFORMAT, + ): + if tag in supplied_tags: + del supplied_tags[tag] # additions written by Greg Couch, [email protected] # inspired by image-sig posting from Kevin Cazabon, [email protected]
save() produces an unreadable TIFF `Image.open('in.tif').save('out.tif')` produces `out.tif` which is unreadable. `Image.__version__ == '10.1.0'` [in.tif.zip](https://github.com/user-attachments/files/15568097/in.tif.zip)
python-pillow/Pillow
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index fe9d017c0..f491f9875 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -685,13 +685,18 @@ class TestFileLibTiff(LibTiffTestCase): assert reloaded.tag_v2[530] == (1, 1) assert reloaded.tag_v2[532] == (0, 255, 128, 255, 128, 255) - def test_exif_ifd(self, tmp_path: Path) -> None: - outfile = str(tmp_path / "temp.tif") + def test_exif_ifd(self) -> None: + out = io.BytesIO() with Image.open("Tests/images/tiff_adobe_deflate.tif") as im: assert im.tag_v2[34665] == 125456 - im.save(outfile) + im.save(out, "TIFF") - with Image.open(outfile) as reloaded: + with Image.open(out) as reloaded: + assert 34665 not in reloaded.tag_v2 + + im.save(out, "TIFF", tiffinfo={34665: 125456}) + + with Image.open(out) as reloaded: if Image.core.libtiff_support_custom_tags: assert reloaded.tag_v2[34665] == 125456
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
10.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest pytest-cov pytest-timeout", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc libjpeg-dev zlib1g-dev libtiff5-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev libharfbuzz-dev libfribidi-dev libxcb1-dev" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work -e git+https://github.com/python-pillow/Pillow.git@e7c1da3cc8a26b821e0a4ec2d4651d62271f00c5#egg=pillow pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 pytest-timeout==2.3.1 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: Pillow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - pillow==10.4.0.dev0 - pytest-cov==6.0.0 - pytest-timeout==2.3.1 prefix: /opt/conda/envs/Pillow
[ "Tests/test_file_libtiff.py::TestFileLibTiff::test_exif_ifd" ]
[]
[ "Tests/test_file_libtiff.py::TestFileLibTiff::test_version", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_large", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_tiff_file", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_tiff_bytesio", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_non_disk_file_object", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_eq_png", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_fillorder_eq_png", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_write", "Tests/test_file_libtiff.py::TestFileLibTiff::test_adobe_deflate_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_write_metadata[False]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_write_metadata[True]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_additional_metadata", "Tests/test_file_libtiff.py::TestFileLibTiff::test_custom_metadata[True]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_custom_metadata[False]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_osubfiletype", "Tests/test_file_libtiff.py::TestFileLibTiff::test_subifd", "Tests/test_file_libtiff.py::TestFileLibTiff::test_xmlpacket_tag", "Tests/test_file_libtiff.py::TestFileLibTiff::test_int_dpi", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g3_compression", "Tests/test_file_libtiff.py::TestFileLibTiff::test_little_endian", "Tests/test_file_libtiff.py::TestFileLibTiff::test_big_endian", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_string_info", "Tests/test_file_libtiff.py::TestFileLibTiff::test_12bit_rawmode", "Tests/test_file_libtiff.py::TestFileLibTiff::test_blur", "Tests/test_file_libtiff.py::TestFileLibTiff::test_compressions", "Tests/test_file_libtiff.py::TestFileLibTiff::test_tiff_jpeg_compression", "Tests/test_file_libtiff.py::TestFileLibTiff::test_tiff_deflate_compression", "Tests/test_file_libtiff.py::TestFileLibTiff::test_quality", "Tests/test_file_libtiff.py::TestFileLibTiff::test_cmyk_save", "Tests/test_file_libtiff.py::TestFileLibTiff::test_palette_save[im0]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_palette_save[im1]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_bw_compression_w_rgb[tiff_ccitt]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_bw_compression_w_rgb[group3]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_bw_compression_w_rgb[group4]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_fp_leak", "Tests/test_file_libtiff.py::TestFileLibTiff::test_multipage", "Tests/test_file_libtiff.py::TestFileLibTiff::test_multipage_nframes", "Tests/test_file_libtiff.py::TestFileLibTiff::test_multipage_seek_backwards", "Tests/test_file_libtiff.py::TestFileLibTiff::test__next", "Tests/test_file_libtiff.py::TestFileLibTiff::test_4bit", "Tests/test_file_libtiff.py::TestFileLibTiff::test_gray_semibyte_per_pixel", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_bytesio", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_ycbcr", "Tests/test_file_libtiff.py::TestFileLibTiff::test_crashing_metadata", "Tests/test_file_libtiff.py::TestFileLibTiff::test_page_number_x_0", "Tests/test_file_libtiff.py::TestFileLibTiff::test_fd_duplication", "Tests/test_file_libtiff.py::TestFileLibTiff::test_read_icc", "Tests/test_file_libtiff.py::TestFileLibTiff::test_write_icc[True]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_write_icc[False]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_multipage_compression", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_tiff_with_jpegtables", "Tests/test_file_libtiff.py::TestFileLibTiff::test_16bit_RGB_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_16bit_RGBa_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_gimp_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_sampleformat", "Tests/test_file_libtiff.py::TestFileLibTiff::test_sampleformat_write", "Tests/test_file_libtiff.py::TestFileLibTiff::test_lzma", "Tests/test_file_libtiff.py::TestFileLibTiff::test_webp", "Tests/test_file_libtiff.py::TestFileLibTiff::test_lzw", "Tests/test_file_libtiff.py::TestFileLibTiff::test_strip_cmyk_jpeg", "Tests/test_file_libtiff.py::TestFileLibTiff::test_strip_cmyk_16l_jpeg", "Tests/test_file_libtiff.py::TestFileLibTiff::test_strip_ycbcr_jpeg_2x2_sampling", "Tests/test_file_libtiff.py::TestFileLibTiff::test_strip_ycbcr_jpeg_1x1_sampling", "Tests/test_file_libtiff.py::TestFileLibTiff::test_tiled_cmyk_jpeg", "Tests/test_file_libtiff.py::TestFileLibTiff::test_tiled_ycbcr_jpeg_1x1_sampling", "Tests/test_file_libtiff.py::TestFileLibTiff::test_tiled_ycbcr_jpeg_2x2_sampling", "Tests/test_file_libtiff.py::TestFileLibTiff::test_strip_planar_rgb", "Tests/test_file_libtiff.py::TestFileLibTiff::test_tiled_planar_rgb", "Tests/test_file_libtiff.py::TestFileLibTiff::test_tiled_planar_16bit_RGB", "Tests/test_file_libtiff.py::TestFileLibTiff::test_strip_planar_16bit_RGB", "Tests/test_file_libtiff.py::TestFileLibTiff::test_tiled_planar_16bit_RGBa", "Tests/test_file_libtiff.py::TestFileLibTiff::test_strip_planar_16bit_RGBa", "Tests/test_file_libtiff.py::TestFileLibTiff::test_block_tile_tags[None]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_block_tile_tags[jpeg]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_old_style_jpeg", "Tests/test_file_libtiff.py::TestFileLibTiff::test_open_missing_samplesperpixel", "Tests/test_file_libtiff.py::TestFileLibTiff::test_wrong_bits_per_sample[tiff_wrong_bits_per_sample.tiff-RGBA-size0-tile0]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_wrong_bits_per_sample[tiff_wrong_bits_per_sample_2.tiff-RGB-size1-tile1]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_wrong_bits_per_sample[tiff_wrong_bits_per_sample_3.tiff-RGBA-size2-tile2]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_no_rows_per_strip", "Tests/test_file_libtiff.py::TestFileLibTiff::test_orientation", "Tests/test_file_libtiff.py::TestFileLibTiff::test_exif_transpose", "Tests/test_file_libtiff.py::TestFileLibTiff::test_sampleformat_not_corrupted", "Tests/test_file_libtiff.py::TestFileLibTiff::test_realloc_overflow", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_multistrip[tiff_adobe_deflate]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_multistrip[jpeg]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_single_strip[True]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_single_strip[False]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_zero[tiff_adobe_deflate]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_zero[None]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_many_compressed", "Tests/test_file_libtiff.py::TestFileLibTiff::test_get_child_images[Tests/images/hopper.tif-sizes0]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_get_child_images[Tests/images/child_ifd.tiff-sizes1]", "Tests/test_file_libtiff.py::TestFileLibTiff::test_get_child_images[Tests/images/child_ifd_jpeg.tiff-sizes2]" ]
[]
MIT-CMU License
18,612
288
[ "src/PIL/TiffImagePlugin.py" ]
lincc-frameworks__nested-pandas-105
615258097faba3ced8ae4dbce517d62526c680a1
2024-06-06 20:26:41
975fbc88de84b6d8d9ae309f71ae3f0b96831818
diff --git a/src/nested_pandas/nestedframe/core.py b/src/nested_pandas/nestedframe/core.py index 6142238..b3be03e 100644 --- a/src/nested_pandas/nestedframe/core.py +++ b/src/nested_pandas/nestedframe/core.py @@ -201,7 +201,6 @@ class NestedFrame(pd.DataFrame): """resolves the target layer for a given set of dropna kwargs""" nested_cols = self.nested_columns - columns = self.columns # first check the subset kwarg input subset_target = [] @@ -210,13 +209,15 @@ class NestedFrame(pd.DataFrame): subset = [subset] for col in subset: - col = col.split(".")[0] - if col in nested_cols: - subset_target.append(col) - elif col in columns: + # Without a ".", always assume base layer + if "." not in col: subset_target.append("base") else: - raise ValueError(f"Column name {col} not found in any base or nested columns") + layer, col = col.split(".") + if layer in nested_cols: + subset_target.append(layer) + else: + raise ValueError(f"layer '{layer}' not found in the base columns") # Check for 1 target subset_target = np.unique(subset_target)
Allow Dropna to work on nested columns as base columns **Bug report** Current dropna logic assumes that if the user invokes a nested layer, that it then must be trying to dropna within the rows of that nested layer. We should fix dropna to also work with nested columns as base columns, which is particularly useful when filtering out base rows that have empty data in a nested layer. Here's a reproducible sample: ``` # Test dropna on nested columns import nested_pandas as npd from nested_pandas.datasets import generate_data nf = generate_data(10,100, seed=1).query("nested.t>19.75") nf.dropna(subset=["nested"]) ``` which currently fails: ``` --------------------------------------------------------------------------- KeyError Traceback (most recent call last) /var/folders/lc/dws63_cs5gz5mf8s869hjpx40000gn/T/ipykernel_52322/3221593222.py in ?() 2 import nested_pandas as npd 3 4 from nested_pandas.datasets import generate_data 5 nf = generate_data(10,100, seed=1).query("nested.t>19.75") ----> 6 nf.dropna(subset=["nested"]) ~/lincc/nested-pandas/src/nested_pandas/nestedframe/core.py in ?(self, axis, how, thresh, on_nested, subset, inplace, ignore_index) 335 return self 336 # Or if not inplace 337 new_df = self.copy() 338 new_df[target] = packer.pack_flat( --> 339 new_df[target] 340 .nest.to_flat() 341 .dropna( 342 axis=axis, ~/miniforge3/envs/ray310/lib/python3.10/site-packages/pandas/core/frame.py in ?(self, axis, how, thresh, subset, inplace, ignore_index) 6653 ax = self._get_axis(agg_axis) 6654 indices = ax.get_indexer_for(subset) 6655 check = indices == -1 6656 if check.any(): -> 6657 raise KeyError(np.array(subset)[check].tolist()) 6658 agg_obj = self.take(indices, axis=agg_axis) 6659 6660 if thresh is not lib.no_default: KeyError: ['nested'] ``` **Before submitting** Please check the following: - [x] I have described the situation in which the bug arose, including what code was executed, information about my environment, and any applicable data others will need to reproduce the problem. - [x] I have included available evidence of the unexpected behavior (including error messages, screenshots, and/or plots) as well as a descriprion of what I expected instead. - [ ] If I have a solution in mind, I have provided an explanation and/or pseudocode and/or task list.
lincc-frameworks/nested-pandas
diff --git a/tests/nested_pandas/nestedframe/test_nestedframe.py b/tests/nested_pandas/nestedframe/test_nestedframe.py index a9c9e15..66931cc 100644 --- a/tests/nested_pandas/nestedframe/test_nestedframe.py +++ b/tests/nested_pandas/nestedframe/test_nestedframe.py @@ -3,6 +3,7 @@ import pandas as pd import pyarrow as pa import pytest from nested_pandas import NestedFrame +from nested_pandas.datasets import generate_data from pandas.testing import assert_frame_equal @@ -203,6 +204,15 @@ def test_dropna(): assert len(dn_hierarchical["nested"].nest.to_flat() == 8) +def test_dropna_layer_as_base_column(): + """Test that a nested column still works as a top level column for dropna""" + nf = generate_data(10, 100, seed=1).query("nested.t>19.75") + nf = nf.dropna(subset=["nested"]) + + # make sure rows have been dropped as expected + assert len(nf) == 6 + + def test_dropna_inplace_base(): """Test in-place behavior of dropna""" @@ -362,55 +372,3 @@ def test_reduce(): assert result.index.name == "idx" for i in range(len(result)): assert result["offset_avg"].values[i] == expected_offset_avg[i] - - -def test_reduce_duplicated_cols(): - """Tests nf.reduce() to correctly handle duplicated column names.""" - nf = NestedFrame( - data={"a": [1, 2, 3], "b": [2, 4, 6]}, - index=pd.Index([0, 1, 2], name="idx"), - ) - - to_pack = pd.DataFrame( - data={ - "time": [1, 2, 3, 1, 2, 4, 2, 1, 4], - "c": [0, 2, 4, 10, 4, 3, 1, 4, 1], - "d": [5, 4, 7, 5, 3, 1, 9, 3, 4], - }, - index=pd.Index([0, 0, 0, 1, 1, 1, 2, 2, 2], name="idx"), - ) - - to_pack2 = pd.DataFrame( - data={ - "time2": [ - 1, - 2, - 3, - 1, - 2, - 3, - 1, - 2, - 4, - ], # TODO: fix duplicate name in join once to_list subset bug fixed - "e": [2, 9, 4, 1, 23, 3, 1, 4, 1], - "f": [5, 4, 7, 5, 3, 25, 9, 3, 4], - }, - index=pd.Index([0, 0, 0, 1, 1, 1, 2, 2, 2], name="idx"), - ) - - # Add two nested layers to pack into our dataframe - nf = nf.add_nested(to_pack, "packed").add_nested(to_pack2, "packed2") - - def cols_allclose(col1, col2): - return pd.Series([np.allclose(col1, col2)], index=["allclose"]) - - result = nf.reduce(cols_allclose, "packed.time", "packed2.f") - assert_frame_equal( - result, pd.DataFrame({"allclose": [False, False, False]}, index=pd.Index([0, 1, 2], name="idx")) - ) - - result = nf.reduce(cols_allclose, "packed.c", "packed.c") - assert_frame_equal( - result, pd.DataFrame({"allclose": [True, True, True]}, index=pd.Index([0, 1, 2], name="idx")) - )
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
accessible-pygments==0.0.5 alabaster==0.7.16 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 astroid==3.3.9 asttokens==3.0.0 asv==0.6.3 asv_runner==0.2.1 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 bleach==6.2.0 build==1.2.2.post1 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 comm==0.2.2 coverage==7.8.0 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fqdn==1.5.1 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 identify==2.6.9 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 jupytext==1.16.7 markdown-it-py==3.0.0 MarkupSafe==3.0.2 matplotlib-inline==0.1.7 mdit-py-plugins==0.4.2 mdurl==0.1.2 mistune==3.1.3 mypy==1.15.0 mypy-extensions==1.0.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbsphinx==0.9.7 nest-asyncio==1.6.0 -e git+https://github.com/lincc-frameworks/nested-pandas.git@615258097faba3ced8ae4dbce517d62526c680a1#egg=nested_pandas nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pycparser==2.22 pydata-sphinx-theme==0.15.4 Pygments==2.19.1 Pympler==1.1 pyproject_hooks==1.2.0 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 ruff==0.11.2 Send2Trash==1.8.3 six==1.17.0 sniffio==1.3.1 snowballstemmer==2.2.0 soupsieve==2.6 Sphinx==7.4.7 sphinx-autoapi==3.6.0 sphinx-book-theme==1.1.4 sphinx-copybutton==0.5.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 stack-data==0.6.3 stdlib-list==0.11.1 tabulate==0.9.0 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 zipp==3.21.0
name: nested-pandas channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - accessible-pygments==0.0.5 - alabaster==0.7.16 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - astroid==3.3.9 - asttokens==3.0.0 - asv==0.6.3 - asv-runner==0.2.1 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - build==1.2.2.post1 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - comm==0.2.2 - coverage==7.8.0 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fqdn==1.5.1 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - jupytext==1.16.7 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - matplotlib-inline==0.1.7 - mdit-py-plugins==0.4.2 - mdurl==0.1.2 - mistune==3.1.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbsphinx==0.9.7 - nest-asyncio==1.6.0 - nested-pandas==0.1.2.dev6+g6152580 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pycparser==2.22 - pydata-sphinx-theme==0.15.4 - pygments==2.19.1 - pympler==1.1 - pyproject-hooks==1.2.0 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - ruff==0.11.2 - send2trash==1.8.3 - six==1.17.0 - sniffio==1.3.1 - snowballstemmer==2.2.0 - soupsieve==2.6 - sphinx==7.4.7 - sphinx-autoapi==3.6.0 - sphinx-book-theme==1.1.4 - sphinx-copybutton==0.5.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - stack-data==0.6.3 - stdlib-list==0.11.1 - tabulate==0.9.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - zipp==3.21.0 prefix: /opt/conda/envs/nested-pandas
[ "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna_layer_as_base_column" ]
[ "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna_inplace_base", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna_inplace_nested", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_dropna_errors" ]
[ "tests/nested_pandas/nestedframe/test_nestedframe.py::test_nestedframe_construction", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_all_columns", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_nested_columns", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_is_known_hierarchical_column", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_with_flat_df", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_with_flat_df_and_mismatched_index", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_with_series", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_with_series_and_mismatched_index", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_add_nested_for_empty_df", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_query", "tests/nested_pandas/nestedframe/test_nestedframe.py::test_reduce" ]
[]
MIT License
18,617
325
[ "src/nested_pandas/nestedframe/core.py" ]
tobymao__sqlglot-3612
664ae5c3ecc21553e7a5909d7811e5da3a9db1d9
2024-06-06 21:02:33
47472d9c0a27070fd5f4f9b8c12a8bd8c86b1de1
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py index 25a02b0d..7ad1f90e 100644 --- a/sqlglot/dialects/postgres.py +++ b/sqlglot/dialects/postgres.py @@ -8,6 +8,7 @@ from sqlglot.dialects.dialect import ( Dialect, JSON_EXTRACT_TYPE, any_value_to_max_sql, + binary_from_function, bool_xor_sql, datestrtodate_sql, build_formatted_time, @@ -329,6 +330,7 @@ class Postgres(Dialect): "REGTYPE": TokenType.OBJECT_IDENTIFIER, "FLOAT": TokenType.DOUBLE, } + KEYWORDS.pop("DIV") SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, @@ -347,6 +349,9 @@ class Postgres(Dialect): FUNCTIONS = { **parser.Parser.FUNCTIONS, "DATE_TRUNC": build_timestamp_trunc, + "DIV": lambda args: exp.cast( + binary_from_function(exp.IntDiv)(args), exp.DataType.Type.DECIMAL + ), "GENERATE_SERIES": _build_generate_series, "JSON_EXTRACT_PATH": build_json_extract_path(exp.JSONExtract), "JSON_EXTRACT_PATH_TEXT": build_json_extract_path(exp.JSONExtractScalar), @@ -494,6 +499,7 @@ class Postgres(Dialect): exp.DateSub: _date_add_sql("-"), exp.Explode: rename_func("UNNEST"), exp.GroupConcat: _string_agg_sql, + exp.IntDiv: rename_func("DIV"), exp.JSONExtract: _json_extract_sql("JSON_EXTRACT_PATH", "->"), exp.JSONExtractScalar: _json_extract_sql("JSON_EXTRACT_PATH_TEXT", "->>"), exp.JSONBExtract: lambda self, e: self.binary(e, "#>"), @@ -621,3 +627,12 @@ class Postgres(Dialect): return f"{self.expressions(expression, flat=True)}[{values}]" return "ARRAY" return super().datatype_sql(expression) + + def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: + this = expression.this + + # Postgres casts DIV() to decimal for transpilation but when roundtripping it's superfluous + if isinstance(this, exp.IntDiv) and expression.to == exp.DataType.build("decimal"): + return self.sql(this) + + return super().cast_sql(expression, safe_prefix=safe_prefix) diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py index df6985df..0dd372e7 100644 --- a/sqlglot/dialects/redshift.py +++ b/sqlglot/dialects/redshift.py @@ -115,6 +115,12 @@ class Redshift(Postgres): self._retreat(index) return None + def _parse_column(self) -> t.Optional[exp.Expression]: + column = super()._parse_column() + if column: + column.set("join_mark", self._match(TokenType.JOIN_MARKER)) + return column + class Tokenizer(Postgres.Tokenizer): BIT_STRINGS = [] HEX_STRINGS = [] @@ -128,6 +134,7 @@ class Redshift(Postgres): "UNLOAD": TokenType.COMMAND, "VARBYTE": TokenType.VARBINARY, "MINUS": TokenType.EXCEPT, + "(+)": TokenType.JOIN_MARKER, } KEYWORDS.pop("VALUES") @@ -148,6 +155,7 @@ class Redshift(Postgres): HEX_FUNC = "TO_HEX" # Redshift doesn't have `WITH` as part of their with_properties so we remove it WITH_PROPERTIES_PREFIX = " " + COLUMN_JOIN_MARKS_SUPPORTED = True TYPE_MAPPING = { **Postgres.Generator.TYPE_MAPPING, diff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py index e828b9bb..0212352d 100644 --- a/sqlglot/dialects/spark.py +++ b/sqlglot/dialects/spark.py @@ -41,6 +41,21 @@ def _build_datediff(args: t.List) -> exp.Expression: ) +def _build_dateadd(args: t.List) -> exp.Expression: + expression = seq_get(args, 1) + + if len(args) == 2: + # DATE_ADD(startDate, numDays INTEGER) + # https://docs.databricks.com/en/sql/language-manual/functions/date_add.html + return exp.TsOrDsAdd( + this=seq_get(args, 0), expression=expression, unit=exp.Literal.string("DAY") + ) + + # DATE_ADD / DATEADD / TIMESTAMPADD(unit, value integer, expr) + # https://docs.databricks.com/en/sql/language-manual/functions/date_add3.html + return exp.TimestampAdd(this=seq_get(args, 2), expression=expression, unit=seq_get(args, 0)) + + def _normalize_partition(e: exp.Expression) -> exp.Expression: """Normalize the expressions in PARTITION BY (<expression>, <expression>, ...)""" if isinstance(e, str): @@ -50,6 +65,30 @@ def _normalize_partition(e: exp.Expression) -> exp.Expression: return e +def _dateadd_sql(self: Spark.Generator, expression: exp.TsOrDsAdd | exp.TimestampAdd) -> str: + if not expression.unit or ( + isinstance(expression, exp.TsOrDsAdd) and expression.text("unit").upper() == "DAY" + ): + # Coming from Hive/Spark2 DATE_ADD or roundtripping the 2-arg version of Spark3/DB + return self.func("DATE_ADD", expression.this, expression.expression) + + this = self.func( + "DATE_ADD", + unit_to_var(expression), + expression.expression, + expression.this, + ) + + if isinstance(expression, exp.TsOrDsAdd): + # The 3 arg version of DATE_ADD produces a timestamp in Spark3/DB but possibly not + # in other dialects + return_type = expression.return_type + if not return_type.is_type(exp.DataType.Type.TIMESTAMP, exp.DataType.Type.DATETIME): + this = f"CAST({this} AS {return_type})" + + return this + + class Spark(Spark2): class Tokenizer(Spark2.Tokenizer): RAW_STRINGS = [ @@ -62,6 +101,9 @@ class Spark(Spark2): FUNCTIONS = { **Spark2.Parser.FUNCTIONS, "ANY_VALUE": _build_with_ignore_nulls(exp.AnyValue), + "DATE_ADD": _build_dateadd, + "DATEADD": _build_dateadd, + "TIMESTAMPADD": _build_dateadd, "DATEDIFF": _build_datediff, "TIMESTAMP_LTZ": _build_as_cast("TIMESTAMP_LTZ"), "TIMESTAMP_NTZ": _build_as_cast("TIMESTAMP_NTZ"), @@ -111,9 +153,8 @@ class Spark(Spark2): exp.PartitionedByProperty: lambda self, e: f"PARTITIONED BY {self.wrap(self.expressions(sqls=[_normalize_partition(e) for e in e.this.expressions], skip_first=True))}", exp.StartsWith: rename_func("STARTSWITH"), - exp.TimestampAdd: lambda self, e: self.func( - "DATEADD", unit_to_var(e), e.expression, e.this - ), + exp.TsOrDsAdd: _dateadd_sql, + exp.TimestampAdd: _dateadd_sql, exp.TryCast: lambda self, e: ( self.trycast_sql(e) if e.args.get("safe") else self.cast_sql(e) ),
Redshift - add support for oracle style join markers ` (+)` **Fully reproducible code snippet** ```python from sqlglot import parse_one sample_sql_stmt = "select a.foo, b.bar, a.baz from a, b where a.baz = b.baz (+)" parse_one(sample_sql_stmt, read="redshift").sql(dialect="redshift") ``` expected: `SELECT a.foo, b.bar, a.baz FROM a, b WHERE a.baz = b.baz (+)` actual: `SELECT a.foo, b.bar, a.baz FROM a, b WHERE a.baz = b.BAZ()` **Official Documentation** [Oracle-Style outer joins in the WHERE clause](https://docs.aws.amazon.com/redshift/latest/dg/r_WHERE_oracle_outer.html) >For Oracle compatibility, Amazon Redshift supports the Oracle outer-join operator (+) in WHERE clause join conditions
tobymao/sqlglot
diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py index bfaf0091..888071de 100644 --- a/tests/dialects/test_bigquery.py +++ b/tests/dialects/test_bigquery.py @@ -619,9 +619,9 @@ LANGUAGE js AS 'SELECT TIMESTAMP_ADD(TIMESTAMP "2008-12-25 15:30:00+00", INTERVAL 10 MINUTE)', write={ "bigquery": "SELECT TIMESTAMP_ADD(CAST('2008-12-25 15:30:00+00' AS TIMESTAMP), INTERVAL 10 MINUTE)", - "databricks": "SELECT DATEADD(MINUTE, 10, CAST('2008-12-25 15:30:00+00' AS TIMESTAMP))", + "databricks": "SELECT DATE_ADD(MINUTE, 10, CAST('2008-12-25 15:30:00+00' AS TIMESTAMP))", "mysql": "SELECT DATE_ADD(TIMESTAMP('2008-12-25 15:30:00+00'), INTERVAL 10 MINUTE)", - "spark": "SELECT DATEADD(MINUTE, 10, CAST('2008-12-25 15:30:00+00' AS TIMESTAMP))", + "spark": "SELECT DATE_ADD(MINUTE, 10, CAST('2008-12-25 15:30:00+00' AS TIMESTAMP))", }, ) self.validate_all( diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py index 74753beb..50ba6053 100644 --- a/tests/dialects/test_postgres.py +++ b/tests/dialects/test_postgres.py @@ -724,6 +724,28 @@ class TestPostgres(Validator): self.validate_identity("cast(a as FLOAT8)", "CAST(a AS DOUBLE PRECISION)") self.validate_identity("cast(a as FLOAT4)", "CAST(a AS REAL)") + self.validate_all( + "1 / DIV(4, 2)", + read={ + "postgres": "1 / DIV(4, 2)", + }, + write={ + "sqlite": "1 / CAST(CAST(CAST(4 AS REAL) / 2 AS INTEGER) AS REAL)", + "duckdb": "1 / CAST(4 // 2 AS DECIMAL)", + "bigquery": "1 / CAST(DIV(4, 2) AS NUMERIC)", + }, + ) + self.validate_all( + "CAST(DIV(4, 2) AS DECIMAL(5, 3))", + read={ + "duckdb": "CAST(4 // 2 AS DECIMAL(5, 3))", + }, + write={ + "duckdb": "CAST(CAST(4 // 2 AS DECIMAL) AS DECIMAL(5, 3))", + "postgres": "CAST(DIV(4, 2) AS DECIMAL(5, 3))", + }, + ) + def test_ddl(self): # Checks that user-defined types are parsed into DataType instead of Identifier self.parse_one("CREATE TABLE t (a udt)").this.expressions[0].args["kind"].assert_is( diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py index 844fe461..69793c73 100644 --- a/tests/dialects/test_redshift.py +++ b/tests/dialects/test_redshift.py @@ -281,6 +281,9 @@ class TestRedshift(Validator): "redshift": "SELECT DATEADD(MONTH, 18, '2008-02-28')", "snowflake": "SELECT DATEADD(MONTH, 18, CAST('2008-02-28' AS TIMESTAMP))", "tsql": "SELECT DATEADD(MONTH, 18, CAST('2008-02-28' AS DATETIME2))", + "spark": "SELECT DATE_ADD(MONTH, 18, '2008-02-28')", + "spark2": "SELECT ADD_MONTHS('2008-02-28', 18)", + "databricks": "SELECT DATE_ADD(MONTH, 18, '2008-02-28')", }, ) self.validate_all( @@ -585,3 +588,9 @@ FROM ( self.assertEqual( ast.sql("redshift"), "SELECT * FROM x AS a, a.b AS c, c.d.e AS f, f.g.h.i.j.k AS l" ) + + def test_join_markers(self): + self.validate_identity( + "select a.foo, b.bar, a.baz from a, b where a.baz = b.baz (+)", + "SELECT a.foo, b.bar, a.baz FROM a, b WHERE a.baz = b.baz (+)", + ) diff --git a/tests/dialects/test_spark.py b/tests/dialects/test_spark.py index ecc152f2..bff91bf8 100644 --- a/tests/dialects/test_spark.py +++ b/tests/dialects/test_spark.py @@ -563,6 +563,7 @@ TBLPROPERTIES ( "SELECT DATE_ADD(my_date_column, 1)", write={ "spark": "SELECT DATE_ADD(my_date_column, 1)", + "spark2": "SELECT DATE_ADD(my_date_column, 1)", "bigquery": "SELECT DATE_ADD(CAST(CAST(my_date_column AS DATETIME) AS DATE), INTERVAL 1 DAY)", }, ) @@ -675,6 +676,16 @@ TBLPROPERTIES ( "spark": "SELECT ARRAY_SORT(x)", }, ) + self.validate_all( + "SELECT DATE_ADD(MONTH, 20, col)", + read={ + "spark": "SELECT TIMESTAMPADD(MONTH, 20, col)", + }, + write={ + "spark": "SELECT DATE_ADD(MONTH, 20, col)", + "databricks": "SELECT DATE_ADD(MONTH, 20, col)", + }, + ) def test_bool_or(self): self.validate_all(
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
25.0
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [], "python": "3.9", "reqs_path": [], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 Pygments==2.19.1 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@664ae5c3ecc21553e7a5909d7811e5da3a9db1d9#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - pygments==2.19.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery", "tests/dialects/test_postgres.py::TestPostgres::test_postgres", "tests/dialects/test_redshift.py::TestRedshift::test_join_markers", "tests/dialects/test_redshift.py::TestRedshift::test_redshift", "tests/dialects/test_spark.py::TestSpark::test_spark" ]
[]
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_errors", "tests/dialects/test_bigquery.py::TestBigQuery::test_gap_fill", "tests/dialects/test_bigquery.py::TestBigQuery::test_group_concat", "tests/dialects/test_bigquery.py::TestBigQuery::test_json_object", "tests/dialects/test_bigquery.py::TestBigQuery::test_merge", "tests/dialects/test_bigquery.py::TestBigQuery::test_mod", "tests/dialects/test_bigquery.py::TestBigQuery::test_models", "tests/dialects/test_bigquery.py::TestBigQuery::test_pushdown_cte_column_names", "tests/dialects/test_bigquery.py::TestBigQuery::test_remove_precision_parameterized_types", "tests/dialects/test_bigquery.py::TestBigQuery::test_rename_table", "tests/dialects/test_bigquery.py::TestBigQuery::test_user_defined_functions", "tests/dialects/test_bigquery.py::TestBigQuery::test_warnings", "tests/dialects/test_postgres.py::TestPostgres::test_array_offset", "tests/dialects/test_postgres.py::TestPostgres::test_bool_or", "tests/dialects/test_postgres.py::TestPostgres::test_ddl", "tests/dialects/test_postgres.py::TestPostgres::test_operator", "tests/dialects/test_postgres.py::TestPostgres::test_regexp_binary", "tests/dialects/test_postgres.py::TestPostgres::test_string_concat", "tests/dialects/test_postgres.py::TestPostgres::test_unnest", "tests/dialects/test_postgres.py::TestPostgres::test_unnest_json_array", "tests/dialects/test_postgres.py::TestPostgres::test_variance", "tests/dialects/test_redshift.py::TestRedshift::test_alter_table", "tests/dialects/test_redshift.py::TestRedshift::test_column_unnesting", "tests/dialects/test_redshift.py::TestRedshift::test_create_table_like", "tests/dialects/test_redshift.py::TestRedshift::test_identity", "tests/dialects/test_redshift.py::TestRedshift::test_no_schema_binding", "tests/dialects/test_redshift.py::TestRedshift::test_values", "tests/dialects/test_redshift.py::TestRedshift::test_varchar_max", "tests/dialects/test_spark.py::TestSpark::test_bool_or", "tests/dialects/test_spark.py::TestSpark::test_current_user", "tests/dialects/test_spark.py::TestSpark::test_ddl", "tests/dialects/test_spark.py::TestSpark::test_explode_to_unnest", "tests/dialects/test_spark.py::TestSpark::test_hint", "tests/dialects/test_spark.py::TestSpark::test_insert_cte", "tests/dialects/test_spark.py::TestSpark::test_strip_modifiers", "tests/dialects/test_spark.py::TestSpark::test_to_date", "tests/dialects/test_spark.py::TestSpark::test_transform_query" ]
[]
MIT License
18,618
1,812
[ "sqlglot/dialects/postgres.py", "sqlglot/dialects/redshift.py", "sqlglot/dialects/spark.py" ]
holoviz__holoviews-6269
4bd31bcf1ac2aa6f11897de6f4e7fe830d088aee
2024-06-07 14:12:37
6a9643355f12027207eb0d427dc81ca8798cb78c
diff --git a/holoviews/core/dimension.py b/holoviews/core/dimension.py index 56b348a63..fa05ac8e5 100644 --- a/holoviews/core/dimension.py +++ b/holoviews/core/dimension.py @@ -716,37 +716,27 @@ class LabelledData(param.Parameterized): "Restores options applied to this object." d = param_aliases(d) - # Backwards compatibility for objects before id was made a property - opts_id = d['_id'] if '_id' in d else d.pop('id', None) - try: - load_options = Store.load_counter_offset is not None - if load_options: - matches = [k for k in d if k.startswith('_custom_option')] - for match in matches: - custom_id = int(match.split('_')[-1])+Store.load_counter_offset - if not isinstance(d[match], dict): - # Backward compatibility before multiple backends - backend_info = {'matplotlib':d[match]} - else: - backend_info = d[match] - for backend, info in backend_info.items(): - if backend not in Store._custom_options: - Store._custom_options[backend] = {} - Store._custom_options[backend][custom_id] = info - if backend_info: - if custom_id not in Store._weakrefs: - Store._weakrefs[custom_id] = [] - ref = weakref.ref(self, partial(cleanup_custom_options, custom_id)) - Store._weakrefs[opts_id].append(ref) - d.pop(match) - - if opts_id is not None: - opts_id += Store.load_counter_offset - except Exception: - self.param.warning("Could not unpickle custom style information.") - d['_id'] = opts_id + load_options = Store.load_counter_offset is not None + if load_options: + matches = [k for k in d if k.startswith('_custom_option')] + for match in matches: + custom_id = int(match.split('_')[-1])+Store.load_counter_offset + for backend, info in d[match].items(): + if backend not in Store._custom_options: + Store._custom_options[backend] = {} + Store._custom_options[backend][custom_id] = info + if d[match]: + if custom_id not in Store._weakrefs: + Store._weakrefs[custom_id] = [] + ref = weakref.ref(self, partial(cleanup_custom_options, custom_id)) + Store._weakrefs[d["_id"]].append(ref) + d.pop(match) + + if d["_id"] is not None: + d["_id"] += Store.load_counter_offset + self.__dict__.update(d) - super().__setstate__({}) + super().__setstate__(d) class Dimensioned(LabelledData): diff --git a/holoviews/plotting/renderer.py b/holoviews/plotting/renderer.py index 7d8fcb97f..361de8193 100644 --- a/holoviews/plotting/renderer.py +++ b/holoviews/plotting/renderer.py @@ -389,8 +389,9 @@ class Renderer(Exporter): src is source or (src._plot_id is not None and src._plot_id == source._plot_id) for src, streams in registry for s in streams ) + if config.comms == 'colab': + load_notebook(config.inline) embed = (not (dynamic or streams or self.widget_mode == 'live') or config.embed) - if embed or config.comms == 'default': return self._render_panel(plot, embed, comm) return self._render_ipywidget(plot)
Empty output in Colab #### ALL software version info Google Colab ``` sys.version_info: sys.version_info(major=3, minor=10, micro=12, releaselevel='final', serial=0) ipywidgets.__version__: 8.1.1 bokeh.__version__: 3.3.2 jupyter_bokeh.__version__: 3.0.7 holoviews.__version__: 1.17.1 ``` #### Description of expected behavior and the observed behavior I'm trying to run the demo for the `BoxEdit` module, but when I run the demo nothing is shown #### Complete, minimal, self-contained example code that reproduces the issue ``` !pip install holoviews --quiet !pip install jupyter_bokeh --quiet import holoviews holoviews.extension('bokeh', logo=False) from bokeh.plotting import output_notebook output_notebook(hide_banner=True) from google.colab import output output.enable_custom_widget_manager() ``` This works: ``` %output size = 200 holoviews.extension('bokeh') boxes = holoviews.Rectangles( [(0, 0, 1, 1), (2, 3, 4, 6), (0.5, 2, 1.5, 4), (2, 1, 3.5, 2.5)]) boxes.opts( holoviews.opts.Rectangles( fill_alpha=0.5, height=400, width=400)) ``` Nothing is shown for this: ``` %output size = 200 holoviews.extension('bokeh') boxes = holoviews.Rectangles( [(0, 0, 1, 1), (2, 3, 4, 6), (0.5, 2, 1.5, 4), (2, 1, 3.5, 2.5)]) box_stream = holoviews.streams.BoxEdit(source=boxes) boxes.opts( holoviews.opts.Rectangles( fill_alpha=0.5, height=400, width=400)) ``` #### Stack traceback and/or browser JavaScript console output Looking in the Chrome develop tools console ``` Error has occurred while trying to update output. output_binary.js:173 message: 'Widget @bokeh/jupyter_bokeh BokehModel is not supported', Stack: CustomError: Widget @bokeh/jupyter_bokeh BokehModel is not supported at new Bk (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:168:471) at wa.eval [as h] (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:166:142) at za (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:11:141) at Ba.next (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:11:440) at eval (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:12:319) at new Promise (<anonymous>) at Ca (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:12:212) at y (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:12:351) at yk (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:166:51) at new zk (https://ssl.gstatic.com/colaboratory-static/common/b124d179c25e30ffc6a1ff293e85eba8/output_binary.js:165:1730) ``` #### Screenshots or screencasts of the bug in action <img width="738" alt="image" src="https://github.com/holoviz/holoviews/assets/129072/36011584-cd4d-4bc4-98ba-a4360093e025"> ### Other things to note This code was working as is on google colab in August 2023, but is not now working in December 2023 - Note that running the code brings up snippets suggesting adding the code: ``` from google.colab import output output.enable_custom_widget_manager() ``` However this has no effect - Using the latest developer version of holoviews from github had no effect ### Other things I've tried I found this [issue](https://github.com/googlecolab/colabtools/issues/3020) on colabtools github, **_Default ipywidgets don't show up in notebooks_** This issue suggests that "Downgrading ipywidgets to 7.7.1" may help I tried ``` !pip install ipywidgets==7.7.1 ``` The current version of `jupyter-bokeh` is `3.0.7` and requires `ipywidgets==8.*` The most current version of `jupyter-bokeh` that supports `ipywidgets==7.7.1` is version `3.0.2`. ``` !pip install jupyter_bokeh==3.0.2 ``` However in going from `3.0.2` => `3.0.7` there was a bug fixed to be compatible with the current version of bokeh `3.3.2`, namely ``` standalone_docs_json_and_render_items() takes 1 positional argument but 2 were given ``` This fix can be monkey patched back into `jupyter-bokeh` version `3.0.2`, so all together the code looks like this: ``` !pip install ipywidgets==7.7.1 !pip install jupyter_bokeh==3.0.2 import bokeh import bokeh.model import jupyter_bokeh import jupyter_bokeh.widgets # use functools.wraps to keep the @classmethod decorator import functools @functools.wraps(jupyter_bokeh.widgets.BokehModel._model_to_traits) def _model_to_traits(cls, model): if model.document is None: document = bokeh.document.Document() document.add_root(model) (docs_json, [render_item]) = bokeh.embed.util.standalone_docs_json_and_render_items( [model], suppress_callback_warning=True) render_bundle = dict( docs_json=docs_json, render_items=[render_item.to_json()], div=bokeh.embed.elements.div_for_render_item(render_item), ) return render_bundle jupyter_bokeh.widgets.BokehModel._model_to_traits = _model_to_traits !pip install holoviews --quiet from bokeh.plotting import output_notebook output_notebook(hide_banner=True) import holoviews holoviews.extension('bokeh', logo=False) ``` However downgrading to ipywidgets did not resolve the problem
holoviz/holoviews
diff --git a/holoviews/tests/core/test_dimensioned.py b/holoviews/tests/core/test_dimensioned.py index f65060dea..1dc3dc7a4 100644 --- a/holoviews/tests/core/test_dimensioned.py +++ b/holoviews/tests/core/test_dimensioned.py @@ -1,8 +1,10 @@ import gc +import pickle from holoviews.core.element import Element from holoviews.core.options import Keywords, Options, OptionTree, Store from holoviews.core.spaces import HoloMap +from holoviews.element.chart import Curve from ..utils import LoggingComparisonTestCase @@ -247,3 +249,11 @@ class TestOptionsCleanup(CustomBackendTestCase): ExampleElement([]).opts(style_opt1='A').opts.clear() custom_options = Store._custom_options['backend_1'] self.assertEqual(len(custom_options), 0) + +class TestGetSetState: + + def test_pickle_roundtrip(self): + curve = Curve([0, 1, 2], kdims=["XAXIS"]) + roundtrip_curve = pickle.loads(pickle.dumps(curve)) + assert curve.kdims == roundtrip_curve.kdims + assert curve.vdims == roundtrip_curve.vdims
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 2 }
1.19
{ "env_vars": null, "env_yml_path": [ "binder/environment.yml" ], "install": "pip install -e .[recommended]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "environment.yml", "pip_packages": [ "pytest", "pytest-rerunfailures", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
atpublic @ file:///home/conda/feedstock_root/build_artifacts/atpublic_1737771474411/work attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1741918516150/work bidict @ file:///home/conda/feedstock_root/build_artifacts/bidict_1734272627465/work bleach @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_bleach_1737382993/work bokeh==3.4.3 Brotli @ file:///home/conda/feedstock_root/build_artifacts/brotli-split_1725267488082/work certifi @ file:///home/conda/feedstock_root/build_artifacts/certifi_1739515848642/work/certifi cffi @ file:///home/conda/feedstock_root/build_artifacts/cffi_1725571112467/work cftime @ file:///home/conda/feedstock_root/build_artifacts/cftime_1725400455427/work charset-normalizer @ file:///home/conda/feedstock_root/build_artifacts/charset-normalizer_1735929714516/work click @ file:///home/conda/feedstock_root/build_artifacts/click_1734858813237/work cloudpickle @ file:///home/conda/feedstock_root/build_artifacts/cloudpickle_1736947526808/work colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1733218098505/work colorcet @ file:///home/conda/feedstock_root/build_artifacts/colorcet_1734007314889/work contourpy @ file:///home/conda/feedstock_root/build_artifacts/contourpy_1727293517607/work coverage==7.8.0 cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1733332471406/work cytoolz @ file:///home/conda/feedstock_root/build_artifacts/cytoolz_1734107207199/work dask @ file:///home/conda/feedstock_root/build_artifacts/dask-core_1722976580461/work dask-expr @ file:///home/conda/feedstock_root/build_artifacts/dask-expr_1722982607046/work datashader @ file:///home/conda/feedstock_root/build_artifacts/datashader_1734341715727/work distributed @ file:///home/conda/feedstock_root/build_artifacts/distributed_1722982528621/work exceptiongroup @ file:///home/conda/feedstock_root/build_artifacts/exceptiongroup_1733208806608/work filelock @ file:///home/conda/feedstock_root/build_artifacts/filelock_1741969488311/work fonttools @ file:///home/conda/feedstock_root/build_artifacts/fonttools_1738940303262/work fsspec @ file:///home/conda/feedstock_root/build_artifacts/fsspec_1743361113926/work graphviz @ file:///home/conda/feedstock_root/build_artifacts/python-graphviz_1733791968395/work h11 @ file:///home/conda/feedstock_root/build_artifacts/h11_1733327467879/work h2 @ file:///home/conda/feedstock_root/build_artifacts/h2_1738578511449/work -e git+https://github.com/holoviz/holoviews.git@4bd31bcf1ac2aa6f11897de6f4e7fe830d088aee#egg=holoviews hpack @ file:///home/conda/feedstock_root/build_artifacts/hpack_1737618293087/work hyperframe @ file:///home/conda/feedstock_root/build_artifacts/hyperframe_1737618333194/work ibis-framework @ file:///home/conda/feedstock_root/build_artifacts/ibis-framework-ext_1726155380758/work idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1733211830134/work importlib_metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1737420181517/work importlib_resources @ file:///home/conda/feedstock_root/build_artifacts/importlib_resources_1736252299705/work iniconfig==2.1.0 Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1741263328855/work kiwisolver @ file:///home/conda/feedstock_root/build_artifacts/kiwisolver_1725459266648/work linkify-it-py==2.0.3 llvmlite==0.43.0 locket @ file:///home/conda/feedstock_root/build_artifacts/locket_1650660393415/work lz4 @ file:///home/conda/feedstock_root/build_artifacts/lz4_1733474248677/work Markdown @ file:///home/conda/feedstock_root/build_artifacts/markdown_1710435156458/work markdown-it-py @ file:///home/conda/feedstock_root/build_artifacts/markdown-it-py_1733250460757/work MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1733219680183/work matplotlib==3.9.4 mdit-py-plugins==0.4.2 mdurl @ file:///home/conda/feedstock_root/build_artifacts/mdurl_1733255585584/work msgpack @ file:///home/conda/feedstock_root/build_artifacts/msgpack-python_1725975012026/work multipledispatch @ file:///home/conda/feedstock_root/build_artifacts/multipledispatch_1721907546485/work munkres==1.1.4 narwhals @ file:///home/conda/feedstock_root/build_artifacts/narwhals_1742841036354/work netCDF4 @ file:///home/conda/feedstock_root/build_artifacts/netcdf4_1733253078561/work networkx @ file:///home/conda/feedstock_root/build_artifacts/networkx_1698504735452/work numba @ file:///home/conda/feedstock_root/build_artifacts/numba_1718888028049/work numpy @ file:///home/conda/feedstock_root/build_artifacts/numpy_1732314280888/work/dist/numpy-2.0.2-cp39-cp39-linux_x86_64.whl#sha256=62d98eb3da9f13e6b227c430d01026b7427f341b3fdcb838430f2a9e520417b1 outcome @ file:///home/conda/feedstock_root/build_artifacts/outcome_1733406188332/work packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1733203243479/work pandas @ file:///home/conda/feedstock_root/build_artifacts/pandas_1736810577256/work panel==1.4.5 param==2.2.0 parsy @ file:///home/conda/feedstock_root/build_artifacts/parsy_1734616013612/work partd @ file:///home/conda/feedstock_root/build_artifacts/partd_1715026491486/work pillow @ file:///home/conda/feedstock_root/build_artifacts/pillow_1735929703139/work plotly @ file:///home/conda/feedstock_root/build_artifacts/plotly_1742240435426/work pluggy==1.5.0 psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1740663125313/work pyarrow==19.0.1 pyarrow-hotfix @ file:///home/conda/feedstock_root/build_artifacts/pyarrow-hotfix_1734380560621/work pycparser @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_pycparser_1733195786/work pyct @ file:///home/conda/feedstock_root/build_artifacts/pyct_1734342495516/work Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1736243443484/work pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1743089729650/work PySide6==6.8.3 PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1733217236728/work pytest==8.3.5 pytest-cov==6.0.0 pytest-rerunfailures==15.0 python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1733215673016/work pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1706886791323/work pyviz_comms @ file:///home/conda/feedstock_root/build_artifacts/pyviz_comms_1736890319493/work PyYAML @ file:///home/conda/feedstock_root/build_artifacts/pyyaml_1737454647378/work regex @ file:///home/conda/feedstock_root/build_artifacts/regex_1730952178579/work requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1733217035951/work retrying @ file:///home/conda/feedstock_root/build_artifacts/retrying_1740053923454/work rich @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rich_1743371105/work/dist scipy @ file:///home/conda/feedstock_root/build_artifacts/scipy-split_1716470218293/work/dist/scipy-1.13.1-cp39-cp39-linux_x86_64.whl#sha256=e6696cb8683d94467891b7648e068a3970f6bc0a1b3c1aa7f9bc89458eafd2f0 selenium @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_selenium_1742656691/work shiboken6==6.8.3 six @ file:///home/conda/feedstock_root/build_artifacts/six_1733380938961/work sniffio @ file:///home/conda/feedstock_root/build_artifacts/sniffio_1733244044561/work sortedcontainers @ file:///home/conda/feedstock_root/build_artifacts/sortedcontainers_1738440353519/work spatialpandas @ file:///home/conda/feedstock_root/build_artifacts/spatialpandas_1704978503377/work sqlglot @ file:///home/conda/feedstock_root/build_artifacts/sqlglot_1725660219720/work streamz @ file:///home/conda/feedstock_root/build_artifacts/streamz_1734714199010/work tblib @ file:///home/conda/feedstock_root/build_artifacts/tblib_1733842374544/work tomli==2.2.1 toolz @ file:///home/conda/feedstock_root/build_artifacts/toolz_1706112571092/work tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1732615921868/work tqdm @ file:///home/conda/feedstock_root/build_artifacts/tqdm_1735661334605/work trio @ file:///home/conda/feedstock_root/build_artifacts/trio_1739529631723/work trio-websocket @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_trio-websocket_1740493956/work typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_typing_extensions_1743201626/work tzdata @ file:///home/conda/feedstock_root/build_artifacts/python-tzdata_1742745135198/work uc-micro-py==1.0.3 unicodedata2 @ file:///home/conda/feedstock_root/build_artifacts/unicodedata2_1736692503055/work urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1734859416348/work webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1733236011802/work websocket-client @ file:///home/conda/feedstock_root/build_artifacts/websocket-client_1733157342724/work wsproto @ file:///home/conda/feedstock_root/build_artifacts/wsproto_1733060193308/work xarray @ file:///home/conda/feedstock_root/build_artifacts/xarray_1722348170975/work xyzservices==2025.1.0 zict @ file:///home/conda/feedstock_root/build_artifacts/zict_1733261551178/work zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1732827521216/work zstandard==0.23.0
name: holoviews channels: - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=conda_forge - _openmp_mutex=4.5=2_gnu - adwaita-icon-theme=48.0=unix_0 - alsa-lib=1.2.13=hb9d3cd8_0 - aom=3.9.1=hac33072_0 - at-spi2-atk=2.38.0=h0630a04_3 - at-spi2-core=2.40.3=h0630a04_0 - atk-1.0=2.38.0=h04ea711_2 - atpublic=5.1=pyhd8ed1ab_0 - attr=2.5.1=h166bdaf_1 - attrs=25.3.0=pyh71513ae_0 - aws-c-auth=0.8.6=hd08a7f5_4 - aws-c-cal=0.8.7=h043a21b_0 - aws-c-common=0.12.0=hb9d3cd8_0 - aws-c-compression=0.3.1=h3870646_2 - aws-c-event-stream=0.5.4=h04a3f94_2 - aws-c-http=0.9.4=hb9b18c6_4 - aws-c-io=0.17.0=h3dad3f2_6 - aws-c-mqtt=0.12.2=h108da3e_2 - aws-c-s3=0.7.13=h822ba82_2 - aws-c-sdkutils=0.2.3=h3870646_2 - aws-checksums=0.2.3=h3870646_2 - aws-crt-cpp=0.31.0=h55f77e1_4 - aws-sdk-cpp=1.11.510=h37a5c72_3 - azure-core-cpp=1.14.0=h5cfcd09_0 - azure-identity-cpp=1.10.0=h113e628_0 - azure-storage-blobs-cpp=12.13.0=h3cf044e_1 - azure-storage-common-cpp=12.8.0=h736e048_1 - azure-storage-files-datalake-cpp=12.12.0=ha633028_1 - bidict=0.23.1=pyhd8ed1ab_1 - bleach=6.2.0=pyh29332c3_4 - blosc=1.21.6=he440d0b_1 - brotli=1.1.0=hb9d3cd8_2 - brotli-bin=1.1.0=hb9d3cd8_2 - brotli-python=1.1.0=py39hf88036b_2 - bzip2=1.0.8=h4bc722e_7 - c-ares=1.34.4=hb9d3cd8_0 - ca-certificates=2025.1.31=hbcca054_0 - cairo=1.18.4=h3394656_0 - certifi=2025.1.31=pyhd8ed1ab_0 - cffi=1.17.1=py39h15c3d72_0 - cftime=1.6.4=py39hf3d9206_1 - charset-normalizer=3.4.1=pyhd8ed1ab_0 - click=8.1.8=pyh707e725_0 - cloudpickle=3.1.1=pyhd8ed1ab_0 - colorama=0.4.6=pyhd8ed1ab_1 - colorcet=3.1.0=pyhd8ed1ab_1 - contourpy=1.3.0=py39h74842e3_2 - cycler=0.12.1=pyhd8ed1ab_1 - cyrus-sasl=2.1.27=h54b06d7_7 - cytoolz=1.0.1=py39h8cd3c5a_0 - dask=2024.8.0=pyhd8ed1ab_0 - dask-core=2024.8.0=pyhd8ed1ab_0 - dask-expr=1.1.10=pyhd8ed1ab_0 - datashader=0.16.3=pyhd8ed1ab_1 - dav1d=1.2.1=hd590300_0 - dbus=1.13.6=h5008d03_3 - distributed=2024.8.0=pyhd8ed1ab_0 - double-conversion=3.3.1=h5888daf_0 - epoxy=1.5.10=h166bdaf_1 - exceptiongroup=1.2.2=pyhd8ed1ab_1 - expat=2.6.4=h5888daf_0 - ffmpeg=7.1.1=gpl_h0b79d52_704 - filelock=3.18.0=pyhd8ed1ab_0 - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 - font-ttf-inconsolata=3.000=h77eed37_0 - font-ttf-source-code-pro=2.038=h77eed37_0 - font-ttf-ubuntu=0.83=h77eed37_3 - fontconfig=2.15.0=h7e30c49_1 - fonts-conda-ecosystem=1=0 - fonts-conda-forge=1=0 - fonttools=4.56.0=py39h9399b63_0 - freetype=2.13.3=h48d6fc4_0 - fribidi=1.0.10=h36c2ea0_0 - fsspec=2025.3.1=pyhd8ed1ab_0 - gdk-pixbuf=2.42.12=hb9ae30d_0 - gettext=0.23.1=h5888daf_0 - gettext-tools=0.23.1=h5888daf_0 - gflags=2.2.2=h5888daf_1005 - glib-tools=2.84.0=h4833e2c_0 - glog=0.7.1=hbabe93e_0 - gmp=6.3.0=hac33072_2 - graphite2=1.3.13=h59595ed_1003 - graphviz=12.2.1=h5ae0cbf_1 - gtk3=3.24.43=h0c6a113_5 - gts=0.7.6=h977cf35_4 - h11=0.14.0=pyhd8ed1ab_1 - h2=4.2.0=pyhd8ed1ab_0 - harfbuzz=11.0.0=h76408a6_0 - hdf4=4.2.15=h2a13503_7 - hdf5=1.14.4=nompi_h2d575fe_105 - hicolor-icon-theme=0.17=ha770c72_2 - hpack=4.1.0=pyhd8ed1ab_0 - hyperframe=6.1.0=pyhd8ed1ab_0 - ibis-framework-core=9.5.0=pyhd8ed1ab_0 - ibis-sqlite=9.5.0=hd8ed1ab_0 - icu=75.1=he02047a_0 - idna=3.10=pyhd8ed1ab_1 - importlib-metadata=8.6.1=pyha770c72_0 - importlib-resources=6.5.2=pyhd8ed1ab_0 - importlib_metadata=8.6.1=hd8ed1ab_0 - importlib_resources=6.5.2=pyhd8ed1ab_0 - jack=1.9.22=h7c63dc7_2 - jinja2=3.1.6=pyhd8ed1ab_0 - keyutils=1.6.1=h166bdaf_0 - kiwisolver=1.4.7=py39h74842e3_0 - krb5=1.21.3=h659f571_0 - lame=3.100=h166bdaf_1003 - lcms2=2.17=h717163a_0 - ld_impl_linux-64=2.43=h712a8e2_4 - lerc=4.0.0=h27087fc_0 - level-zero=1.21.6=h84d6215_0 - libabseil=20250127.1=cxx17_hbbce691_0 - libaec=1.1.3=h59595ed_0 - libarrow=19.0.1=h120c447_5_cpu - libarrow-acero=19.0.1=hcb10f89_5_cpu - libarrow-dataset=19.0.1=hcb10f89_5_cpu - libarrow-substrait=19.0.1=h1bed206_5_cpu - libasprintf=0.23.1=h8e693c7_0 - libasprintf-devel=0.23.1=h8e693c7_0 - libass=0.17.3=h52826cd_2 - libblas=3.9.0=31_h59b9bed_openblas - libbrotlicommon=1.1.0=hb9d3cd8_2 - libbrotlidec=1.1.0=hb9d3cd8_2 - libbrotlienc=1.1.0=hb9d3cd8_2 - libcap=2.75=h39aace5_0 - libcblas=3.9.0=31_he106b2a_openblas - libclang-cpp20.1=20.1.1=default_hb5137d0_0 - libclang13=20.1.1=default_h9c6a7e4_0 - libcrc32c=1.1.2=h9c3ff4c_0 - libcups=2.3.3=h4637d8d_4 - libcurl=8.12.1=h332b0f4_0 - libdb=6.2.32=h9c3ff4c_0 - libdeflate=1.23=h4ddbbb0_0 - libdrm=2.4.124=hb9d3cd8_0 - libedit=3.1.20250104=pl5321h7949ede_0 - libegl=1.7.0=ha4b6fd6_2 - libev=4.33=hd590300_2 - libevent=2.1.12=hf998b51_1 - libexpat=2.6.4=h5888daf_0 - libffi=3.4.6=h2dba641_0 - libflac=1.4.3=h59595ed_0 - libgcc=14.2.0=h767d61c_2 - libgcc-ng=14.2.0=h69a702a_2 - libgcrypt-lib=1.11.0=hb9d3cd8_2 - libgd=2.3.3=h6f5c62b_11 - libgettextpo=0.23.1=h5888daf_0 - libgettextpo-devel=0.23.1=h5888daf_0 - libgfortran=14.2.0=h69a702a_2 - libgfortran-ng=14.2.0=h69a702a_2 - libgfortran5=14.2.0=hf1ad2bd_2 - libgl=1.7.0=ha4b6fd6_2 - libglib=2.84.0=h2ff4ddf_0 - libglvnd=1.7.0=ha4b6fd6_2 - libglx=1.7.0=ha4b6fd6_2 - libgomp=14.2.0=h767d61c_2 - libgoogle-cloud=2.36.0=hc4361e1_1 - libgoogle-cloud-storage=2.36.0=h0121fbd_1 - libgpg-error=1.51=hbd13f7d_1 - libgrpc=1.71.0=he753a82_0 - libhwloc=2.11.2=default_h0d58e46_1001 - libiconv=1.18=h4ce23a2_1 - libjpeg-turbo=3.0.0=hd590300_1 - liblapack=3.9.0=31_h7ac8fdf_openblas - libllvm14=14.0.6=hcd5def8_4 - libllvm20=20.1.1=ha7bfdaf_0 - liblzma=5.6.4=hb9d3cd8_0 - libnetcdf=4.9.2=nompi_h5ddbaa4_116 - libnghttp2=1.64.0=h161d5f1_0 - libnsl=2.0.1=hd590300_0 - libntlm=1.8=hb9d3cd8_0 - libogg=1.3.5=h4ab18f5_0 - libopenblas=0.3.29=pthreads_h94d23a6_0 - libopengl=1.7.0=ha4b6fd6_2 - libopentelemetry-cpp=1.19.0=hd1b1c89_0 - libopentelemetry-cpp-headers=1.19.0=ha770c72_0 - libopenvino=2025.0.0=hdc3f47d_3 - libopenvino-auto-batch-plugin=2025.0.0=h4d9b6c2_3 - libopenvino-auto-plugin=2025.0.0=h4d9b6c2_3 - libopenvino-hetero-plugin=2025.0.0=h981d57b_3 - libopenvino-intel-cpu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-intel-gpu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-intel-npu-plugin=2025.0.0=hdc3f47d_3 - libopenvino-ir-frontend=2025.0.0=h981d57b_3 - libopenvino-onnx-frontend=2025.0.0=h0e684df_3 - libopenvino-paddle-frontend=2025.0.0=h0e684df_3 - libopenvino-pytorch-frontend=2025.0.0=h5888daf_3 - libopenvino-tensorflow-frontend=2025.0.0=h684f15b_3 - libopenvino-tensorflow-lite-frontend=2025.0.0=h5888daf_3 - libopus=1.3.1=h7f98852_1 - libparquet=19.0.1=h081d1f1_5_cpu - libpciaccess=0.18=hd590300_0 - libpng=1.6.47=h943b412_0 - libpq=17.4=h27ae623_0 - libprotobuf=5.29.3=h501fc15_0 - libre2-11=2024.07.02=hba17884_3 - librsvg=2.58.4=he92a37e_3 - libsndfile=1.2.2=hc60ed4a_1 - libsqlite=3.49.1=hee588c1_2 - libssh2=1.11.1=hf672d98_0 - libstdcxx=14.2.0=h8f9b012_2 - libstdcxx-ng=14.2.0=h4852527_2 - libsystemd0=257.4=h4e0b6ca_1 - libthrift=0.21.0=h0e7cc3e_0 - libtiff=4.7.0=hd9ff511_3 - libudev1=257.4=hbe16f8c_1 - libunwind=1.6.2=h9c3ff4c_0 - liburing=2.9=h84d6215_0 - libusb=1.0.28=hb9d3cd8_0 - libutf8proc=2.10.0=h4c51ac1_0 - libuuid=2.38.1=h0b41bf4_0 - libva=2.22.0=h4f16b4b_2 - libvorbis=1.3.7=h9c3ff4c_0 - libvpx=1.14.1=hac33072_0 - libwebp-base=1.5.0=h851e524_0 - libxcb=1.17.0=h8a09558_0 - libxcrypt=4.4.36=hd590300_1 - libxkbcommon=1.8.1=hc4a0caf_0 - libxml2=2.13.7=h8d12d68_0 - libxslt=1.1.39=h76b75d6_0 - libzip=1.11.2=h6991a6a_0 - libzlib=1.3.1=hb9d3cd8_2 - llvmlite=0.43.0=py39hf8b6b1a_1 - locket=1.0.0=pyhd8ed1ab_0 - lz4=4.3.3=py39h92207c2_2 - lz4-c=1.10.0=h5888daf_1 - markdown=3.6=pyhd8ed1ab_0 - markdown-it-py=3.0.0=pyhd8ed1ab_1 - markupsafe=3.0.2=py39h9399b63_1 - matplotlib=3.9.4=py39hf3d152e_0 - matplotlib-base=3.9.4=py39h16632d1_0 - mdurl=0.1.2=pyhd8ed1ab_1 - mpg123=1.32.9=hc50e24c_0 - msgpack-python=1.1.0=py39h74842e3_0 - multipledispatch=0.6.0=pyhd8ed1ab_1 - munkres=1.1.4=pyh9f0ad1d_0 - mysql-common=9.0.1=h266115a_5 - mysql-libs=9.0.1=he0572af_5 - narwhals=1.32.0=pyhd8ed1ab_0 - ncurses=6.5=h2d0b736_3 - netcdf4=1.7.2=nompi_py39h1defa26_101 - networkx=3.2.1=pyhd8ed1ab_0 - nlohmann_json=3.11.3=he02047a_1 - numba=0.60.0=py39h0320e7d_0 - numpy=2.0.2=py39h9cb892a_1 - ocl-icd=2.3.2=hb9d3cd8_2 - opencl-headers=2024.10.24=h5888daf_0 - openh264=2.6.0=hc22cd8d_0 - openjpeg=2.5.3=h5fbd93e_0 - openldap=2.6.9=he970967_0 - openssl=3.4.1=h7b32b05_0 - orc=2.1.1=h17f744e_1 - outcome=1.3.0.post0=pyhd8ed1ab_1 - packaging=24.2=pyhd8ed1ab_2 - pandas=2.2.3=py39h3b40f6f_2 - pango=1.56.3=h9ac818e_1 - parsy=2.1=pyhd8ed1ab_1 - partd=1.4.2=pyhd8ed1ab_0 - pcre2=10.44=hba22ea6_2 - phantomjs=2.1.1=ha770c72_1 - pillow=11.1.0=py39h15c0740_0 - pip=25.0.1=pyh8b19718_0 - pixman=0.44.2=h29eaf8c_0 - plotly=6.0.1=pyhd8ed1ab_0 - prometheus-cpp=1.3.0=ha5d0236_0 - psutil=7.0.0=py39h8cd3c5a_0 - pthread-stubs=0.4=hb9d3cd8_1002 - pugixml=1.15=h3f63f65_0 - pulseaudio-client=17.0=hac146a9_1 - pyarrow=19.0.1=py39hf3d152e_0 - pyarrow-core=19.0.1=py39h6117c73_0_cpu - pyarrow-hotfix=0.6=pyhd8ed1ab_1 - pycparser=2.22=pyh29332c3_1 - pyct=0.5.0=pyhd8ed1ab_1 - pygments=2.19.1=pyhd8ed1ab_0 - pyparsing=3.2.3=pyhd8ed1ab_1 - pyside6=6.8.3=py39h0383914_0 - pysocks=1.7.1=pyha55dd90_7 - python=3.9.21=h9c0c6dc_1_cpython - python-dateutil=2.9.0.post0=pyhff2d567_1 - python-graphviz=0.20.3=pyh91182bf_2 - python-tzdata=2025.2=pyhd8ed1ab_0 - python_abi=3.9=5_cp39 - pytz=2024.1=pyhd8ed1ab_0 - pyviz_comms=3.0.4=pyhd8ed1ab_1 - pyyaml=6.0.2=py39h9399b63_2 - qhull=2020.2=h434a139_5 - qt6-main=6.8.3=h6441bc3_1 - re2=2024.07.02=h9925aae_3 - readline=8.2=h8c095d6_2 - regex=2024.11.6=py39h8cd3c5a_0 - requests=2.32.3=pyhd8ed1ab_1 - retrying=1.3.4=pyhd8ed1ab_0 - rich=14.0.0=pyh29332c3_0 - s2n=1.5.14=h6c98b2b_0 - scipy=1.13.1=py39haf93ffa_0 - sdl2=2.32.50=h9b8e6db_1 - sdl3=3.2.8=h3083f51_0 - selenium=4.30.0=pyh29332c3_0 - selenium-manager=4.30.0=h6c30b3d_0 - setuptools=75.8.2=pyhff2d567_0 - six=1.17.0=pyhd8ed1ab_0 - snappy=1.2.1=h8bd8927_1 - sniffio=1.3.1=pyhd8ed1ab_1 - sortedcontainers=2.4.0=pyhd8ed1ab_1 - spatialpandas=0.4.10=pyhd8ed1ab_1 - sqlglot=25.20.1=pyhd8ed1ab_0 - streamz=0.6.4=pyhd8ed1ab_1 - svt-av1=3.0.2=h5888daf_0 - tbb=2022.0.0=hceb3a55_0 - tblib=3.0.0=pyhd8ed1ab_1 - tk=8.6.13=noxft_h4845f30_101 - toolz=0.12.1=pyhd8ed1ab_0 - tornado=6.4.2=py39h8cd3c5a_0 - tqdm=4.67.1=pyhd8ed1ab_1 - trio=0.29.0=py39hf3d152e_0 - trio-websocket=0.12.2=pyh29332c3_0 - typing-extensions=4.13.0=h9fa5a19_1 - typing_extensions=4.13.0=pyh29332c3_1 - tzdata=2025b=h78e105d_0 - unicodedata2=16.0.0=py39h8cd3c5a_0 - urllib3=2.3.0=pyhd8ed1ab_0 - wayland=1.23.1=h3e06ad9_0 - wayland-protocols=1.42=hd8ed1ab_0 - webencodings=0.5.1=pyhd8ed1ab_3 - websocket-client=1.8.0=pyhd8ed1ab_1 - wheel=0.45.1=pyhd8ed1ab_1 - wsproto=1.2.0=pyhd8ed1ab_1 - x264=1!164.3095=h166bdaf_2 - x265=3.5=h924138e_3 - xarray=2024.7.0=pyhd8ed1ab_0 - xcb-util=0.4.1=hb711507_2 - xcb-util-cursor=0.1.5=hb9d3cd8_0 - xcb-util-image=0.4.0=hb711507_2 - xcb-util-keysyms=0.4.1=hb711507_0 - xcb-util-renderutil=0.3.10=hb711507_0 - xcb-util-wm=0.4.2=hb711507_0 - xkeyboard-config=2.43=hb9d3cd8_0 - xorg-libice=1.1.2=hb9d3cd8_0 - xorg-libsm=1.2.6=he73a12e_0 - xorg-libx11=1.8.12=h4f16b4b_0 - xorg-libxau=1.0.12=hb9d3cd8_0 - xorg-libxcomposite=0.4.6=hb9d3cd8_2 - xorg-libxcursor=1.2.3=hb9d3cd8_0 - xorg-libxdamage=1.1.6=hb9d3cd8_0 - xorg-libxdmcp=1.1.5=hb9d3cd8_0 - xorg-libxext=1.3.6=hb9d3cd8_0 - xorg-libxfixes=6.0.1=hb9d3cd8_0 - xorg-libxi=1.8.2=hb9d3cd8_0 - xorg-libxinerama=1.1.5=h5888daf_1 - xorg-libxrandr=1.5.4=hb9d3cd8_0 - xorg-libxrender=0.9.12=hb9d3cd8_0 - xorg-libxscrnsaver=1.2.4=hb9d3cd8_0 - xorg-libxtst=1.2.5=hb9d3cd8_3 - xorg-libxxf86vm=1.1.6=hb9d3cd8_0 - yaml=0.2.5=h7f98852_2 - zict=3.0.0=pyhd8ed1ab_1 - zipp=3.21.0=pyhd8ed1ab_1 - zlib=1.3.1=hb9d3cd8_2 - zstandard=0.23.0=py39h8cd3c5a_1 - zstd=1.5.7=hb8e6e7a_2 - pip: - bokeh==3.4.3 - coverage==7.8.0 - holoviews==1.19.0a4.dev20+g4bd31bcf1 - iniconfig==2.1.0 - linkify-it-py==2.0.3 - mdit-py-plugins==0.4.2 - panel==1.4.5 - param==2.2.0 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-rerunfailures==15.0 - tomli==2.2.1 - uc-micro-py==1.0.3 - xyzservices==2025.1.0 prefix: /opt/conda/envs/holoviews
[ "holoviews/tests/core/test_dimensioned.py::TestGetSetState::test_pickle_roundtrip" ]
[]
[ "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_cloned", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_current_backend_plot", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_current_backend_plot_and_style", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_current_backend_plot_multiple", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_current_backend_style", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_current_backend_style_invalid", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_current_backend_style_invalid_cross_backend_match", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_current_backend_style_invalid_no_match", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_current_backend_style_multiple", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_persist_old_backend", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_persists_other_backend_inverted", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_plot", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_plot_and_style", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_plot_multiple", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_style", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_style_invalid", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_style_invalid_cross_backend", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_style_invalid_no_match", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_explicit_backend_style_multiple", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_not_cloned", "holoviews/tests/core/test_dimensioned.py::TestDimensioned_options::test_apply_options_when_backend_switched", "holoviews/tests/core/test_dimensioned.py::TestOptionsCleanup::test_garbage_collect_cleans_unused_tree", "holoviews/tests/core/test_dimensioned.py::TestOptionsCleanup::test_opts_clear_cleans_unused_tree", "holoviews/tests/core/test_dimensioned.py::TestOptionsCleanup::test_opts_multiple_resassignment_cleans_unused_tree", "holoviews/tests/core/test_dimensioned.py::TestOptionsCleanup::test_opts_resassignment_cleans_unused_tree", "holoviews/tests/core/test_dimensioned.py::TestOptionsCleanup::test_opts_resassignment_cleans_unused_tree_cross_backend", "holoviews/tests/core/test_dimensioned.py::TestOptionsCleanup::test_partial_garbage_collect_does_not_clear_tree" ]
[]
BSD 3-Clause "New" or "Revised" License
18,622
880
[ "holoviews/core/dimension.py", "holoviews/plotting/renderer.py" ]
BoboTiG__ebook-reader-dict-2054
d6cc6741d4712018610391f1bc229fb9e0d3210e
2024-06-07 19:48:52
d6cc6741d4712018610391f1bc229fb9e0d3210e
diff --git a/wikidict/__main__.py b/wikidict/__main__.py index 16d992c0..6af1ea32 100644 --- a/wikidict/__main__.py +++ b/wikidict/__main__.py @@ -25,6 +25,7 @@ - "data/$LOCALE/dicthtml-$LOCALE-$LOCALE.zip": Kobo format. - "data/$LOCALE/dict-$LOCALE-$LOCALE.df.bz2": DictFile format. - "data/$LOCALE/dict-$LOCALE-$LOCALE.zip": StarDict format. + - "data/$LOCALE/dictorg-$LOCALE-$LOCALE.zip": DICT.org format. --find-templates DEBUG: Find all templates in use. --check-words Render words, then compare with the rendering done on the Wiktionary to catch errors. --random Randomly if --random diff --git a/wikidict/convert.py b/wikidict/convert.py index 0cb10c6c..8b3b2dec 100644 --- a/wikidict/convert.py +++ b/wikidict/convert.py @@ -39,20 +39,6 @@ <a name="{{ word }}"/><b>{{ current_word }}</b>{{ pronunciation }}{{ gender }} <br/> <br/> - {% if etymologies %} - {% for etymology in etymologies %} - {% if etymology is string %} - <p>{{ etymology }}</p> - {% else %} - <ol> - {% for sub_etymology in etymology %} - <li>{{ sub_etymology }}</li> - {% endfor %} - </ol> - {% endif %} - {% endfor %} - <br/> - {% endif %} <ol> {% for definition in definitions %} {% if definition is string %} @@ -74,6 +60,19 @@ {% endif %} {% endfor %} </ol> + {% if etymologies %} + {% for etymology in etymologies %} + {% if etymology is string %} + <p>{{ etymology }}</p> + {% else %} + <ol> + {% for sub_etymology in etymology %} + <li>{{ sub_etymology }}</li> + {% endfor %} + </ol> + {% endif %} + {% endfor %} + {% endif %} </p> {% if variants %} {{ variants }} @@ -92,22 +91,7 @@ {%- for variant in variants %} & {{ variant }} {%- endfor %} -<html> -{%- if etymologies -%} - {%- for etymology in etymologies -%} - {%- if etymology is string -%} - <p>{{ etymology }}</p> - {%- else -%} - <ol> - {%- for sub_etymology in etymology -%} - <li>{{ sub_etymology }}</li> - {%- endfor -%} - </ol> - {%- endif -%} - {%- endfor -%} - <br/> -{%- endif -%} -<ol> +<html><ol> {%- for definition in definitions -%} {%- if definition is string -%} <li>{{ definition }}</li> @@ -127,7 +111,20 @@ </ol> {%- endif -%} {%- endfor -%} -</ol></html> +</ol> +{%- if etymologies -%} + {%- for etymology in etymologies -%} + {%- if etymology is string -%} + <p>{{ etymology }}</p> + {%- else -%} + <ol> + {%- for sub_etymology in etymology -%} + <li>{{ sub_etymology }}</li> + {%- endfor -%} + </ol> + {%- endif -%} + {%- endfor -%} +{%- endif -%}</html> """ )
Move etymology at the bottom As per #1846 poll, move the etymology after definitions. <!-- POLAR PLEDGE BADGE START --> ## Upvote & Fund - We're using [Polar.sh](https://polar.sh/tiger-222) so you can upvote and help fund this issue. - We receive the funding once the issue is completed & confirmed by you. - Thank you in advance for helping prioritize & fund our backlog. <a href="https://polar.sh/BoboTiG/ebook-reader-dict/issues/2009"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/BoboTiG/ebook-reader-dict/issues/2009/pledge.svg?darkmode=1"> <img alt="Fund with Polar" src="https://polar.sh/api/github/BoboTiG/ebook-reader-dict/issues/2009/pledge.svg"> </picture> </a> <!-- POLAR PLEDGE BADGE END -->
BoboTiG/ebook-reader-dict
diff --git a/tests/test_3_convert.py b/tests/test_3_convert.py index 962c8a5d..eba6419c 100644 --- a/tests/test_3_convert.py +++ b/tests/test_3_convert.py @@ -216,7 +216,7 @@ def test_generate_secondary_dict(formatter: type[convert.BaseFormat], filename: FORMATTED_WORD_KOBO = """\ -<w><p><a name="Multiple Etymologies"/><b>Multiple Etymologies</b> pron <i>gender</i>.<br/><br/><p>etyl 1</p><ol><li>setyl 1</li></ol><br/><ol><li>def 1</li><ol style="list-style-type:lower-alpha"><li>sdef 1</li></ol></ol></p><var><variant name="multiple etymology"/></var></w> +<w><p><a name="Multiple Etymologies"/><b>Multiple Etymologies</b> pron <i>gender</i>.<br/><br/><ol><li>def 1</li><ol style="list-style-type:lower-alpha"><li>sdef 1</li></ol></ol><p>etyl 1</p><ol><li>setyl 1</li></ol></p><var><variant name="multiple etymology"/></var></w> """ FORMATTED_WORD_KOBO_NO_ETYMOLOGY = """\ <w><p><a name="Multiple Etymologies"/><b>Multiple Etymologies</b> pron <i>gender</i>.<br/><br/><ol><li>def 1</li><ol style="list-style-type:lower-alpha"><li>sdef 1</li></ol></ol></p><var><variant name="multiple etymology"/></var></w> @@ -225,7 +225,7 @@ def test_generate_secondary_dict(formatter: type[convert.BaseFormat], filename: @ Multiple Etymologies : pron <i>gender</i>. & Multiple Etymology -<html><p>etyl 1</p><ol><li>setyl 1</li></ol><br/><ol><li>def 1</li><ol style="list-style-type:lower-alpha"><li>sdef 1</li></ol></ol></html>\ +<html><ol><li>def 1</li><ol style="list-style-type:lower-alpha"><li>sdef 1</li></ol></ol><p>etyl 1</p><ol><li>setyl 1</li></ol></html>\ """
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.12", "reqs_path": [ "requirements.txt", "requirements-tests.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
beautifulsoup4==4.12.3 certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 docopt==0.6.2 idna==3.10 iniconfig==2.1.0 Jinja2==3.1.4 marisa-trie==1.2.0 MarkupSafe==3.0.2 mistune==3.0.2 mypy==1.11.2 mypy-extensions==1.0.0 packaging==24.2 pluggy==1.5.0 pyglossary==4.7.1 pytest==8.3.3 pytest-cov==5.0.0 pytest-dependency==0.6.0 python-idzip==0.3.9 PyYAML==6.0.2 regex==2024.11.6 requests==2.32.3 responses==0.25.3 ruff==0.6.9 ruff-api==0.0.8 scour==0.38.2 setuptools==75.8.0 six==1.17.0 soupsieve==2.6 types-requests==2.32.0.20240914 typing_extensions==4.13.0 urllib3==2.3.0 wcwidth==0.2.13 wheel==0.45.1 -e git+https://github.com/BoboTiG/ebook-reader-dict.git@d6cc6741d4712018610391f1bc229fb9e0d3210e#egg=wikidict wikitextparser==0.56.2
name: ebook-reader-dict channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - expat=2.6.4=h6a678d5_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py312h06a4308_0 - python=3.12.9=h5148396_0 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py312h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py312h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - beautifulsoup4==4.12.3 - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - docopt==0.6.2 - idna==3.10 - iniconfig==2.1.0 - jinja2==3.1.4 - marisa-trie==1.2.0 - markupsafe==3.0.2 - mistune==3.0.2 - mypy==1.11.2 - mypy-extensions==1.0.0 - packaging==24.2 - pluggy==1.5.0 - pyglossary==4.7.1 - pytest==8.3.3 - pytest-cov==5.0.0 - pytest-dependency==0.6.0 - python-idzip==0.3.9 - pyyaml==6.0.2 - regex==2024.11.6 - requests==2.32.3 - responses==0.25.3 - ruff==0.6.9 - ruff-api==0.0.8 - scour==0.38.2 - six==1.17.0 - soupsieve==2.6 - types-requests==2.32.0.20240914 - typing-extensions==4.13.0 - urllib3==2.3.0 - wcwidth==0.2.13 - wikidict==0.0.0 - wikitextparser==0.56.2 prefix: /opt/conda/envs/ebook-reader-dict
[ "tests/test_3_convert.py::test_word_rendering[KoboFormat-True-<w><p><a", "tests/test_3_convert.py::test_word_rendering[DictFileFormat-True-@" ]
[ "tests/test_3_convert.py::test_simple" ]
[ "tests/test_3_convert.py::test_no_json_file", "tests/test_3_convert.py::test_generate_primary_dict[DictFileFormat-dict-fr-fr.df-True]", "tests/test_3_convert.py::test_generate_primary_dict[DictFileFormat-dict-fr-fr-noetym.df-False]", "tests/test_3_convert.py::test_generate_primary_dict[KoboFormat-dicthtml-fr-fr.zip-True]", "tests/test_3_convert.py::test_generate_primary_dict[KoboFormat-dicthtml-fr-fr-noetym.zip-False]", "tests/test_3_convert.py::test_word_rendering[KoboFormat-False-<w><p><a", "tests/test_3_convert.py::test_word_rendering[DictFileFormat-False-@" ]
[]
MIT License
18,625
946
[ "wikidict/__main__.py", "wikidict/convert.py" ]
celery__kombu-2024
e32f8fc39b3135eca2aa9d70a92e35c1c94b9406
2024-06-10 11:36:56
e32f8fc39b3135eca2aa9d70a92e35c1c94b9406
diff --git a/kombu/connection.py b/kombu/connection.py index 13b1e9e5..beec4c73 100644 --- a/kombu/connection.py +++ b/kombu/connection.py @@ -1065,7 +1065,8 @@ class ConnectionPool(Resource): def setup(self): if self.limit: q = self._resource.queue - while len(q) < self.limit: + # Keep in mind dirty/used resources + while len(q) < self.limit - len(self._dirty): self._resource.put_nowait(lazy(self.new)) def prepare(self, resource): @@ -1091,7 +1092,8 @@ class ChannelPool(Resource): channel = self.new() if self.limit: q = self._resource.queue - while len(q) < self.limit: + # Keep in mind dirty/used resources + while len(q) < self.limit - len(self._dirty): self._resource.put_nowait(lazy(channel)) def prepare(self, channel): diff --git a/kombu/resource.py b/kombu/resource.py index 9f75eb06..d911587a 100644 --- a/kombu/resource.py +++ b/kombu/resource.py @@ -144,15 +144,20 @@ class Resource: def collect_resource(self, resource): pass - def force_close_all(self): + def force_close_all(self, close_pool=True): """Close and remove all resources in the pool (also those in use). Used to close resources from parent processes after fork (e.g. sockets/connections). + + Arguments: + --------- + close_pool (bool): If True (default) then the pool is marked + as closed. In case of False the pool can be reused. """ if self._closed: return - self._closed = True + self._closed = close_pool dirty = self._dirty resource = self._resource while 1: # - acquired @@ -188,7 +193,7 @@ class Resource: self._limit = limit if reset: try: - self.force_close_all() + self.force_close_all(close_pool=False) except Exception: pass self.setup() @@ -211,7 +216,9 @@ class Resource: resource = self._resource # Items to the left are last recently used, so we remove those first. with getattr(resource, 'mutex', Noop()): - while len(resource.queue) > self.limit: + # keep in mind the dirty resources are not shrinking + while len(resource.queue) and \ + (len(resource.queue) + len(self._dirty)) > self.limit: R = resource.queue.popleft() if collect: self.collect_resource(R)
ConnectionPool can't be used after .resize(..., reset=True) I close pool and then want to use it again. Reinit. I found the `.resize()` method which has option `reset`. reset=True allow close all available connections and then `.setup()` will be called, but pool will be closed (`._closed=True`) and any `.acquire()` call will raise an error. https://github.com/celery/kombu/blob/1df567a5e813b9030b858b454e51eb70ea928e6a/kombu/resource.py#L189
celery/kombu
diff --git a/t/unit/test_connection.py b/t/unit/test_connection.py index e57f4db0..4f1b71d8 100644 --- a/t/unit/test_connection.py +++ b/t/unit/test_connection.py @@ -811,6 +811,93 @@ class ResourceCase: P = self.create_resource(None) P.acquire().release() + def test_acquire_resize_in_use(self): + P = self.create_resource(5) + self.assert_state(P, 5, 0) + chans = [P.acquire() for _ in range(5)] + self.assert_state(P, 0, 5) + with pytest.raises(RuntimeError): + P.resize(4) + [chan.release() for chan in chans] + self.assert_state(P, 5, 0) + + def test_acquire_resize_ignore_err_no_shrink(self): + P = self.create_resource(5) + self.assert_state(P, 5, 0) + chans = [P.acquire() for _ in range(5)] + self.assert_state(P, 0, 5) + P.resize(4, ignore_errors=True) + self.assert_state(P, 0, 5) + [chan.release() for chan in chans] + self.assert_state(P, 5, 0) + + def test_acquire_resize_ignore_err_shrink(self): + P = self.create_resource(5) + self.assert_state(P, 5, 0) + chans = [P.acquire() for _ in range(4)] + self.assert_state(P, 1, 4) + P.resize(4, ignore_errors=True) + self.assert_state(P, 0, 4) + [chan.release() for chan in chans] + self.assert_state(P, 4, 0) + + def test_acquire_resize_larger(self): + P = self.create_resource(1) + self.assert_state(P, 1, 0) + c1 = P.acquire() + self.assert_state(P, 0, 1) + with pytest.raises(P.LimitExceeded): + P.acquire() + P.resize(2) + self.assert_state(P, 1, 1) + c2 = P.acquire() + self.assert_state(P, 0, 2) + c1.release() + c2.release() + self.assert_state(P, 2, 0) + + def test_acquire_resize_force_smaller(self): + P = self.create_resource(2) + self.assert_state(P, 2, 0) + c1 = P.acquire() + c2 = P.acquire() + self.assert_state(P, 0, 2) + with pytest.raises(P.LimitExceeded): + P.acquire() + P.resize(1, force=True) # acts like reset + del c1 + del c2 + self.assert_state(P, 1, 0) + c1 = P.acquire() + self.assert_state(P, 0, 1) + with pytest.raises(P.LimitExceeded): + P.acquire() + c1.release() + self.assert_state(P, 1, 0) + + def test_acquire_resize_reset(self): + P = self.create_resource(2) + self.assert_state(P, 2, 0) + c1 = P.acquire() + c2 = P.acquire() + self.assert_state(P, 0, 2) + with pytest.raises(P.LimitExceeded): + P.acquire() + P.resize(3, reset=True) + del c1 + del c2 + self.assert_state(P, 3, 0) + c1 = P.acquire() + c2 = P.acquire() + c3 = P.acquire() + self.assert_state(P, 0, 3) + with pytest.raises(P.LimitExceeded): + P.acquire() + c1.release() + c2.release() + c3.release() + self.assert_state(P, 3, 0) + def test_replace_when_limit(self): P = self.create_resource(10) r = P.acquire()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
5.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y libcurl4-openssl-dev libssl-dev" ], "python": "3.9", "reqs_path": [ "requirements/default.txt", "requirements/dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
amqp @ https://github.com/celery/py-amqp/zipball/main#sha256=bc618e1a51e852a457ee5aca2a8d1b46440d1304ca23f50d250d2fc216e3e499 certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup==1.2.2 execnet==2.1.1 idna==3.10 iniconfig==2.1.0 -e git+https://github.com/celery/kombu.git@e32f8fc39b3135eca2aa9d70a92e35c1c94b9406#egg=kombu packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 requests==2.31.0 tomli==2.2.1 typing_extensions==4.12.1 urllib3==2.3.0 vine @ https://github.com/celery/vine/zipball/master#sha256=955be2b59aaf8e6b68540d03a5af8dc493f6ef3dacbdcc977907f9909e6c866e
name: kombu channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - amqp==5.3.1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - requests==2.31.0 - tomli==2.2.1 - typing-extensions==4.12.1 - urllib3==2.3.0 - vine==5.1.0 prefix: /opt/conda/envs/kombu
[ "t/unit/test_connection.py::test_ConnectionPool::test_acquire_resize_ignore_err_no_shrink", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_resize_ignore_err_shrink", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_resize_larger", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_resize_force_smaller", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_resize_reset", "t/unit/test_connection.py::test_ChannelPool::test_acquire_resize_ignore_err_no_shrink", "t/unit/test_connection.py::test_ChannelPool::test_acquire_resize_ignore_err_shrink", "t/unit/test_connection.py::test_ChannelPool::test_acquire_resize_larger", "t/unit/test_connection.py::test_ChannelPool::test_acquire_resize_force_smaller", "t/unit/test_connection.py::test_ChannelPool::test_acquire_resize_reset" ]
[]
[ "t/unit/test_connection.py::test_connection_utils::test_parse_url", "t/unit/test_connection.py::test_connection_utils::test_parse_generated_as_uri", "t/unit/test_connection.py::test_connection_utils::test_bogus_scheme", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://user:pass@host:10000/vhost-expected0]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://user%61:%61pass@ho%61st:10000/v%2fhost-expected1]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://-expected2]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://:@/-expected3]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://user@/-expected4]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://user:pass@/-expected5]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://host-expected6]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://:10000-expected7]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp:///vhost-expected8]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://host/-expected9]", "t/unit/test_connection.py::test_connection_utils::test_rabbitmq_example_urls[amqp://host/%2f-expected10]", "t/unit/test_connection.py::test_connection_utils::test_connection_copy", "t/unit/test_connection.py::test_Connection::test_establish_connection", "t/unit/test_connection.py::test_Connection::test_reuse_connection", "t/unit/test_connection.py::test_Connection::test_connect_no_transport_options", "t/unit/test_connection.py::test_Connection::test_connect_transport_options", "t/unit/test_connection.py::test_Connection::test_multiple_urls", "t/unit/test_connection.py::test_Connection::test_collect", "t/unit/test_connection.py::test_Connection::test_prefer_librabbitmq_over_amqp_when_available", "t/unit/test_connection.py::test_Connection::test_select_amqp_when_librabbitmq_is_not_available", "t/unit/test_connection.py::test_Connection::test_collect_no_transport", "t/unit/test_connection.py::test_Connection::test_collect_transport_gone", "t/unit/test_connection.py::test_Connection::test_uri_passthrough", "t/unit/test_connection.py::test_Connection::test_ensure_connection_on_error", "t/unit/test_connection.py::test_Connection::test_supports_heartbeats", "t/unit/test_connection.py::test_Connection::test_is_evented", "t/unit/test_connection.py::test_Connection::test_register_with_event_loop", "t/unit/test_connection.py::test_Connection::test_manager", "t/unit/test_connection.py::test_Connection::test_copy", "t/unit/test_connection.py::test_Connection::test_copy_multiples", "t/unit/test_connection.py::test_Connection::test_switch", "t/unit/test_connection.py::test_Connection::test_maybe_switch_next", "t/unit/test_connection.py::test_Connection::test_maybe_switch_next_no_cycle", "t/unit/test_connection.py::test_Connection::test_switch_without_uri_identifier", "t/unit/test_connection.py::test_Connection::test_heartbeat_check", "t/unit/test_connection.py::test_Connection::test_completes_cycle_no_cycle", "t/unit/test_connection.py::test_Connection::test_completes_cycle", "t/unit/test_connection.py::test_Connection::test_get_heartbeat_interval", "t/unit/test_connection.py::test_Connection::test_supports_exchange_type", "t/unit/test_connection.py::test_Connection::test_qos_semantics_matches_spec", "t/unit/test_connection.py::test_Connection::test__enter____exit__", "t/unit/test_connection.py::test_Connection::test_close_survives_connerror", "t/unit/test_connection.py::test_Connection::test_close_when_default_channel", "t/unit/test_connection.py::test_Connection::test_auto_reconnect_default_channel", "t/unit/test_connection.py::test_Connection::test_close_when_default_channel_close_raises", "t/unit/test_connection.py::test_Connection::test_revive_when_default_channel", "t/unit/test_connection.py::test_Connection::test_ensure_connection", "t/unit/test_connection.py::test_Connection::test_ensure_success", "t/unit/test_connection.py::test_Connection::test_ensure_failure", "t/unit/test_connection.py::test_Connection::test_ensure_connection_failure", "t/unit/test_connection.py::test_Connection::test_ensure_retry_errors_is_limited_by_max_retries", "t/unit/test_connection.py::test_Connection::test_autoretry", "t/unit/test_connection.py::test_Connection::test_SimpleQueue", "t/unit/test_connection.py::test_Connection::test_SimpleBuffer", "t/unit/test_connection.py::test_Connection::test_SimpleQueue_with_parameters", "t/unit/test_connection.py::test_Connection::test_SimpleBuffer_with_parameters", "t/unit/test_connection.py::test_Connection::test_Producer", "t/unit/test_connection.py::test_Connection::test_Consumer", "t/unit/test_connection.py::test_Connection::test__repr__", "t/unit/test_connection.py::test_Connection::test__reduce__", "t/unit/test_connection.py::test_Connection::test_channel_errors", "t/unit/test_connection.py::test_Connection::test_channel_errors__exception_no_cache", "t/unit/test_connection.py::test_Connection::test_connection_errors", "t/unit/test_connection.py::test_Connection::test_connection_errors__exception_no_cache", "t/unit/test_connection.py::test_Connection::test_recoverable_connection_errors", "t/unit/test_connection.py::test_Connection::test_recoverable_connection_errors__fallback", "t/unit/test_connection.py::test_Connection::test_recoverable_connection_errors__exception_no_cache", "t/unit/test_connection.py::test_Connection::test_recoverable_channel_errors", "t/unit/test_connection.py::test_Connection::test_recoverable_channel_errors__fallback", "t/unit/test_connection.py::test_Connection::test_recoverable_channel_errors__exception_no_cache", "t/unit/test_connection.py::test_Connection::test_multiple_urls_hostname", "t/unit/test_connection.py::test_Connection::test_connection_respect_its_timeout", "t/unit/test_connection.py::test_Connection::test_connection_failover_without_total_timeout", "t/unit/test_connection.py::test_Connection::test_connection_failover_with_total_timeout", "t/unit/test_connection.py::test_Connection_with_transport_options::test_establish_connection", "t/unit/test_connection.py::test_ConnectionPool::test_acquire__release", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_prepare_raises", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_no_limit", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_resize_in_use", "t/unit/test_connection.py::test_ConnectionPool::test_replace_when_limit", "t/unit/test_connection.py::test_ConnectionPool::test_replace_no_limit", "t/unit/test_connection.py::test_ConnectionPool::test_interface_prepare", "t/unit/test_connection.py::test_ConnectionPool::test_force_close_all_handles_AttributeError", "t/unit/test_connection.py::test_ConnectionPool::test_force_close_all_no_mutex", "t/unit/test_connection.py::test_ConnectionPool::test_add_when_empty", "t/unit/test_connection.py::test_ConnectionPool::test_collect_resource__does_not_collect_lazy_resource", "t/unit/test_connection.py::test_ConnectionPool::test_collect_resource", "t/unit/test_connection.py::test_ConnectionPool::test_setup", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_raises_evaluated", "t/unit/test_connection.py::test_ConnectionPool::test_release_no__debug", "t/unit/test_connection.py::test_ConnectionPool::test_setup_no_limit", "t/unit/test_connection.py::test_ConnectionPool::test_prepare_not_callable", "t/unit/test_connection.py::test_ConnectionPool::test_acquire_channel", "t/unit/test_connection.py::test_ChannelPool::test_acquire__release", "t/unit/test_connection.py::test_ChannelPool::test_acquire_prepare_raises", "t/unit/test_connection.py::test_ChannelPool::test_acquire_no_limit", "t/unit/test_connection.py::test_ChannelPool::test_acquire_resize_in_use", "t/unit/test_connection.py::test_ChannelPool::test_replace_when_limit", "t/unit/test_connection.py::test_ChannelPool::test_replace_no_limit", "t/unit/test_connection.py::test_ChannelPool::test_interface_prepare", "t/unit/test_connection.py::test_ChannelPool::test_force_close_all_handles_AttributeError", "t/unit/test_connection.py::test_ChannelPool::test_force_close_all_no_mutex", "t/unit/test_connection.py::test_ChannelPool::test_add_when_empty", "t/unit/test_connection.py::test_ChannelPool::test_setup", "t/unit/test_connection.py::test_ChannelPool::test_setup_no_limit", "t/unit/test_connection.py::test_ChannelPool::test_prepare_not_callable" ]
[]
BSD 3-Clause "New" or "Revised" License
18,636
665
[ "kombu/connection.py", "kombu/resource.py" ]
tkrajina__gpxpy-282
017d9961ee9aa86ccdbf5bb50a4e2341d5c42f4b
2024-06-10 18:06:51
017d9961ee9aa86ccdbf5bb50a4e2341d5c42f4b
diff --git a/gpxpy/gpxfield.py b/gpxpy/gpxfield.py index d31200a..e253df3 100644 --- a/gpxpy/gpxfield.py +++ b/gpxpy/gpxfield.py @@ -16,6 +16,7 @@ import inspect as mod_inspect import datetime as mod_datetime import re as mod_re import copy as mod_copy +import xml.sax.saxutils as mod_saxutils from . import utils as mod_utils @@ -400,8 +401,7 @@ class GPXExtensionsField(AbstractGPXField): result.append(f' {attrib}="{value}"') result.append('>') if node.text is not None: - result.append(node.text.strip()) - + result.append(mod_saxutils.escape(node.text).strip()) # Build subelement nodes for child in node: @@ -412,7 +412,7 @@ class GPXExtensionsField(AbstractGPXField): # Add tail and close tag tail = node.tail if tail is not None: - tail = tail.strip() + tail = mod_saxutils.escape(tail.strip()) else: tail = '' if len(node) > 0:
Custom attributes in `to_xml` not escaped properly It seems that if `to_xml()` is called to produce a XML file, certain conditions can cause a XML with invalid syntax to be produced. This happens whenever there are custom attributes in a waypoint. Even though the regular attributes seem to escape properly (e.g. `&` to `&amp;`), this validation doesn't seem to be done for the custom attributes. Here is an example of a failure case: ``` <wpt lat="52.4824535" lon="13.4451467"> <time>2024-02-12T12:48:53Z</time> <name>Du Beast drinks &amp; coffee</name> <desc>Innstraße 4, Neukölln</desc> <sym>amenity_pub</sym> <extensions> <osmand:amenity_name>Du Beast drinks & coffee</osmand:amenity_name> <osmand:amenity_origin>Amenity:Du Beast drinks & coffee: sustenance:bar</osmand:amenity_origin> </extensions> </wpt> ``` This is invalid XML cause there is a disallowed ampersand at line 7 (`drinks & coffee`). This can easily be reproduced by using a GPX file with custom attributes (e.g. from OSMAnd in this case) that contain any of the special characters that are invalid in XML such as `&`.
tkrajina/gpxpy
diff --git a/test.py b/test.py index e5b60d5..7dd6f44 100644 --- a/test.py +++ b/test.py @@ -2649,6 +2649,18 @@ class GPXTests(mod_unittest.TestCase): self.assertTrue('<name>Test&lt;a&gt;jkljkl&lt;/gpx&gt;</name>' in gpx_2.to_xml()) + def test_xml_chars_encode_decode_extensions(self) -> None: + gpx = mod_gpxpy.gpx.GPX() + ext = mod_etree.Element('test') + ext.text = "Test<a>jkljkl</gpx>" + ext.tail = "<&tail>" + gpx.extensions.append(ext) + print(gpx.to_xml()) + gpx_2 = mod_gpxpy.parse(gpx.to_xml()) + self.assertTrue('<test>Test&lt;a&gt;jkljkl&lt;/gpx&gt;</test>' in gpx_2.to_xml()) + self.assertTrue('&lt;&amp;tail&gt;' in gpx_2.to_xml()) + + def test_10_to_11_conversion(self) -> None: """ This test checks that reparsing from 1.0 to 1.1 and from 1.1 to 1.0
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "lxml", "coverage", "mypy", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 -e git+https://github.com/tkrajina/gpxpy.git@017d9961ee9aa86ccdbf5bb50a4e2341d5c42f4b#egg=gpxpy iniconfig==2.1.0 lxml==5.3.1 mypy==1.15.0 mypy-extensions==1.0.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1 typing_extensions==4.13.0
name: gpxpy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - lxml==5.3.1 - mypy==1.15.0 - mypy-extensions==1.0.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 - typing-extensions==4.13.0 prefix: /opt/conda/envs/gpxpy
[ "test.py::GPXTests::test_xml_chars_encode_decode_extensions" ]
[]
[ "test.py::GPXTests::test_10_to_11_conversion", "test.py::GPXTests::test_add_elevation", "test.py::GPXTests::test_add_missing_data_no_intervals", "test.py::GPXTests::test_add_missing_data_one_interval", "test.py::GPXTests::test_add_missing_data_one_interval_and_empty_points_on_start_and_end", "test.py::GPXTests::test_add_missing_elevations", "test.py::GPXTests::test_add_missing_elevations_without_ele", "test.py::GPXTests::test_add_missing_speeds", "test.py::GPXTests::test_add_missing_times", "test.py::GPXTests::test_add_missing_times_2", "test.py::GPXTests::test_adjust_time_all", "test.py::GPXTests::test_adjust_time_tracks_only", "test.py::GPXTests::test_angle", "test.py::GPXTests::test_angle_0", "test.py::GPXTests::test_angle_2", "test.py::GPXTests::test_angle_3", "test.py::GPXTests::test_angle_4", "test.py::GPXTests::test_angle_loc", "test.py::GPXTests::test_bounds", "test.py::GPXTests::test_bounds_xml", "test.py::GPXTests::test_clone_and_smooth", "test.py::GPXTests::test_course_between", "test.py::GPXTests::test_creator_field", "test.py::GPXTests::test_custom_schema_locations", "test.py::GPXTests::test_default_schema_locations", "test.py::GPXTests::test_delta_add_and_move", "test.py::GPXTests::test_dilutions", "test.py::GPXTests::test_distance", "test.py::GPXTests::test_distance_between_points_near_0_longitude", "test.py::GPXTests::test_distance_from_line", "test.py::GPXTests::test_dst_in_SimpleTZ", "test.py::GPXTests::test_extension_without_namespaces", "test.py::GPXTests::test_force_version", "test.py::GPXTests::test_format_time", "test.py::GPXTests::test_garmin_extension", "test.py::GPXTests::test_get_bounds_and_refresh_bounds", "test.py::GPXTests::test_get_course", "test.py::GPXTests::test_get_duration", "test.py::GPXTests::test_get_location_at", "test.py::GPXTests::test_gpx_10_fields", "test.py::GPXTests::test_gpx_11_fields", "test.py::GPXTests::test_gpx_fill_time_data_raises_when_force_is_false", "test.py::GPXTests::test_gpx_fill_time_data_raises_when_not_enough_parameters", "test.py::GPXTests::test_gpx_fill_time_data_raises_when_start_time_after_end_time", "test.py::GPXTests::test_gpx_fill_time_data_with_end_time_and_time_delta", "test.py::GPXTests::test_gpx_fill_time_data_with_start_time_and_end_time", "test.py::GPXTests::test_gpx_fill_time_data_with_start_time_and_end_time_and_time_delta", "test.py::GPXTests::test_gpx_fill_time_data_with_start_time_and_time_delta", "test.py::GPXTests::test_has_elevation_false", "test.py::GPXTests::test_has_elevation_true", "test.py::GPXTests::test_has_times", "test.py::GPXTests::test_has_times_false", "test.py::GPXTests::test_haversine_and_nonhaversine", "test.py::GPXTests::test_haversine_distance", "test.py::GPXTests::test_horizontal_and_vertical_smooth_remove_extremes", "test.py::GPXTests::test_horizontal_smooth_remove_extremes", "test.py::GPXTests::test_ignore_maximums_for_max_speed", "test.py::GPXTests::test_join_gpx_xml_files", "test.py::GPXTests::test_large_float_values", "test.py::GPXTests::test_location_delta", "test.py::GPXTests::test_location_delta_equality", "test.py::GPXTests::test_location_equator_delta_distance_111120", "test.py::GPXTests::test_location_equator_delta_distance_50", "test.py::GPXTests::test_location_nonequator_delta_distance_111120", "test.py::GPXTests::test_location_nonequator_delta_distance_50", "test.py::GPXTests::test_long_timestamps", "test.py::GPXTests::test_microsecond", "test.py::GPXTests::test_min_max", "test.py::GPXTests::test_moving_stopped_times", "test.py::GPXTests::test_name_comment_and_symbol", "test.py::GPXTests::test_named_tuples_values_elevation_extremes", "test.py::GPXTests::test_named_tuples_values_moving_data", "test.py::GPXTests::test_named_tuples_values_nearest_location_data", "test.py::GPXTests::test_named_tuples_values_point_data", "test.py::GPXTests::test_named_tuples_values_time_bounds", "test.py::GPXTests::test_named_tuples_values_uphill_downhill", "test.py::GPXTests::test_nan_elevation", "test.py::GPXTests::test_nearest_location_1", "test.py::GPXTests::test_no_10_extensions", "test.py::GPXTests::test_no_creator_field", "test.py::GPXTests::test_no_track", "test.py::GPXTests::test_parse_bytes", "test.py::GPXTests::test_parse_custom_schema_locations", "test.py::GPXTests::test_parse_gpx_with_node_with_comments", "test.py::GPXTests::test_parse_time", "test.py::GPXTests::test_positions_on_track", "test.py::GPXTests::test_positions_on_track_2", "test.py::GPXTests::test_raw_max_speed", "test.py::GPXTests::test_read_extensions", "test.py::GPXTests::test_reduce_by_min_distance", "test.py::GPXTests::test_reduce_gpx_file", "test.py::GPXTests::test_remove_elevation", "test.py::GPXTests::test_remove_point_from_segment", "test.py::GPXTests::test_remove_time_all", "test.py::GPXTests::test_remove_time_tracks_only", "test.py::GPXTests::test_simple_parse_function", "test.py::GPXTests::test_simple_parse_function_invalid_root_tag", "test.py::GPXTests::test_simple_parse_function_invalid_xml", "test.py::GPXTests::test_simplify", "test.py::GPXTests::test_simplify_circular_gpx", "test.py::GPXTests::test_single_quotes_xmlns", "test.py::GPXTests::test_small_floats", "test.py::GPXTests::test_smooth_without_removing_extreemes_preserves_point_count", "test.py::GPXTests::test_smooth_without_removing_extreemes_preserves_point_count_2", "test.py::GPXTests::test_smooth_without_removing_extreemes_preserves_point_count_3", "test.py::GPXTests::test_spaces_in_elevation", "test.py::GPXTests::test_speed", "test.py::GPXTests::test_speed_ignore_top_speed_percentiles", "test.py::GPXTests::test_split", "test.py::GPXTests::test_split_and_join", "test.py::GPXTests::test_split_on_impossible_index", "test.py::GPXTests::test_split_tracks_without_gpxpy", "test.py::GPXTests::test_subsecond_speed", "test.py::GPXTests::test_time_bounds", "test.py::GPXTests::test_time_difference", "test.py::GPXTests::test_timestamp_with_single_digits", "test.py::GPXTests::test_timezone_from_timestamp", "test.py::GPXTests::test_to_xml_creator", "test.py::GPXTests::test_total_time_none", "test.py::GPXTests::test_total_time_support_less_one_sec", "test.py::GPXTests::test_track_points_data", "test.py::GPXTests::test_track_with_elevation_zero", "test.py::GPXTests::test_track_with_empty_segment", "test.py::GPXTests::test_track_with_some_points_are_without_elevations", "test.py::GPXTests::test_track_without_elevation", "test.py::GPXTests::test_unicode", "test.py::GPXTests::test_unicode_2", "test.py::GPXTests::test_unicode_bom", "test.py::GPXTests::test_unicode_bom_noencoding", "test.py::GPXTests::test_unicode_name", "test.py::GPXTests::test_uphill_downhill_with_no_elevations", "test.py::GPXTests::test_vertical_smooth_remove_extremes", "test.py::GPXTests::test_walk_gpx_points", "test.py::GPXTests::test_walk_gpx_points2", "test.py::GPXTests::test_walk_route_points", "test.py::GPXTests::test_walk_segment_points", "test.py::GPXTests::test_waypoint_time", "test.py::GPXTests::test_waypoints_equality_after_reparse", "test.py::GPXTests::test_with_ns_namespace", "test.py::GPXTests::test_write_read_extensions", "test.py::GPXTests::test_xml_chars_encode_decode", "test.py::GPXTests::test_zero_latlng" ]
[]
Apache License 2.0
18,645
287
[ "gpxpy/gpxfield.py" ]
modin-project__modin-7307
af5ed0628a4a609f70becd29fd081a290ba981a0
2024-06-11 02:35:04
af5ed0628a4a609f70becd29fd081a290ba981a0
diff --git a/modin/config/envvars.py b/modin/config/envvars.py index 3f83ec1f..d05a7117 100644 --- a/modin/config/envvars.py +++ b/modin/config/envvars.py @@ -13,7 +13,6 @@ """Module houses Modin configs originated from environment variables.""" -import importlib import os import secrets import sys @@ -771,36 +770,6 @@ class DocModule(EnvironmentVariable, type=ExactStr): varname = "MODIN_DOC_MODULE" default = "pandas" - @classmethod - def put(cls, value: str) -> None: - """ - Assign a value to the DocModule config. - - Parameters - ---------- - value : str - Config value to set. - """ - super().put(value) - # Reload everything to apply the documentation. This is required since the - # docs might already have been created and the implementation will assume - # that the new docs are applied when the config is set. This set of operations - # does this. - import modin.pandas as pd - - importlib.reload(pd.accessor) - importlib.reload(pd.base) - importlib.reload(pd.dataframe) - importlib.reload(pd.general) - importlib.reload(pd.groupby) - importlib.reload(pd.io) - importlib.reload(pd.iterator) - importlib.reload(pd.series) - importlib.reload(pd.series_utils) - importlib.reload(pd.utils) - importlib.reload(pd.window) - importlib.reload(pd) - class DaskThreadsPerWorker(EnvironmentVariable, type=int): """Number of threads per Dask worker.""" diff --git a/modin/utils.py b/modin/utils.py index fdc5260b..2a7df885 100644 --- a/modin/utils.py +++ b/modin/utils.py @@ -378,6 +378,129 @@ def _replace_doc( target_obj.__doc__ = doc +# This is a map from objects whose docstrings we are overriding to functions that +# take a DocModule string and override the docstring according to the +# DocModule. When we update DocModule, we can use this map to update all +# inherited docstrings. +_docstring_inheritance_calls: list[Callable[[str], None]] = [] + + +def _documentable_obj(obj: object) -> bool: + """ + Check whether we can replace the docstring of `obj`. + + Parameters + ---------- + obj : object + Object whose docstring we want to replace. + + Returns + ------- + bool + Whether we can replace the docstring. + """ + return bool( + callable(obj) + and not inspect.isclass(obj) + or (isinstance(obj, property) and obj.fget) + or (isinstance(obj, functools.cached_property)) + or (isinstance(obj, (staticmethod, classmethod)) and obj.__func__) + ) + + +def _update_inherited_docstrings(doc_module: DocModule) -> None: + """ + Update all inherited docstrings. + + Parameters + ---------- + doc_module : DocModule + The current DocModule. + """ + _doc_module = doc_module.get() + for doc_inheritance_call in _docstring_inheritance_calls: + doc_inheritance_call(doc_module=_doc_module) # type: ignore[call-arg] + + +def _inherit_docstrings_in_place( + cls_or_func: Fn, + doc_module: str, + parent: object, + excluded: List[object], + overwrite_existing: bool = False, + apilink: Optional[Union[str, List[str]]] = None, +) -> None: + """ + Replace `cls_or_func` docstrings with `parent` docstrings in place. + + Parameters + ---------- + cls_or_func : Fn + The class or function whose docstrings we need to update. + doc_module : str + The docs module. + parent : object + Parent object from which the decorated object inherits __doc__. + excluded : list, default: [] + List of parent objects from which the class does not + inherit docstrings. + overwrite_existing : bool, default: False + Allow overwriting docstrings that already exist in + the decorated class. + apilink : str | List[str], optional + If non-empty, insert the link(s) to pandas API documentation. + Should be the prefix part in the URL template, e.g. "pandas.DataFrame". + """ + # Import the docs module and get the class (e.g. `DataFrame`). + imported_doc_module = importlib.import_module(doc_module) + # Set the default parent so we can use it in case some docs are missing from + # parent module. + default_parent = parent + # Try to get the parent object from the doc module, and if it isn't there, + # get it from parent instead. We only do this if we are overriding pandas + # documentation. We don't touch other docs. + if doc_module != DocModule.default and "pandas" in str( + getattr(parent, "__module__", "") + ): + parent = getattr(imported_doc_module, getattr(parent, "__name__", ""), parent) + if parent != default_parent: + # Reset API link in case the docs are overridden. + apilink = None + overwrite_existing = True + + if parent not in excluded: + _replace_doc(parent, cls_or_func, overwrite_existing, apilink) + + if not isinstance(cls_or_func, types.FunctionType): + seen = set() + for base in cls_or_func.__mro__: # type: ignore[attr-defined] + if base is object: + continue + for attr, obj in base.__dict__.items(): + if attr in seen: + continue + seen.add(attr) + # Try to get the attribute from the docs class first, then + # from the default parent (pandas), and if it's not in either, + # set `parent_obj` to `None`. + parent_obj = getattr(parent, attr, getattr(default_parent, attr, None)) + if ( + parent_obj in excluded + or not _documentable_obj(parent_obj) + or not _documentable_obj(obj) + ): + continue + + _replace_doc( + parent_obj, + obj, + overwrite_existing, + apilink, + parent_cls=cls_or_func, + attr_name=attr, + ) + + def _inherit_docstrings( parent: object, excluded: List[object] = [], @@ -416,73 +539,26 @@ def _inherit_docstrings( are not defined in target class (but are defined in the ancestor class), which means that ancestor class attribute docstrings could also change. """ - # Import the docs module and get the class (e.g. `DataFrame`). - imported_doc_module = importlib.import_module(DocModule.get()) - # Set the default parent so we can use it in case some docs are missing from - # parent module. - default_parent = parent - # Try to get the parent object from the doc module, and if it isn't there, - # get it from parent instead. We only do this if we are overriding pandas - # documentation. We don't touch other docs. - if DocModule.get() != DocModule.default and "pandas" in str( - getattr(parent, "__module__", "") - ): - parent = getattr(imported_doc_module, getattr(parent, "__name__", ""), parent) - if parent != default_parent: - # Reset API link in case the docs are overridden. - apilink = None - overwrite_existing = True - - def _documentable_obj(obj: object) -> bool: - """Check if `obj` docstring could be patched.""" - return bool( - callable(obj) - and not inspect.isclass(obj) - or (isinstance(obj, property) and obj.fget) - or (isinstance(obj, functools.cached_property)) - or (isinstance(obj, (staticmethod, classmethod)) and obj.__func__) - ) def decorator(cls_or_func: Fn) -> Fn: - if parent not in excluded: - _replace_doc(parent, cls_or_func, overwrite_existing, apilink) - - if not isinstance(cls_or_func, types.FunctionType): - seen = set() - for base in cls_or_func.__mro__: # type: ignore[attr-defined] - if base is object: - continue - for attr, obj in base.__dict__.items(): - if attr in seen: - continue - seen.add(attr) - # Try to get the attribute from the docs class first, then - # from the default parent (pandas), and if it's not in either, - # set `parent_obj` to `None`. - parent_obj = getattr( - parent, attr, getattr(default_parent, attr, None) - ) - if ( - parent_obj in excluded - or not _documentable_obj(parent_obj) - or not _documentable_obj(obj) - ): - continue - - _replace_doc( - parent_obj, - obj, - overwrite_existing, - apilink, - parent_cls=cls_or_func, - attr_name=attr, - ) - + inherit_docstring_in_place = functools.partial( + _inherit_docstrings_in_place, + cls_or_func=cls_or_func, + parent=parent, + excluded=excluded, + overwrite_existing=overwrite_existing, + apilink=apilink, + ) + inherit_docstring_in_place(doc_module=DocModule.get()) + _docstring_inheritance_calls.append(inherit_docstring_in_place) return cls_or_func return decorator +DocModule.subscribe(_update_inherited_docstrings) + + def expanduser_path_arg(argname: str) -> Callable[[Fn], Fn]: """ Decorate a function replacing its path argument with "user-expanded" value.
BUG: using docstring extensions causes several incorrect behaviors because DataFrame, Series, and BasePandasDataset cannot recognize each other ### Modin version checks - [X] I have checked that this issue has not already been reported. - [X] I have confirmed this bug exists on the latest released version of Modin. - [X] I have confirmed this bug exists on the main branch of Modin. (In order to do this you can follow [this guide](https://modin.readthedocs.io/en/stable/getting_started/installation.html#installing-from-the-github-master-branch).) ### Reproducible Example ```python import pandas import numpy as np import modin.pandas as pd from modin.config import DocModule assert pd.DataFrame([True]).all(axis=None) is np.bool_(True) DocModule.put("modin.config.test.docs_module") # Test for override assert ( pd.DataFrame.apply.__doc__ == "This is a test of the documentation module for DataFrame." ) # Test for pandas doc when method is not defined on the plugin module assert pandas.DataFrame.isna.__doc__ in pd.DataFrame.isna.__doc__ assert pandas.DataFrame.isnull.__doc__ in pd.DataFrame.isnull.__doc__ # Test for override assert ( pd.Series.isna.__doc__ == "This is a test of the documentation module for Series." ) # Test for pandas doc when method is not defined on the plugin module assert pandas.Series.isnull.__doc__ in pd.Series.isnull.__doc__ assert pandas.Series.apply.__doc__ in pd.Series.apply.__doc__ # Test for override assert pd.read_csv.__doc__ == "Test override for functions on the module." # Test for pandas doc when function is not defined on module. assert pandas.read_table.__doc__ in pd.read_table.__doc__ assert pd.DataFrame([True]).all(axis=None) is np.bool_(True) ``` ### Issue Description The reproducible example is a modified version of `modin/config/test/test_envvars.py::test_doc_module` at modin commit a616e4cc4944b4ad3c3daf446adf06714e22ad34. The cause is that we redefine `BasePandasDataset`, `Series`, and `DataFrame` twice each: 1. define `BasePandasDataset`, then `Series`, then `DataFrame` when we first load `modin.pandas` 1. redefine `BasePandasDataset` when we do `importlib.reload(pd.base)` [here](https://github.com/modin-project/modin/blob/553eb5cf5f3bb255999720ab9539ffc4964677f1/modin/config/envvars.py#L880) because we're adding the doc module. 1. redefine `DataFrame` when we do `importlib.reload(pd.dataframe)` [here](https://github.com/modin-project/modin/blob/553eb5cf5f3bb255999720ab9539ffc4964677f1/modin/config/envvars.py#L881) because we're adding the doc module. 1. redefine `Series` when we do `importlib.reload(pd.series)` [here](https://github.com/modin-project/modin/blob/553eb5cf5f3bb255999720ab9539ffc4964677f1/modin/config/envvars.py#L881) because we're adding the doc module. When we execute `all`, `BasePandasDataset` [here](https://github.com/modin-project/modin/blob/553eb5cf5f3bb255999720ab9539ffc4964677f1/modin/pandas/base.py#L857C35-L857C52), `BasePandasDataset` is the second `BasePandasDataset` class, but `result` is an instance of the first `BasePandasDataset` class because [dataframe imported `Series`](https://github.com/modin-project/modin/blob/553eb5cf5f3bb255999720ab9539ffc4964677f1/modin/pandas/dataframe.py#L66) before the `series` module was reloaded. So `result` should be an instance of `BasePandasDataset`, but it's not, so we skip the extra reduction and end up with a `Series` result instead of a boolean. There's no good order to do the reloads in because all three classes need to reference each other. We could do `import modin.pandas.base as modin_base` and always do `base.BasePandasDataset` instead of `from modin.pandas.base import BsaePandasDataset`, but that's hadr to read. Proposed solution: instead of doing `importlib.reload`, we should update docstrings in place when we do `DocModule.put()`. ### Expected Behavior `all(axis=None)` should always return a boolean. In general, `BasePandasDataset`, `Series`, and `DataFrame` should all be able to reference each other. ### Error Logs <details> ```python-traceback ___________________________________________________________________ test_doc_module ____________________________________________________________________ def test_doc_module(): import pandas import numpy as np import modin.pandas as pd from modin.config import DocModule assert pd.DataFrame([True]).all(axis=None) is np.bool_(True) DocModule.put("modin.config.test.docs_module") # Test for override assert ( pd.DataFrame.apply.__doc__ == "This is a test of the documentation module for DataFrame." ) # Test for pandas doc when method is not defined on the plugin module assert pandas.DataFrame.isna.__doc__ in pd.DataFrame.isna.__doc__ assert pandas.DataFrame.isnull.__doc__ in pd.DataFrame.isnull.__doc__ # Test for override assert ( pd.Series.isna.__doc__ == "This is a test of the documentation module for Series." ) # Test for pandas doc when method is not defined on the plugin module assert pandas.Series.isnull.__doc__ in pd.Series.isnull.__doc__ assert pandas.Series.apply.__doc__ in pd.Series.apply.__doc__ # Test for override assert pd.read_csv.__doc__ == "Test override for functions on the module." # Test for pandas doc when function is not defined on module. assert pandas.read_table.__doc__ in pd.read_table.__doc__ > assert pd.DataFrame([True]).all(axis=None) is np.bool_(True) E AssertionError: assert 0 True\ndtype: bool is True E + where 0 True\ndtype: bool = <bound method BasePandasDataset.all of 0\n0 True>(axis=None) E + where <bound method BasePandasDataset.all of 0\n0 True> = 0\n0 True.all E + where 0\n0 True = <class 'modin.pandas.dataframe.DataFrame'>([True]) E + where <class 'modin.pandas.dataframe.DataFrame'> = <module 'modin.pandas' from '/Users/mvashishtha/sources/modin/modin/pandas/__init__.py'>.DataFrame E + and True = <class 'numpy.bool_'>(True) E + where <class 'numpy.bool_'> = <module 'numpy' from '/Users/mvashishtha/miniconda3/envs/modin-latest/lib/python3.9/site-packages/numpy/__init__.py'>.bool_ modin/config/test/test_envvars.py:116: AssertionErro ``` </details> ### Installed Versions <details> INSTALLED VERSIONS ------------------ commit : a616e4cc4944b4ad3c3daf446adf06714e22ad34 python : 3.9.18.final.0 python-bits : 64 OS : Darwin OS-release : 23.4.0 Version : Darwin Kernel Version 23.4.0: Wed Feb 21 21:45:49 PST 2024; root:xnu-10063.101.15~2/RELEASE_ARM64_T6020 machine : arm64 processor : arm byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8 Modin dependencies ------------------ modin : 0.28.0+35.ga616e4cc.dirty ray : 2.8.0 dask : 2024.3.1 distributed : 2024.3.1 hdk : None pandas dependencies ------------------- pandas : 2.2.1 numpy : 1.26.1 pytz : 2023.3.post1 dateutil : 2.8.2 setuptools : 68.0.0 pip : 23.3 Cython : None pytest : 8.1.1 hypothesis : None sphinx : 7.2.6 blosc : None feather : None xlsxwriter : None lxml.etree : 5.1.0 html5lib : None pymysql : None psycopg2 : 2.9.9 jinja2 : 3.1.2 IPython : 8.17.2 pandas_datareader : None adbc-driver-postgresql: None adbc-driver-sqlite : None bs4 : 4.12.3 bottleneck : None dataframe-api-compat : None fastparquet : 2024.2.0 fsspec : 2024.3.1 gcsfs : None matplotlib : 3.8.1 numba : None numexpr : 2.8.4 odfpy : None openpyxl : 3.1.2 pandas_gbq : 0.22.0 pyarrow : 14.0.1 pyreadstat : None python-calamine : None pyxlsb : None s3fs : 2024.3.1 scipy : 1.11.3 sqlalchemy : 2.0.29 tables : 3.9.2 tabulate : None xarray : 2024.2.0 xlrd : 2.0.1 zstandard : None tzdata : 2023.3 qtpy : None pyqt5 : None </details>
modin-project/modin
diff --git a/modin/tests/config/test_envvars.py b/modin/tests/config/test_envvars.py index 4fc1b651..c1fa009d 100644 --- a/modin/tests/config/test_envvars.py +++ b/modin/tests/config/test_envvars.py @@ -13,6 +13,7 @@ import os +import pandas import pytest import modin.config as cfg @@ -79,34 +80,47 @@ def test_custom_help(make_custom_envvar): assert "custom var" in make_custom_envvar.get_help() -def test_doc_module(): - import pandas - - import modin.pandas as pd - from modin.config import DocModule - - DocModule.put("modin.tests.config.docs_module") - - # Test for override - assert ( - pd.DataFrame.apply.__doc__ - == "This is a test of the documentation module for DataFrame." - ) - # Test for pandas doc when method is not defined on the plugin module - assert pandas.DataFrame.isna.__doc__ in pd.DataFrame.isna.__doc__ - assert pandas.DataFrame.isnull.__doc__ in pd.DataFrame.isnull.__doc__ - # Test for override - assert ( - pd.Series.isna.__doc__ - == "This is a test of the documentation module for Series." - ) - # Test for pandas doc when method is not defined on the plugin module - assert pandas.Series.isnull.__doc__ in pd.Series.isnull.__doc__ - assert pandas.Series.apply.__doc__ in pd.Series.apply.__doc__ - # Test for override - assert pd.read_csv.__doc__ == "Test override for functions on the module." - # Test for pandas doc when function is not defined on module. - assert pandas.read_table.__doc__ in pd.read_table.__doc__ +class TestDocModule: + """ + Test using a module to replace default docstrings. + """ + + def test_overrides(self): + cfg.DocModule.put("modin.tests.config.docs_module") + + # Test for override + assert ( + pd.DataFrame.apply.__doc__ + == "This is a test of the documentation module for DataFrame." + ) + # Test for pandas doc when method is not defined on the plugin module + assert pandas.DataFrame.isna.__doc__ in pd.DataFrame.isna.__doc__ + assert pandas.DataFrame.isnull.__doc__ in pd.DataFrame.isnull.__doc__ + # Test for override + assert ( + pd.Series.isna.__doc__ + == "This is a test of the documentation module for Series." + ) + # Test for pandas doc when method is not defined on the plugin module + assert pandas.Series.isnull.__doc__ in pd.Series.isnull.__doc__ + assert pandas.Series.apply.__doc__ in pd.Series.apply.__doc__ + # Test for override + assert pd.read_csv.__doc__ == "Test override for functions on the module." + # Test for pandas doc when function is not defined on module. + assert pandas.read_table.__doc__ in pd.read_table.__doc__ + + def test_not_redefining_classes_modin_issue_7138(self): + original_dataframe_class = pd.DataFrame + + cfg.DocModule.put("modin.tests.config.docs_module") + + # Test for override + assert ( + pd.DataFrame.apply.__doc__ + == "This is a test of the documentation module for DataFrame." + ) + + assert pd.DataFrame is original_dataframe_class @pytest.mark.skipif(cfg.Engine.get() != "Ray", reason="Ray specific test")
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 2 }
0.30
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore==2.21.1 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aioitertools==0.12.0 aiosignal==1.3.2 alabaster==0.7.16 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 asv==0.5.1 async-lru==2.0.5 async-timeout==5.0.1 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 black==25.1.0 bleach==6.2.0 blinker==1.9.0 blosc2==2.5.1 bokeh==3.4.3 boto3==1.37.1 botocore==1.37.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 click==8.1.8 cloudpickle==3.1.1 comm==0.2.2 connectorx==0.3.4a3 contourpy==1.3.0 coverage==7.8.0 cramjam==2.9.1 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 dask-expr==1.1.10 dataframe_api_compat==0.2.7 db-dtypes==1.4.2 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 Deprecated==1.2.18 distributed==2024.8.0 docutils==0.21.2 et_xmlfile==2.0.0 exceptiongroup==1.2.2 execnet==2.1.1 executing==2.2.0 Faker==37.1.0 fastjsonschema==2.21.1 fastparquet==2024.11.0 filelock==3.18.0 flake8==7.2.0 flake8-no-implicit-concat==0.3.7 flake8-print==5.0.0 Flask==3.1.0 flask-cors==5.0.1 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 fuzzydata==0.0.11 google-api-core==2.24.2 google-auth==2.38.0 google-auth-oauthlib==1.2.1 google-cloud-bigquery==3.31.0 google-cloud-core==2.4.3 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 greenlet==3.1.1 grpcio==1.71.0 grpcio-status==1.71.0 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 isoduration==20.11.0 isort==6.0.1 itsdangerous==2.2.0 jedi==0.19.2 Jinja2==3.1.6 jmespath==1.0.1 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 locket==1.0.0 lxml==5.3.1 lz4==4.4.3 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mccabe==0.7.0 mistune==3.1.3 -e git+https://github.com/modin-project/modin.git@af5ed0628a4a609f70becd29fd081a290ba981a0#egg=modin modin-spreadsheet @ git+https://github.com/modin-project/modin-spreadsheet.git@49ffd89f683f54c311867d602c55443fb11bf2a5 more-itertools==10.6.0 moto==5.1.2 msgpack==1.1.0 multidict==6.2.0 mypy==1.15.0 mypy-extensions==1.0.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 ndindex==1.9.2 nest-asyncio==1.6.0 networkx==3.2.1 notebook==7.3.3 notebook_shim==0.2.4 numexpr==2.10.2 numpy==2.0.2 numpydoc==1.1.0 oauthlib==3.2.2 openpyxl==3.1.5 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandas-gbq==0.28.0 pandas-stubs==2.2.2.240807 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pathspec==0.12.1 pexpect==4.9.0 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==5.29.4 psutil==7.0.0 psycopg2-binary==2.9.10 ptyprocess==0.7.0 pure_eval==0.2.3 py-cpuinfo==9.0.0 pyarrow==19.0.1 pyarrow-hotfix==0.6 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycodestyle==2.13.0 pycparser==2.22 pydata-google-auth==1.9.1 pyflakes==3.3.1 pygit2==1.15.1 PyGithub==2.6.1 Pygments==2.19.1 PyJWT==2.10.1 pymssql==2.3.2 PyNaCl==1.5.0 pyparsing==3.2.3 pytest==8.3.5 pytest-benchmark==5.1.0 pytest-cov==6.0.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 ray==2.44.1 referencing==0.36.2 requests==2.32.3 requests-oauthlib==2.0.0 responses==0.25.7 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 rsa==4.9 s3fs==2025.3.1 s3transfer==0.11.3 scipy==1.13.1 Send2Trash==1.8.3 six==1.17.0 sniffio==1.3.1 snowballstemmer==2.2.0 sortedcontainers==2.4.0 soupsieve==2.6 Sphinx==7.4.7 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 SQLAlchemy==2.0.40 stack-data==0.6.3 tables==3.9.2 tblib==3.0.0 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==1.26.20 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==3.1.3 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xlrd==2.0.1 xmltodict==0.14.2 xyzservices==2025.1.0 yarl==1.18.3 zict==3.0.0 zipp==3.21.0
name: modin channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aiobotocore==2.21.1 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aioitertools==0.12.0 - aiosignal==1.3.2 - alabaster==0.7.16 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - asv==0.5.1 - async-lru==2.0.5 - async-timeout==5.0.1 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - black==25.1.0 - bleach==6.2.0 - blinker==1.9.0 - blosc2==2.5.1 - bokeh==3.4.3 - boto3==1.37.1 - botocore==1.37.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - click==8.1.8 - cloudpickle==3.1.1 - comm==0.2.2 - connectorx==0.3.4a3 - contourpy==1.3.0 - coverage==7.8.0 - cramjam==2.9.1 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - dask-expr==1.1.10 - dataframe-api-compat==0.2.7 - db-dtypes==1.4.2 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - deprecated==1.2.18 - distributed==2024.8.0 - docutils==0.21.2 - et-xmlfile==2.0.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - executing==2.2.0 - faker==37.1.0 - fastjsonschema==2.21.1 - fastparquet==2024.11.0 - filelock==3.18.0 - flake8==7.2.0 - flake8-no-implicit-concat==0.3.7 - flake8-print==5.0.0 - flask==3.1.0 - flask-cors==5.0.1 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - fuzzydata==0.0.11 - google-api-core==2.24.2 - google-auth==2.38.0 - google-auth-oauthlib==1.2.1 - google-cloud-bigquery==3.31.0 - google-cloud-core==2.4.3 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - greenlet==3.1.1 - grpcio==1.71.0 - grpcio-status==1.71.0 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.28.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - isort==6.0.1 - itsdangerous==2.2.0 - jedi==0.19.2 - jinja2==3.1.6 - jmespath==1.0.1 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - locket==1.0.0 - lxml==5.3.1 - lz4==4.4.3 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mccabe==0.7.0 - mistune==3.1.3 - modin-spreadsheet==0.1.2+3.g49ffd89 - more-itertools==10.6.0 - moto==5.1.2 - msgpack==1.1.0 - multidict==6.2.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - ndindex==1.9.2 - nest-asyncio==1.6.0 - networkx==3.2.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numexpr==2.10.2 - numpy==2.0.2 - numpydoc==1.1.0 - oauthlib==3.2.2 - openpyxl==3.1.5 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandas-gbq==0.28.0 - pandas-stubs==2.2.2.240807 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pathspec==0.12.1 - pexpect==4.9.0 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==5.29.4 - psutil==7.0.0 - psycopg2-binary==2.9.10 - ptyprocess==0.7.0 - pure-eval==0.2.3 - py-cpuinfo==9.0.0 - pyarrow==19.0.1 - pyarrow-hotfix==0.6 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycodestyle==2.13.0 - pycparser==2.22 - pydata-google-auth==1.9.1 - pyflakes==3.3.1 - pygit2==1.15.1 - pygithub==2.6.1 - pygments==2.19.1 - pyjwt==2.10.1 - pymssql==2.3.2 - pynacl==1.5.0 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-benchmark==5.1.0 - pytest-cov==6.0.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - ray==2.44.1 - referencing==0.36.2 - requests==2.32.3 - requests-oauthlib==2.0.0 - responses==0.25.7 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - rsa==4.9 - s3fs==2025.3.1 - s3transfer==0.11.3 - scipy==1.13.1 - send2trash==1.8.3 - six==1.17.0 - sniffio==1.3.1 - snowballstemmer==2.2.0 - sortedcontainers==2.4.0 - soupsieve==2.6 - sphinx==7.4.7 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - sqlalchemy==2.0.40 - stack-data==0.6.3 - tables==3.9.2 - tblib==3.0.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==1.26.20 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==3.1.3 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xlrd==2.0.1 - xmltodict==0.14.2 - xyzservices==2025.1.0 - yarl==1.18.3 - zict==3.0.0 - zipp==3.21.0 prefix: /opt/conda/envs/modin
[ "modin/tests/config/test_envvars.py::TestDocModule::test_not_redefining_classes_modin_issue_7138" ]
[ "modin/tests/config/test_envvars.py::test_ray_cluster_resources" ]
[ "modin/tests/config/test_envvars.py::test_unknown", "modin/tests/config/test_envvars.py::test_custom_default[str]", "modin/tests/config/test_envvars.py::test_custom_default[ExactStr]", "modin/tests/config/test_envvars.py::test_custom_set[str]", "modin/tests/config/test_envvars.py::test_custom_set[ExactStr]", "modin/tests/config/test_envvars.py::test_custom_help[str]", "modin/tests/config/test_envvars.py::test_custom_help[ExactStr]", "modin/tests/config/test_envvars.py::TestDocModule::test_overrides", "modin/tests/config/test_envvars.py::test_context_manager_update_config[modify_config0]", "modin/tests/config/test_envvars.py::test_wrong_values[NPartitions]", "modin/tests/config/test_envvars.py::test_wrong_values[CpuCount]", "modin/tests/config/test_envvars.py::test_wrong_values[LogMemoryInterval]", "modin/tests/config/test_envvars.py::test_wrong_values[LogFileSize]", "modin/tests/config/test_envvars.py::test_wrong_values[MinPartitionSize]" ]
[]
Apache License 2.0
18,647
2,343
[ "modin/config/envvars.py", "modin/utils.py" ]
tobymao__sqlglot-3627
ee9b01d5631f8f0942b61dfaf0632ae0ac2543bb
2024-06-11 13:07:42
47472d9c0a27070fd5f4f9b8c12a8bd8c86b1de1
diff --git a/sqlglot/parser.py b/sqlglot/parser.py index b99d34c0..854f5e7d 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -4534,7 +4534,11 @@ class Parser(metaclass=_Parser): while self._match(TokenType.COLON): start_index = self._index - path = self._parse_column_ops(self._parse_field(any_token=True)) + + # Snowflake allows reserved keywords as json keys but advance_any() excludes TokenType.SELECT from any_tokens=True + path = self._parse_column_ops( + self._parse_field(any_token=True, tokens=(TokenType.SELECT,)) + ) # The cast :: operator has a lower precedence than the extraction operator :, so # we rearrange the AST appropriately to avoid casting the JSON path
Parsing fails when struct / json field is called `select` **Fully reproducible code snippet** ``` query = """ select invocations.invocation_args:select::varchar as invocation_select from table """ sqlglot.parse(query, sqlglot.Dialects.SNOWFLAKE) ``` This snippet raises an exception: `sqlglot.errors.ParseError: Invalid expression / Unexpected token. Line 3, Col: 19.`
tobymao/sqlglot
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py index e5bf4f27..12864369 100644 --- a/tests/dialects/test_snowflake.py +++ b/tests/dialects/test_snowflake.py @@ -125,6 +125,10 @@ WHERE "SELECT a:from::STRING, a:from || ' test' ", "SELECT CAST(GET_PATH(a, 'from') AS TEXT), GET_PATH(a, 'from') || ' test'", ) + self.validate_identity( + "SELECT a:select", + "SELECT GET_PATH(a, 'select')", + ) self.validate_identity("x:from", "GET_PATH(x, 'from')") self.validate_identity( "value:values::string::int",
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
25.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 Pygments==2.19.1 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@ee9b01d5631f8f0942b61dfaf0632ae0ac2543bb#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - pygments==2.19.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake" ]
[]
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_alter_set_unset", "tests/dialects/test_snowflake.py::TestSnowflake::test_copy", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_describe_table", "tests/dialects/test_snowflake.py::TestSnowflake::test_flatten", "tests/dialects/test_snowflake.py::TestSnowflake::test_historical_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_snowflake.py::TestSnowflake::test_minus", "tests/dialects/test_snowflake.py::TestSnowflake::test_null_treatment", "tests/dialects/test_snowflake.py::TestSnowflake::test_parse_like_any", "tests/dialects/test_snowflake.py::TestSnowflake::test_querying_semi_structured_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_replace", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_substr", "tests/dialects/test_snowflake.py::TestSnowflake::test_sample", "tests/dialects/test_snowflake.py::TestSnowflake::test_semi_structured_types", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_columns", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_imported_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_objects", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_primary_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_schemas", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_sequences", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_tables", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_unique_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_users", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_views", "tests/dialects/test_snowflake.py::TestSnowflake::test_staged_files", "tests/dialects/test_snowflake.py::TestSnowflake::test_storage_integration", "tests/dialects/test_snowflake.py::TestSnowflake::test_stored_procedures", "tests/dialects/test_snowflake.py::TestSnowflake::test_swap", "tests/dialects/test_snowflake.py::TestSnowflake::test_table_literal", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/dialects/test_snowflake.py::TestSnowflake::test_try_cast", "tests/dialects/test_snowflake.py::TestSnowflake::test_user_defined_functions", "tests/dialects/test_snowflake.py::TestSnowflake::test_values" ]
[]
MIT License
18,653
203
[ "sqlglot/parser.py" ]
casbin__pycasbin-346
846cf2490648f344817d53280cfb3c4f03a91f26
2024-06-11 15:21:53
b03e65a27ddd772f7f7e96bf641a7783a5087722
casbin-bot: @Nekotoxin please review CLAassistant: [![CLA assistant check](https://cla-assistant.io/pull/badge/not_signed)](https://cla-assistant.io/casbin/pycasbin?pullRequest=346) <br/>Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our [Contributor License Agreement](https://cla-assistant.io/casbin/pycasbin?pullRequest=346) before we can accept your contribution.<br/><sub>You have signed the CLA already but the status is still pending? Let us [recheck](https://cla-assistant.io/check/casbin/pycasbin?pullRequest=346) it.</sub> hsluoyz: @leeqvip plz review
diff --git a/casbin/constant/constants.py b/casbin/constant/constants.py index c5b89b3..428dc13 100644 --- a/casbin/constant/constants.py +++ b/casbin/constant/constants.py @@ -13,6 +13,7 @@ # limitations under the License. # Index constants +ACTION_INDEX = "act" DOMAIN_INDEX = "dom" SUBJECT_INDEX = "sub" OBJECT_INDEX = "obj" diff --git a/casbin/management_enforcer.py b/casbin/management_enforcer.py index b374ce1..b1897fa 100644 --- a/casbin/management_enforcer.py +++ b/casbin/management_enforcer.py @@ -14,6 +14,7 @@ from casbin.internal_enforcer import InternalEnforcer from casbin.model.policy_op import PolicyOp +from casbin.constant.constants import ACTION_INDEX, SUBJECT_INDEX, OBJECT_INDEX class ManagementEnforcer(InternalEnforcer): @@ -27,7 +28,8 @@ class ManagementEnforcer(InternalEnforcer): def get_all_named_subjects(self, ptype): """gets the list of subjects that show up in the current named policy.""" - return self.model.get_values_for_field_in_policy("p", ptype, 0) + field_index = self.model.get_field_index(ptype, SUBJECT_INDEX) + return self.model.get_values_for_field_in_policy("p", ptype, field_index) def get_all_objects(self): """gets the list of objects that show up in the current policy.""" @@ -35,7 +37,8 @@ class ManagementEnforcer(InternalEnforcer): def get_all_named_objects(self, ptype): """gets the list of objects that show up in the current named policy.""" - return self.model.get_values_for_field_in_policy("p", ptype, 1) + field_index = self.model.get_field_index(ptype, OBJECT_INDEX) + return self.model.get_values_for_field_in_policy("p", ptype, field_index) def get_all_actions(self): """gets the list of actions that show up in the current policy.""" @@ -43,7 +46,8 @@ class ManagementEnforcer(InternalEnforcer): def get_all_named_actions(self, ptype): """gets the list of actions that show up in the current named policy.""" - return self.model.get_values_for_field_in_policy("p", ptype, 2) + field_index = self.model.get_field_index(ptype, ACTION_INDEX) + return self.model.get_values_for_field_in_policy("p", ptype, field_index) def get_all_roles(self): """gets the list of roles that show up in the current named policy."""
RBAC with Domain model ,get_all_subjects error 1、model.conf ![image](https://github.com/casbin/pycasbin/assets/32121721/9cd37638-a702-4138-8544-50fbdaa0e55f) 2、code: ![image](https://github.com/casbin/pycasbin/assets/32121721/5041e3a1-af32-41a5-8895-227289c759b2) 3、sqlite info ![image](https://github.com/casbin/pycasbin/assets/32121721/f66c78a6-a64c-43fe-9985-e18edde72b65) question: e.get_all_objects() --> ['test.xxx.com'] it should be ['system:get','system:put','system:post']
casbin/pycasbin
diff --git a/tests/test_management_api.py b/tests/test_management_api.py index 84f5522..e924daa 100644 --- a/tests/test_management_api.py +++ b/tests/test_management_api.py @@ -38,6 +38,18 @@ class TestManagementApi(TestCaseBase): self.assertEqual(e.get_all_actions(), ["read", "write"]) self.assertEqual(e.get_all_roles(), ["data2_admin"]) + def test_get_list_with_domains(self): + e = self.get_enforcer( + get_examples("rbac_with_domains_model.conf"), + get_examples("rbac_with_domains_policy.csv"), + # True, + ) + + self.assertEqual(e.get_all_subjects(), ["admin"]) + self.assertEqual(e.get_all_objects(), ["data1", "data2"]) + self.assertEqual(e.get_all_actions(), ["read", "write"]) + self.assertEqual(e.get_all_roles(), ["admin"]) + def test_get_policy_api(self): e = self.get_enforcer( get_examples("rbac_model.conf"),
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 2 }
1.36
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.12", "reqs_path": [ "requirements.txt", "requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 black==23.11.0 -e git+https://github.com/casbin/pycasbin.git@846cf2490648f344817d53280cfb3c4f03a91f26#egg=casbin click==8.1.8 iniconfig==2.1.0 mypy-extensions==1.0.0 packaging==24.2 pathspec==0.12.1 platformdirs==4.3.7 pluggy==1.5.0 py==1.11.0 py-cpuinfo==9.0.0 pytest==7.0.1 pytest-benchmark==3.4.1 setuptools==75.8.0 simpleeval==1.0.3 tomli==2.2.1 wheel==0.45.1
name: pycasbin channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - expat=2.6.4=h6a678d5_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py312h06a4308_0 - python=3.12.9=h5148396_0 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py312h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py312h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - black==23.11.0 - casbin==1.36.1 - click==8.1.8 - iniconfig==2.1.0 - mypy-extensions==1.0.0 - packaging==24.2 - pathspec==0.12.1 - platformdirs==4.3.7 - pluggy==1.5.0 - py==1.11.0 - py-cpuinfo==9.0.0 - pytest==7.0.1 - pytest-benchmark==3.4.1 - simpleeval==1.0.3 - tomli==2.2.1 prefix: /opt/conda/envs/pycasbin
[ "tests/test_management_api.py::TestManagementApi::test_get_list_with_domains", "tests/test_management_api.py::TestManagementApiSynced::test_get_list_with_domains" ]
[]
[ "tests/test_management_api.py::TestManagementApi::test_get_list", "tests/test_management_api.py::TestManagementApi::test_get_policy_api", "tests/test_management_api.py::TestManagementApi::test_get_policy_matching_function", "tests/test_management_api.py::TestManagementApi::test_get_policy_multiple_matching_functions", "tests/test_management_api.py::TestManagementApi::test_modify_policy_api", "tests/test_management_api.py::TestManagementApi::test_update_filtered_policies", "tests/test_management_api.py::TestManagementApiSynced::test_get_list", "tests/test_management_api.py::TestManagementApiSynced::test_get_policy_api", "tests/test_management_api.py::TestManagementApiSynced::test_get_policy_matching_function", "tests/test_management_api.py::TestManagementApiSynced::test_get_policy_multiple_matching_functions", "tests/test_management_api.py::TestManagementApiSynced::test_modify_policy_api", "tests/test_management_api.py::TestManagementApiSynced::test_update_filtered_policies", "tests/test_management_api.py::TestManagementApiAsync::test_get_list", "tests/test_management_api.py::TestManagementApiAsync::test_get_policy_api", "tests/test_management_api.py::TestManagementApiAsync::test_get_policy_matching_function", "tests/test_management_api.py::TestManagementApiAsync::test_get_policy_multiple_matching_functions", "tests/test_management_api.py::TestManagementApiAsync::test_modify_policy_api", "tests/test_management_api.py::TestManagementApiAsync::test_update_filtered_policies" ]
[]
Apache License 2.0
18,655
623
[ "casbin/constant/constants.py", "casbin/management_enforcer.py" ]
scrapy__w3lib-230
d7c3307f8f7e30cdc91d48987e57c42ca04a5df3
2024-06-12 05:50:44
d7c3307f8f7e30cdc91d48987e57c42ca04a5df3
diff --git a/w3lib/url.py b/w3lib/url.py index 28e70cb..c142048 100644 --- a/w3lib/url.py +++ b/w3lib/url.py @@ -654,10 +654,13 @@ def canonicalize_url( fragment = "" if not keep_fragments else fragment + # Apply lowercase to the domain, but not to the userinfo. + netloc_parts = netloc.split("@") + netloc_parts[-1] = netloc_parts[-1].lower().rstrip(":") + netloc = "@".join(netloc_parts) + # every part should be safe already - return urlunparse( - (scheme, netloc.lower().rstrip(":"), path, params, query, fragment) - ) + return urlunparse((scheme, netloc, path, params, query, fragment)) def _unquotepath(path: str) -> bytes:
canonicalize_url inappropriately "lowercases" credentials (username/password) in url ```python from w3lib.url import canonicalize_url def main(): url = "sftp://USERNAME:[email protected]" print(canonicalize_url(url)) print(canonicalize_url(url) == url) ``` ``` sftp://username:[email protected]/ False ```
scrapy/w3lib
diff --git a/tests/test_url.py b/tests/test_url.py index ca84745..319d76c 100644 --- a/tests/test_url.py +++ b/tests/test_url.py @@ -1384,6 +1384,12 @@ class CanonicalizeUrlTest(unittest.TestCase): canonicalize_url("http://www.EXAMPLE.com/"), "http://www.example.com/" ) + def test_userinfo_is_case_sensitive(self): + self.assertEqual( + canonicalize_url("sftp://UsEr:[email protected]/"), + "sftp://UsEr:[email protected]/", + ) + def test_canonicalize_idns(self): self.assertEqual( canonicalize_url("http://www.bücher.de?q=bücher"),
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
2.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/scrapy/w3lib.git@d7c3307f8f7e30cdc91d48987e57c42ca04a5df3#egg=w3lib
name: w3lib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/w3lib
[ "tests/test_url.py::CanonicalizeUrlTest::test_userinfo_is_case_sensitive" ]
[ "tests/test_url.py::test_safe_url_string_url[http://[2a01:5cc0:1:2:3:4]-ValueError]" ]
[ "tests/test_url.py::test_safe_url_string_encoding[None-https://example.com-https://example.com]", "tests/test_url.py::test_safe_url_string_encoding[None-https://example.com/\\xa9-https://example.com/%C2%A9]", "tests/test_url.py::test_safe_url_string_encoding[iso-8859-1-https://example.com/\\xa9-https://example.com/%C2%A9]", "tests/test_url.py::test_safe_url_string_encoding[iso-8859-1-file://example.com?\\xa9-file://example.com?%A9]", "tests/test_url.py::test_safe_url_string_encoding[iso-8859-1-https://example.com?\\xa9-https://example.com?%A9]", "tests/test_url.py::test_safe_url_string_encoding[iso-8859-1-http://example.com?\\xa9-http://example.com?%A9]", "tests/test_url.py::test_safe_url_string_encoding[iso-8859-1-ftp://example.com?\\xa9-ftp://example.com?%A9]", "tests/test_url.py::test_safe_url_string_url[1-Exception]", "tests/test_url.py::test_safe_url_string_url[url1-Exception]", "tests/test_url.py::test_safe_url_string_url[\\x00https://example.com\\x00-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x01https://example.com\\x01-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x02https://example.com\\x02-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x03https://example.com\\x03-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x04https://example.com\\x04-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x05https://example.com\\x05-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x06https://example.com\\x06-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x07https://example.com\\x07-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x08https://example.com\\x08-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x0bhttps://example.com\\x0b-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x0chttps://example.com\\x0c-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x0ehttps://example.com\\x0e-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x0fhttps://example.com\\x0f-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x10https://example.com\\x10-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x11https://example.com\\x11-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x12https://example.com\\x12-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x13https://example.com\\x13-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x14https://example.com\\x14-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x15https://example.com\\x15-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x16https://example.com\\x16-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x17https://example.com\\x17-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x18https://example.com\\x18-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x19https://example.com\\x19-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x1ahttps://example.com\\x1a-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x1bhttps://example.com\\x1b-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x1chttps://example.com\\x1c-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x1dhttps://example.com\\x1d-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x1ehttps://example.com\\x1e-https://example.com]", "tests/test_url.py::test_safe_url_string_url[\\x1fhttps://example.com\\x1f-https://example.com]", "tests/test_url.py::test_safe_url_string_url[", "tests/test_url.py::test_safe_url_string_url[\\t\\n\\rh\\t\\n\\rttps\\t\\n\\r:\\t\\n\\r/\\t\\n\\r/\\t\\n\\ra\\t\\n\\rb\\t\\n\\r:\\t\\n\\ra\\t\\n\\rb\\t\\n\\r@\\t\\n\\rexam\\t\\n\\rple.com\\t\\n\\r:\\t\\n\\r1\\t\\n\\r2\\t\\n\\r/\\t\\n\\ra\\t\\n\\rb\\t\\n\\r?\\t\\n\\ra\\t\\n\\rb\\t\\n\\r#\\t\\n\\ra\\t\\n\\rb\\t\\n\\r-https://ab:[email protected]:12/ab?ab#ab]", "tests/test_url.py::test_safe_url_string_url[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ://example.com-abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz://example.com]", "tests/test_url.py::test_safe_url_string_url[aabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.://example.com-aabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+-.://example.com]", "tests/test_url.py::test_safe_url_string_url[https://[email protected]://[email protected]]", "tests/test_url.py::test_safe_url_string_url[https://a:@example.com-https://a:@example.com]", "tests/test_url.py::test_safe_url_string_url[https://a:[email protected]://a:[email protected]]", "tests/test_url.py::test_safe_url_string_url[https://a%[email protected]://a%[email protected]]", "tests/test_url.py::test_safe_url_string_url[https://abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()&+$,:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()&+$,@example.com-https://abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()&+$,:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()&+$,@example.com]", "tests/test_url.py::test_safe_url_string_url[https://\"%;<=>@^`{|}\\x7f:\"%;<=>@^`{|}\\x7f:@example.com-https://%22%25%3B%3C%3D%3E%40%5E%60%7B%7C%7D%7F:%22%25%3B%3C%3D%3E%40%5E%60%7B%7C%7D%7F%[email protected]]", "tests/test_url.py::test_safe_url_string_url[https://\\x80:\\[email protected]://%C2%80:%C2%[email protected]]", "tests/test_url.py::test_safe_url_string_url[https://example.com-https://example.com]", "tests/test_url.py::test_safe_url_string_url[https://.example-https://.example]", "tests/test_url.py::test_safe_url_string_url[https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example-https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example]", "tests/test_url.py::test_safe_url_string_url[https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example-https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example]", "tests/test_url.py::test_safe_url_string_url[https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example-https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example]", "tests/test_url.py::test_safe_url_string_url[https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example-https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example]", "tests/test_url.py::test_safe_url_string_url[https://\\xf1.example-https://xn--ida.example]", "tests/test_url.py::test_safe_url_string_url[http://192.168.0.0-http://192.168.0.0]", "tests/test_url.py::test_safe_url_string_url[https://example.com:1-https://example.com:1]", "tests/test_url.py::test_safe_url_string_url[https://example.com:443-https://example.com:443]", "tests/test_url.py::test_safe_url_string_url[https://example.com/-https://example.com/]", "tests/test_url.py::test_safe_url_string_url[https://example.com/a-https://example.com/a]", "tests/test_url.py::test_safe_url_string_url[https://example.com/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():@&=+$,/;-https://example.com/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():@&=+$,/;]", "tests/test_url.py::test_safe_url_string_url[https://example.com/\\xf1-https://example.com/%C3%B1]", "tests/test_url.py::test_safe_url_string_url[https://example.com/\\xf1%C3%B1-https://example.com/%C3%B1%C3%B1]", "tests/test_url.py::test_safe_url_string_url[https://example.com?a-https://example.com?a]", "tests/test_url.py::test_safe_url_string_url[https://example.com?a=-https://example.com?a=]", "tests/test_url.py::test_safe_url_string_url[https://example.com?a=b-https://example.com?a=b]", "tests/test_url.py::test_safe_url_string_url[a://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():@&=+$,/;?-a://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():@&=+$,/;?]", "tests/test_url.py::test_safe_url_string_url[file://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?-file://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?]", "tests/test_url.py::test_safe_url_string_url[https://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?-https://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?]", "tests/test_url.py::test_safe_url_string_url[http://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?-http://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?]", "tests/test_url.py::test_safe_url_string_url[ws://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?-ws://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?]", "tests/test_url.py::test_safe_url_string_url[ftp://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?-ftp://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?]", "tests/test_url.py::test_safe_url_string_url[wss://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?-wss://example.com?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*():@&=+$,/;?]", "tests/test_url.py::test_safe_url_string_url[https://example.com?\\xf1-https://example.com?%C3%B1]", "tests/test_url.py::test_safe_url_string_url[https://example.com?\\xf1%C3%B1-https://example.com?%C3%B1%C3%B1]", "tests/test_url.py::test_safe_url_string_url[https://example.com#a-https://example.com#a]", "tests/test_url.py::test_safe_url_string_url[a://example.com#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():@&=+$,/;?-a://example.com#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():@&=+$,/;?]", "tests/test_url.py::test_safe_url_string_url[https://example.com#\\xf1-https://example.com#%C3%B1]", "tests/test_url.py::test_safe_url_string_url[https://example.com#\\xf1%C3%B1-https://example.com#%C3%B1%C3%B1]", "tests/test_url.py::test_safe_url_string_url[https://\\xf1:\\xf1@\\xf1.example:1/\\xf1?\\xf1#\\xf1-https://%C3%B1:%C3%[email protected]:1/%C3%B1?%C3%B1#%C3%B1]", "tests/test_url.py::UrlTests::test_add_or_replace_parameter", "tests/test_url.py::UrlTests::test_add_or_replace_parameters", "tests/test_url.py::UrlTests::test_add_or_replace_parameters_does_not_change_input_param", "tests/test_url.py::UrlTests::test_any_to_uri", "tests/test_url.py::UrlTests::test_file_uri_to_path", "tests/test_url.py::UrlTests::test_is_url", "tests/test_url.py::UrlTests::test_path_to_file_uri", "tests/test_url.py::UrlTests::test_safe_download_url", "tests/test_url.py::UrlTests::test_safe_url_idna", "tests/test_url.py::UrlTests::test_safe_url_idna_encoding_failure", "tests/test_url.py::UrlTests::test_safe_url_port_number", "tests/test_url.py::UrlTests::test_safe_url_string", "tests/test_url.py::UrlTests::test_safe_url_string_bytes_input", "tests/test_url.py::UrlTests::test_safe_url_string_bytes_input_nonutf8", "tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_port", "tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_username_and_empty_password_and_port_number", "tests/test_url.py::UrlTests::test_safe_url_string_encode_idna_domain_with_username_password_and_port_number", "tests/test_url.py::UrlTests::test_safe_url_string_misc", "tests/test_url.py::UrlTests::test_safe_url_string_preserve_nonfragment_hash", "tests/test_url.py::UrlTests::test_safe_url_string_quote_path", "tests/test_url.py::UrlTests::test_safe_url_string_remove_ascii_tab_and_newlines", "tests/test_url.py::UrlTests::test_safe_url_string_user_and_pass_percentage_encoded", "tests/test_url.py::UrlTests::test_safe_url_string_userinfo_unsafe_chars", "tests/test_url.py::UrlTests::test_safe_url_string_with_query", "tests/test_url.py::UrlTests::test_url_query_cleaner", "tests/test_url.py::UrlTests::test_url_query_cleaner_keep_fragments", "tests/test_url.py::UrlTests::test_url_query_parameter", "tests/test_url.py::UrlTests::test_url_query_parameter_2", "tests/test_url.py::CanonicalizeUrlTest::test_append_missing_path", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_idns", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding", "tests/test_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed", "tests/test_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive", "tests/test_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters", "tests/test_url.py::CanonicalizeUrlTest::test_keep_blank_values", "tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths", "tests/test_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments", "tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths", "tests/test_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments", "tests/test_url.py::CanonicalizeUrlTest::test_port_number", "tests/test_url.py::CanonicalizeUrlTest::test_preserve_nonfragment_hash", "tests/test_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign", "tests/test_url.py::CanonicalizeUrlTest::test_remove_fragments", "tests/test_url.py::CanonicalizeUrlTest::test_return_str", "tests/test_url.py::CanonicalizeUrlTest::test_safe_characters_unicode", "tests/test_url.py::CanonicalizeUrlTest::test_sorting", "tests/test_url.py::CanonicalizeUrlTest::test_spaces", "tests/test_url.py::CanonicalizeUrlTest::test_strip_spaces", "tests/test_url.py::CanonicalizeUrlTest::test_typical_usage", "tests/test_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports", "tests/test_url.py::DataURITests::test_base64", "tests/test_url.py::DataURITests::test_base64_spaces", "tests/test_url.py::DataURITests::test_bytes_uri", "tests/test_url.py::DataURITests::test_default_mediatype", "tests/test_url.py::DataURITests::test_default_mediatype_charset", "tests/test_url.py::DataURITests::test_mediatype_parameters", "tests/test_url.py::DataURITests::test_missing_comma", "tests/test_url.py::DataURITests::test_missing_scheme", "tests/test_url.py::DataURITests::test_scheme_case_insensitive", "tests/test_url.py::DataURITests::test_text_charset", "tests/test_url.py::DataURITests::test_text_uri", "tests/test_url.py::DataURITests::test_unicode_uri", "tests/test_url.py::DataURITests::test_wrong_base64_param", "tests/test_url.py::DataURITests::test_wrong_scheme" ]
[]
BSD 3-Clause "New" or "Revised" License
18,664
223
[ "w3lib/url.py" ]
tobymao__sqlglot-3641
47472d9c0a27070fd5f4f9b8c12a8bd8c86b1de1
2024-06-12 15:29:43
47472d9c0a27070fd5f4f9b8c12a8bd8c86b1de1
diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py index 0ddcf4e9..74066765 100644 --- a/sqlglot/dialects/dialect.py +++ b/sqlglot/dialects/dialect.py @@ -169,6 +169,7 @@ class _Dialect(type): if enum not in ("", "athena", "presto", "trino"): klass.generator_class.TRY_SUPPORTED = False + klass.generator_class.SUPPORTS_UESCAPE = False if enum not in ("", "databricks", "hive", "spark", "spark2"): modifier_transforms = klass.generator_class.AFTER_HAVING_MODIFIER_TRANSFORMS.copy() diff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py index b2db7fb7..0791141f 100644 --- a/sqlglot/dialects/oracle.py +++ b/sqlglot/dialects/oracle.py @@ -231,6 +231,12 @@ class Oracle(Dialect): class Tokenizer(tokens.Tokenizer): VAR_SINGLE_TOKENS = {"@", "$", "#"} + UNICODE_STRINGS = [ + (prefix + q, q) + for q in t.cast(t.List[str], tokens.Tokenizer.QUOTES) + for prefix in ("U", "u") + ] + KEYWORDS = { **tokens.Tokenizer.KEYWORDS, "(+)": TokenType.JOIN_MARKER, diff --git a/sqlglot/generator.py b/sqlglot/generator.py index b5624fab..b0de4437 100644 --- a/sqlglot/generator.py +++ b/sqlglot/generator.py @@ -356,6 +356,9 @@ class Generator(metaclass=_Generator): # Whether the conditional TRY(expression) function is supported TRY_SUPPORTED = True + # Whether the UESCAPE syntax in unicode strings is supported + SUPPORTS_UESCAPE = True + # The keyword to use when generating a star projection with excluded columns STAR_EXCEPT = "EXCEPT" @@ -1143,16 +1146,23 @@ class Generator(metaclass=_Generator): escape = expression.args.get("escape") if self.dialect.UNICODE_START: - escape = f" UESCAPE {self.sql(escape)}" if escape else "" - return f"{self.dialect.UNICODE_START}{this}{self.dialect.UNICODE_END}{escape}" + escape_substitute = r"\\\1" + left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END + else: + escape_substitute = r"\\u\1" + left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END if escape: - pattern = re.compile(rf"{escape.name}(\d+)") + escape_pattern = re.compile(rf"{escape.name}(\d+)") + escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" else: - pattern = ESCAPED_UNICODE_RE + escape_pattern = ESCAPED_UNICODE_RE + escape_sql = "" + + if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): + this = escape_pattern.sub(escape_substitute, this) - this = pattern.sub(r"\\u\1", this) - return f"{self.dialect.QUOTE_START}{this}{self.dialect.QUOTE_END}" + return f"{left_quote}{this}{right_quote}{escape_sql}" def rawstring_sql(self, expression: exp.RawString) -> str: string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
oracle unicode literals parse error Parsing some oracle string literal in sqlglot is not working, and returns `sqlglot.errors.ParseError: Invalid expression / Unexpected token.` A simple example using U"str", or N"str": ``` import sqlglot res = sqlglot.transpile(''' SELECT u'\\\20ac' FROM dual; ''', read="oracle", write="oracle")[0] print(res) ``` The following is valid oracle query: ``` select n'\€', u'\\\20ac', n'\\\20ac' from dual; N'\€' U'\\\20AC' N'\\\20AC' ----- ---------- ---------- \€ \€ \\\20ac ``` in sqlglot returns error in parsing: ``` Traceback (most recent call last): File "/Users/deeb/PycharmProjects/datahub_app/parse.py", line 3, in <module> res = sqlglot.transpile(''' ^^^^^^^^^^^^^^^^^^^^^ File "/Users/deeb/anaconda3/lib/python3.11/site-packages/sqlglot/__init__.py", line 177, in transpile for expression in parse(sql, read, error_level=error_level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/deeb/anaconda3/lib/python3.11/site-packages/sqlglot/__init__.py", line 102, in parse return Dialect.get_or_raise(read or dialect).parse(sql, **opts) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/deeb/anaconda3/lib/python3.11/site-packages/sqlglot/dialects/dialect.py", line 512, in parse return self.parser(**opts).parse(self.tokenize(sql), sql) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/deeb/anaconda3/lib/python3.11/site-packages/sqlglot/parser.py", line 1246, in parse return self._parse( ^^^^^^^^^^^^ File "/Users/deeb/anaconda3/lib/python3.11/site-packages/sqlglot/parser.py", line 1318, in _parse self.raise_error("Invalid expression / Unexpected token") File "/Users/deeb/anaconda3/lib/python3.11/site-packages/sqlglot/parser.py", line 1359, in raise_error raise error sqlglot.errors.ParseError: Invalid expression / Unexpected token. Line 2, Col: 14. SELECT u'\ac' FROM dual; ```
tobymao/sqlglot
diff --git a/tests/dialects/test_presto.py b/tests/dialects/test_presto.py index f1bbcc13..ebb270ab 100644 --- a/tests/dialects/test_presto.py +++ b/tests/dialects/test_presto.py @@ -564,6 +564,7 @@ class TestPresto(Validator): self.validate_all( f"{prefix}'Hello winter \\2603 !'", write={ + "oracle": "U'Hello winter \\2603 !'", "presto": "U&'Hello winter \\2603 !'", "snowflake": "'Hello winter \\u2603 !'", "spark": "'Hello winter \\u2603 !'", @@ -572,6 +573,7 @@ class TestPresto(Validator): self.validate_all( f"{prefix}'Hello winter #2603 !' UESCAPE '#'", write={ + "oracle": "U'Hello winter \\2603 !'", "presto": "U&'Hello winter #2603 !' UESCAPE '#'", "snowflake": "'Hello winter \\u2603 !'", "spark": "'Hello winter \\u2603 !'",
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 3 }
25.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 Pygments==2.19.1 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@47472d9c0a27070fd5f4f9b8c12a8bd8c86b1de1#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pygments==2.19.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_presto.py::TestPresto::test_unicode_string" ]
[]
[ "tests/dialects/test_presto.py::TestPresto::test_cast", "tests/dialects/test_presto.py::TestPresto::test_ddl", "tests/dialects/test_presto.py::TestPresto::test_encode_decode", "tests/dialects/test_presto.py::TestPresto::test_hex_unhex", "tests/dialects/test_presto.py::TestPresto::test_interval_plural_to_singular", "tests/dialects/test_presto.py::TestPresto::test_json", "tests/dialects/test_presto.py::TestPresto::test_match_recognize", "tests/dialects/test_presto.py::TestPresto::test_presto", "tests/dialects/test_presto.py::TestPresto::test_quotes", "tests/dialects/test_presto.py::TestPresto::test_regex", "tests/dialects/test_presto.py::TestPresto::test_signum", "tests/dialects/test_presto.py::TestPresto::test_time", "tests/dialects/test_presto.py::TestPresto::test_to_char", "tests/dialects/test_presto.py::TestPresto::test_unnest" ]
[]
MIT License
18,671
894
[ "sqlglot/dialects/dialect.py", "sqlglot/dialects/oracle.py", "sqlglot/generator.py" ]
dag-hammarskjold-library__dlx-318
8936709e06ece6066be8e6f801bd2f4c7098b6d6
2024-06-12 21:42:07
7bc9c436adc657b48945eafa70a190381864e26c
diff --git a/dlx/marc/__init__.py b/dlx/marc/__init__.py index be5cb4b..e20e174 100644 --- a/dlx/marc/__init__.py +++ b/dlx/marc/__init__.py @@ -303,6 +303,27 @@ class MarcSet(): def to_excel(self, path): pass + def to_table(self) -> Table: + table = Table() + + for i, record in enumerate(self.records): + i += 1 + + for tag in [x for x in record.get_tags() if not re.match('00', x)]: + for place, field in enumerate(record.get_fields(tag)): + place += 1 + + for subfield in field.subfields: + table.set(i, f'{place}.{field.tag}${subfield.code}', subfield.value) + + return table + + def to_csv(self) -> str: + return self.to_table().to_csv() + + def to_tsv(self) -> str: + return self.to_table().to_tsv() + class BibSet(MarcSet): def __init__(self, *args, **kwargs): self.handle = DB.bibs diff --git a/dlx/util.py b/dlx/util.py index 1223b24..c86aa28 100644 --- a/dlx/util.py +++ b/dlx/util.py @@ -38,18 +38,19 @@ class Table(): return cls(lol) - def __init__(self,list_of_lists=None,**kwargs): - self.index = {} - self.header = [] + def __init__(self, list_of_lists=None, **kwargs): + self.index = {} # data structure that stores the table + self.header = [] # list of field names for the header + # todo: put this in a class method that instantiates the object if list_of_lists: self.header = list_of_lists[0] - rowx = 0 + for row in list_of_lists[1:len(list_of_lists)]: self.index[rowx] = {} - cellx = 0 + for cell in row: field_name = self.header[cellx] self.index[rowx][field_name] = cell @@ -57,9 +58,14 @@ class Table(): rowx += 1 - def set(self,rowx,field_name,value): + def set(self, rowx, field_name, value): + self.index.setdefault(rowx, {}) + self.index[rowx].setdefault(field_name, {}) self.index[rowx][field_name] = value - + + if field_name not in self.header: + self.header.append(field_name) + return self def get(self,rowx,field_name): @@ -80,6 +86,7 @@ class Table(): return output def to_html(self,**kwargs): + # todo: refactor rows = [] for row in self.to_list(): @@ -93,7 +100,39 @@ class Table(): table = f'<table>{to_str}</table>' return table + + def serialize(self, *, separator): + valid = (',', '\t') + + if separator not in valid: + raise Exception(f'Separator must be in {valid}') + rows = [self.header] + + for i, record in self.index.items(): + row = [] + + for field in self.header: + if value := record.get(field): + if separator in value: + # handle the separator + value.replace('"', '""') + value = f'"{value}"' + + row.append(value) + else: + row.append('') + + rows.append(row) + + return '\n'.join([separator.join(row) for row in rows]) + + def to_csv(self): + return self.serialize(separator=',') + + def to_tsv(self): + return self.serialize(separator='\t') + class ISO6391(): codes = { "aa": "Afar",
Implement CSV serialization Add CSV to the available record and batch serializations
dag-hammarskjold-library/dlx
diff --git a/tests/test_marcset.py b/tests/test_marcset.py index f948b49..3150afa 100644 --- a/tests/test_marcset.py +++ b/tests/test_marcset.py @@ -162,6 +162,12 @@ def test_to_str(db): control = '000\n leader\n008\n controlfield\n245\n a: This\n b: is the\n c: title\n520\n a: Description\n520\n a: Another description\n a: Repeated subfield\n650\n a: Header\n710\n a: Another header\n\n000\n leader\n245\n a: Another\n b: is the\n c: title\n650\n a: Header\n' assert BibSet.from_query({}).to_str() == control +def test_to_csv(db): + from dlx.marc import BibSet + + bibset = BibSet.from_query({}) + assert bibset.to_csv() == '1.245$a,1.245$b,1.245$c,1.520$a,2.520$a,1.650$a,1.710$a\nThis,is the,title,Description,Repeated subfield,Header,Another header\nAnother,is the,title,,,Header,' + def test_from_aggregation(db, bibs): from dlx.marc import BibSet, Query
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==23.2.0 boto3==1.34.100 botocore==1.34.100 certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 click==8.1.7 cryptography==42.0.7 -e git+https://github.com/dag-hammarskjold-library/dlx.git@8936709e06ece6066be8e6f801bd2f4c7098b6d6#egg=dlx dnspython==2.6.1 exceptiongroup==1.2.1 idna==3.7 iniconfig==2.0.0 Jinja2==3.1.4 jmespath==1.0.1 joblib==1.4.2 jsonschema==4.0.0 lxml==5.2.1 MarkupSafe==2.1.5 mongomock==4.1.2 moto==5.0.8 nltk==3.8.1 packaging==24.0 pluggy==1.5.0 pycparser==2.22 pymongo==4.6.3 pyrsistent==0.20.0 pytest==8.2.0 python-dateutil==2.9.0.post0 pytz==2024.1 PyYAML==6.0.1 regex==2024.4.28 requests==2.32.3 responses==0.25.0 s3transfer==0.10.1 sentinels==1.0.0 six==1.16.0 tomli==2.0.1 tqdm==4.66.4 urllib3==1.26.18 Werkzeug==3.0.3 xlrd==1.2.0 xmldiff==2.4 xmltodict==0.13.0
name: dlx channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==23.2.0 - boto3==1.34.100 - botocore==1.34.100 - certifi==2024.2.2 - cffi==1.16.0 - charset-normalizer==3.3.2 - click==8.1.7 - cryptography==42.0.7 - dnspython==2.6.1 - exceptiongroup==1.2.1 - idna==3.7 - iniconfig==2.0.0 - jinja2==3.1.4 - jmespath==1.0.1 - joblib==1.4.2 - jsonschema==4.0.0 - lxml==5.2.1 - markupsafe==2.1.5 - mongomock==4.1.2 - moto==5.0.8 - nltk==3.8.1 - packaging==24.0 - pluggy==1.5.0 - pycparser==2.22 - pymongo==4.6.3 - pyrsistent==0.20.0 - pytest==8.2.0 - python-dateutil==2.9.0.post0 - pytz==2024.1 - pyyaml==6.0.1 - regex==2024.4.28 - requests==2.32.3 - responses==0.25.0 - s3transfer==0.10.1 - sentinels==1.0.0 - six==1.16.0 - tomli==2.0.1 - tqdm==4.66.4 - urllib3==1.26.18 - werkzeug==3.0.3 - xlrd==1.2.0 - xmldiff==2.4 - xmltodict==0.13.0 prefix: /opt/conda/envs/dlx
[ "tests/test_marcset.py::test_to_csv" ]
[]
[ "tests/test_marcset.py::test_mocked", "tests/test_marcset.py::test_init", "tests/test_marcset.py::test_iterate", "tests/test_marcset.py::test_from_query", "tests/test_marcset.py::test_from_ids", "tests/test_marcset.py::test_from_table", "tests/test_marcset.py::test_from_mrk", "tests/test_marcset.py::test_from_xml", "tests/test_marcset.py::test_to_mrc", "tests/test_marcset.py::test_to_mrk", "tests/test_marcset.py::test_to_xml", "tests/test_marcset.py::test_xml_encoding", "tests/test_marcset.py::test_to_str", "tests/test_marcset.py::test_from_aggregation" ]
[]
null
18,679
966
[ "dlx/marc/__init__.py", "dlx/util.py" ]
googleapis__python-bigquery-1952
5d10f1e94222e635cf008d83928555a628cdbb3f
2024-06-12 22:34:24
7e522eea776cd9a74f8078c4236f63d5ff11f20e
diff --git a/google/cloud/bigquery/job/load.py b/google/cloud/bigquery/job/load.py index 17643545..e56ce16f 100644 --- a/google/cloud/bigquery/job/load.py +++ b/google/cloud/bigquery/job/load.py @@ -32,6 +32,26 @@ from google.cloud.bigquery.job.base import _JobReference from google.cloud.bigquery.query import ConnectionProperty +class ColumnNameCharacterMap: + """Indicates the character map used for column names. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#columnnamecharactermap + """ + + COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED = "COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED" + """Unspecified column name character map.""" + + STRICT = "STRICT" + """Support flexible column name and reject invalid column names.""" + + V1 = "V1" + """ Support alphanumeric + underscore characters and names must start with + a letter or underscore. Invalid column names will be normalized.""" + + V2 = "V2" + """Support flexible column name. Invalid column names will be normalized.""" + + class LoadJobConfig(_JobConfig): """Configuration options for load jobs. @@ -597,6 +617,27 @@ class LoadJobConfig(_JobConfig): else: self._del_sub_prop("parquetOptions") + @property + def column_name_character_map(self) -> str: + """Optional[google.cloud.bigquery.job.ColumnNameCharacterMap]: + Character map supported for column names in CSV/Parquet loads. Defaults + to STRICT and can be overridden by Project Config Service. Using this + option with unsupported load formats will result in an error. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.column_name_character_map + """ + return self._get_sub_prop( + "columnNameCharacterMap", + ColumnNameCharacterMap.COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED, + ) + + @column_name_character_map.setter + def column_name_character_map(self, value: Optional[str]): + if value is None: + value = ColumnNameCharacterMap.COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED + self._set_sub_prop("columnNameCharacterMap", value) + class LoadJob(_AsyncJob): """Asynchronous job for loading data into a table.
support load job option ColumnNameCharacterMap Support new field ColumnNameCharacterMap: https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#columnnamecharactermap
googleapis/python-bigquery
diff --git a/tests/unit/job/test_load_config.py b/tests/unit/job/test_load_config.py index e1fa2641..becf3e95 100644 --- a/tests/unit/job/test_load_config.py +++ b/tests/unit/job/test_load_config.py @@ -843,3 +843,42 @@ class TestLoadJobConfig(_Base): config.parquet_options = None self.assertNotIn("parquetOptions", config._properties["load"]) + + def test_column_name_character_map_missing(self): + from google.cloud.bigquery.job.load import ColumnNameCharacterMap + + config = self._get_target_class()() + self.assertEqual( + config.column_name_character_map, + ColumnNameCharacterMap.COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED, + ) + + def test_column_name_character_map_hit(self): + from google.cloud.bigquery.job.load import ColumnNameCharacterMap + + config = self._get_target_class()() + config._properties["load"]["columnNameCharacterMap"] = "STRICT" + self.assertEqual( + config.column_name_character_map, + ColumnNameCharacterMap.STRICT, + ) + + def test_column_name_character_map_setter(self): + from google.cloud.bigquery.job.load import ColumnNameCharacterMap + + config = self._get_target_class()() + config.column_name_character_map = "V1" + self.assertEqual( + config._properties["load"]["columnNameCharacterMap"], + ColumnNameCharacterMap.V1, + ) + + def test_column_name_character_map_none(self): + from google.cloud.bigquery.job.load import ColumnNameCharacterMap + + config = self._get_target_class()() + config.column_name_character_map = None + self.assertEqual( + config._properties["load"]["columnNameCharacterMap"], + ColumnNameCharacterMap.COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED, + )
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
3.24
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asttokens==3.0.0 attrs==25.3.0 cachetools==5.5.2 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 comm==0.2.2 coverage==7.8.0 db-dtypes==1.4.2 debugpy==1.8.13 decorator==5.2.1 Deprecated==1.2.18 exceptiongroup==1.2.2 executing==2.2.0 fiona==1.10.1 geopandas==0.14.4 google-api-core==2.24.2 google-auth==2.38.0 -e git+https://github.com/googleapis/python-bigquery.git@5d10f1e94222e635cf008d83928555a628cdbb3f#egg=google_cloud_bigquery google-cloud-bigquery-storage==2.30.0 google-cloud-core==2.4.3 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 grpcio==1.71.0 grpcio-status==1.63.0rc1 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 jedi==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyterlab_widgets==3.0.13 matplotlib-inline==0.1.7 nest-asyncio==1.6.0 numpy==2.0.2 opentelemetry-api==1.31.1 opentelemetry-instrumentation==0.52b1 opentelemetry-sdk==1.31.1 opentelemetry-semantic-conventions==0.52b1 packaging==24.2 pandas==2.2.3 parso==0.8.4 pexpect==4.9.0 platformdirs==4.3.7 pluggy==1.5.0 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==4.25.6 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 Pygments==2.19.1 pyproj==3.6.1 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==26.3.0 requests==2.32.3 rsa==4.9 shapely==2.0.7 six==1.17.0 stack-data==0.6.3 tomli==2.2.1 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 wcwidth==0.2.13 widgetsnbextension==4.0.13 wrapt==1.17.2 zipp==3.21.0
name: python-bigquery channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asttokens==3.0.0 - attrs==25.3.0 - cachetools==5.5.2 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - comm==0.2.2 - coverage==7.8.0 - db-dtypes==1.4.2 - debugpy==1.8.13 - decorator==5.2.1 - deprecated==1.2.18 - exceptiongroup==1.2.2 - executing==2.2.0 - fiona==1.10.1 - geopandas==0.14.4 - google-api-core==2.24.2 - google-auth==2.38.0 - google-cloud-bigquery-storage==2.30.0 - google-cloud-core==2.4.3 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - grpcio==1.71.0 - grpcio-status==1.63.0rc1 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - jedi==0.19.2 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyterlab-widgets==3.0.13 - matplotlib-inline==0.1.7 - nest-asyncio==1.6.0 - numpy==2.0.2 - opentelemetry-api==1.31.1 - opentelemetry-instrumentation==0.52b1 - opentelemetry-sdk==1.31.1 - opentelemetry-semantic-conventions==0.52b1 - packaging==24.2 - pandas==2.2.3 - parso==0.8.4 - pexpect==4.9.0 - platformdirs==4.3.7 - pluggy==1.5.0 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==4.25.6 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pygments==2.19.1 - pyproj==3.6.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==26.3.0 - requests==2.32.3 - rsa==4.9 - shapely==2.0.7 - six==1.17.0 - stack-data==0.6.3 - tomli==2.2.1 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - wcwidth==0.2.13 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - zipp==3.21.0 prefix: /opt/conda/envs/python-bigquery
[ "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_column_name_character_map_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_column_name_character_map_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_column_name_character_map_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_column_name_character_map_setter" ]
[]
[ "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_allow_jagged_rows_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_allow_jagged_rows_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_allow_jagged_rows_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_allow_quoted_newlines_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_allow_quoted_newlines_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_allow_quoted_newlines_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_autodetect_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_autodetect_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_autodetect_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_clustering_fields_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_clustering_fields_miss", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_clustering_fields_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_clustering_fields_setter_w_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_connection_properties", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_create_disposition_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_create_disposition_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_create_disposition_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_create_session", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_ctor_w_properties", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_decimal_target_types_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_decimal_target_types_miss", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_decimal_target_types_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_decimal_target_types_setter_w_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_encryption_configuration_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_encryption_configuration_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_encryption_configuration_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_encryption_configuration_setter_w_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_description_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_description_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_description_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_description_setter_w_fn_already", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_description_w_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_friendly_name_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_friendly_name_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_friendly_name_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_friendly_name_setter_w_descr_already", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_destination_table_friendly_name_w_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_encoding_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_encoding_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_encoding_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_field_delimiter_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_field_delimiter_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_field_delimiter_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_hive_partitioning_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_hive_partitioning_invalid_type", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_hive_partitioning_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_hive_partitioning_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_ignore_unknown_values_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_ignore_unknown_values_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_ignore_unknown_values_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_json_extension_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_json_extension_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_json_extension_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_max_bad_records_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_max_bad_records_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_max_bad_records_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_null_marker_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_null_marker_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_null_marker_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_parquet_options_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_parquet_options_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_parquet_options_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_parquet_options_setter_clearing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_preserve_ascii_control_characters_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_preserve_ascii_control_characters_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_preserve_ascii_control_characters_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_projection_fields_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_projection_fields_miss", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_quote_character_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_quote_character_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_quote_character_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_range_partitioning_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_range_partitioning_setter_w_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_range_partitioning_setter_w_wrong_type", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_range_partitioning_w_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_range_partitioning_w_value", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_setter_fields", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_setter_invalid_mappings_list", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_setter_unsetting_schema", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_setter_valid_mappings_list", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_update_options_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_update_options_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_schema_update_options_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_skip_leading_rows_hit_w_integer", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_skip_leading_rows_hit_w_str", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_skip_leading_rows_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_skip_leading_rows_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_source_format_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_source_format_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_source_format_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_time_partitioning_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_time_partitioning_miss", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_time_partitioning_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_time_partitioning_setter_w_none", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_to_api_repr_includes_json_extension", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_use_avro_logical_types", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_use_avro_logical_types_setter", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_write_disposition_hit", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_write_disposition_missing", "tests/unit/job/test_load_config.py::TestLoadJobConfig::test_write_disposition_setter" ]
[]
Apache License 2.0
18,680
548
[ "google/cloud/bigquery/job/load.py" ]
tobymao__sqlglot-3650
88c49651ecc9d55967f5c8056352de0f0981989f
2024-06-13 11:02:24
a739741dca5eefd7d4a2c450dd4506cb951d7efb
diff --git a/sqlglot/parser.py b/sqlglot/parser.py index cf5cc9d4..cbce4b7a 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -150,6 +150,7 @@ class Parser(metaclass=_Parser): to=exp.DataType(this=exp.DataType.Type.TEXT), ), "GLOB": lambda args: exp.Glob(this=seq_get(args, 1), expression=seq_get(args, 0)), + "HEX": build_hex, "JSON_EXTRACT": build_extract_json_with_path(exp.JSONExtract), "JSON_EXTRACT_SCALAR": build_extract_json_with_path(exp.JSONExtractScalar), "JSON_EXTRACT_PATH_TEXT": build_extract_json_with_path(exp.JSONExtractScalar), @@ -157,11 +158,13 @@ class Parser(metaclass=_Parser): "LOG": build_logarithm, "LOG2": lambda args: exp.Log(this=exp.Literal.number(2), expression=seq_get(args, 0)), "LOG10": lambda args: exp.Log(this=exp.Literal.number(10), expression=seq_get(args, 0)), + "LOWER": build_lower, "MOD": build_mod, "TIME_TO_TIME_STR": lambda args: exp.Cast( this=seq_get(args, 0), to=exp.DataType(this=exp.DataType.Type.TEXT), ), + "TO_HEX": build_hex, "TS_OR_DS_TO_DATE_STR": lambda args: exp.Substring( this=exp.Cast( this=seq_get(args, 0), @@ -170,11 +173,9 @@ class Parser(metaclass=_Parser): start=exp.Literal.number(1), length=exp.Literal.number(10), ), - "VAR_MAP": build_var_map, - "LOWER": build_lower, + "UNNEST": lambda args: exp.Unnest(expressions=ensure_list(seq_get(args, 0))), "UPPER": build_upper, - "HEX": build_hex, - "TO_HEX": build_hex, + "VAR_MAP": build_var_map, } NO_PAREN_FUNCTIONS = {
Regression in 25.1.0 when the write dialect is postgres and the read dialect is omitted Hi, we ran into the following change of behaviour in 25.1.0. ``` >>> from sqlglot import parse_one >>> parse_one("SELECT unnest(ARRAY[1, 2, 3])").sql() 'SELECT UNNEST(1, 2, 3)' >>> parse_one("SELECT unnest(ARRAY[1, 2, 3])").sql(dialect="postgres") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/expressions.py", line 597, in sql return Dialect.get_or_raise(dialect).generate(self, **opts) File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/dialects/dialect.py", line 538, in generate return self.generator(**opts).generate(expression, copy=copy) File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/generator.py", line 623, in generate sql = self.sql(expression).strip() File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/generator.py", line 777, in sql sql = transform(self, expression) File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/transforms.py", line 650, in _to_sql return _sql_handler(expression) File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/generator.py", line 2302, in select_sql expressions = self.expressions(expression) File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/generator.py", line 3371, in expressions sql = self.sql(e, comment=False) File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/generator.py", line 782, in sql sql = getattr(self, exp_handler_name)(expression) File "/home/ronan/.virtualenvs/insitu/lib/python3.9/site-packages/sqlglot/dialects/postgres.py", line 584, in unnest_sql if len(expression.expressions) == 1: TypeError: object of type 'Array' has no len() >>> parse_one("SELECT unnest(ARRAY[1, 2, 3])", dialect="postgres").sql(dialect="postgres") 'SELECT UNNEST(ARRAY[1, 2, 3])' ``` I realized that this only occurs when the read dialect is not specified, so the workaround for us was to make sure that we added the dialect parameter to `parse_one()`, but I thought I would file the issue in case it would be useful.
tobymao/sqlglot
diff --git a/tests/test_parser.py b/tests/test_parser.py index d6849c3d..d6be7ae3 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -102,6 +102,13 @@ class TestParser(unittest.TestCase): def test_float(self): self.assertEqual(parse_one(".2"), parse_one("0.2")) + def test_unnest(self): + unnest_sql = "UNNEST(foo)" + expr = parse_one(unnest_sql) + self.assertIsInstance(expr, exp.Unnest) + self.assertIsInstance(expr.expressions, list) + self.assertEqual(expr.sql(), unnest_sql) + def test_unnest_projection(self): expr = parse_one("SELECT foo IN UNNEST(bla) AS bar") self.assertIsInstance(expr.selects[0], exp.Alias)
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
25.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest_v2", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest -xvs" }
cfgv==3.4.0 coverage==7.8.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 Pygments==2.19.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@88c49651ecc9d55967f5c8056352de0f0981989f#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - coverage==7.8.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pygments==2.19.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/test_parser.py::TestParser::test_unnest", "tests/test_parser.py::TestParser::test_unnest_projection", "tests/test_parser.py::TestParser::test_values_as_identifier", "tests/test_parser.py::TestParser::test_var" ]
[]
[ "tests/test_parser.py::TestParser::test_alter_set", "tests/test_parser.py::TestParser::test_column", "tests/test_parser.py::TestParser::test_command", "tests/test_parser.py::TestParser::test_comment_error_n", "tests/test_parser.py::TestParser::test_comment_error_r", "tests/test_parser.py::TestParser::test_comments_delete", "tests/test_parser.py::TestParser::test_comments_delete_cte", "tests/test_parser.py::TestParser::test_comments_insert", "tests/test_parser.py::TestParser::test_comments_insert_cte", "tests/test_parser.py::TestParser::test_comments_select", "tests/test_parser.py::TestParser::test_comments_select_cte", "tests/test_parser.py::TestParser::test_comments_update", "tests/test_parser.py::TestParser::test_comments_update_cte", "tests/test_parser.py::TestParser::test_create_table_error", "tests/test_parser.py::TestParser::test_distinct_from", "tests/test_parser.py::TestParser::test_expression", "tests/test_parser.py::TestParser::test_float", "tests/test_parser.py::TestParser::test_identify", "tests/test_parser.py::TestParser::test_lambda_struct", "tests/test_parser.py::TestParser::test_missing_by", "tests/test_parser.py::TestParser::test_multi", "tests/test_parser.py::TestParser::test_parameter", "tests/test_parser.py::TestParser::test_parse_concat_ws", "tests/test_parser.py::TestParser::test_parse_create_schema", "tests/test_parser.py::TestParser::test_parse_drop_schema", "tests/test_parser.py::TestParser::test_parse_empty", "tests/test_parser.py::TestParser::test_parse_errors", "tests/test_parser.py::TestParser::test_parse_floats", "tests/test_parser.py::TestParser::test_parse_intervals", "tests/test_parser.py::TestParser::test_parse_into", "tests/test_parser.py::TestParser::test_parse_into_error", "tests/test_parser.py::TestParser::test_parse_into_errors", "tests/test_parser.py::TestParser::test_parse_nested", "tests/test_parser.py::TestParser::test_parse_prop_eq", "tests/test_parser.py::TestParser::test_parse_properties", "tests/test_parser.py::TestParser::test_parse_terse_coalesce", "tests/test_parser.py::TestParser::test_pivot_columns", "tests/test_parser.py::TestParser::test_pretty_config_override", "tests/test_parser.py::TestParser::test_rename_table", "tests/test_parser.py::TestParser::test_select", "tests/test_parser.py::TestParser::test_set_expression", "tests/test_parser.py::TestParser::test_space", "tests/test_parser.py::TestParser::test_structs", "tests/test_parser.py::TestParser::test_table", "tests/test_parser.py::TestParser::test_trailing_comments", "tests/test_parser.py::TestParser::test_transactions", "tests/test_parser.py::TestParser::test_tuple", "tests/test_parser.py::TestParser::test_type_literals", "tests/test_parser.py::TestParser::test_unary_plus", "tests/test_parser.py::TestParser::test_union" ]
[]
MIT License
18,684
497
[ "sqlglot/parser.py" ]
sosw__sosw-327
8811c1e633ade255fbd4c009f83bef4ece0e1e6a
2024-06-18 16:57:37
231bc0a12a729913eab0b2966a58963a74735774
diff --git a/sosw/app.py b/sosw/app.py index ae6ac18..aee950a 100644 --- a/sosw/app.py +++ b/sosw/app.py @@ -74,13 +74,13 @@ class Processor: self.test = kwargs.get('test') or True if os.environ.get('STAGE') in ['test', 'autotest'] else False - self.lambda_context = kwargs.pop('context', None) - if self.lambda_context: - logger.warning("DEPRECATED: Processor.lambda_context is deprecated. Use global_vars.lambda_context instead") - self.aws_account = trim_arn_to_account(self.lambda_context.invoked_function_arn) + if global_vars.lambda_context: + self.aws_account = trim_arn_to_account(getattr(global_vars.lambda_context, 'invoked_function_arn', None)) + logger.info("Setting self.aws_account from Lambda context to: %s", self.aws_account) self.init_config(custom_config=custom_config) - logger.info(f"Final {self.__class__.__name__} processor config: {self.config}") + logger.info("Final %s processor config", self.__class__.__name__) + logger.info(self.config) self.stats = defaultdict(int) self.result = defaultdict(int) @@ -94,7 +94,9 @@ class Processor: After that, a specific custom config of the Lambda will recursively update the existing one. The last step is update config recursively with a passed custom_config. - Overwrite this method if custom logic of recursive updates in configs is required + Overwrite this method if custom logic of recursive updates in configs is required. + + .. note:: Read more about :ref:`Config_Sourse` :param Dict custom_config: dict with custom configurations """ @@ -229,17 +231,15 @@ class Processor: """ Get current AWS Account to construct different ARNs. - We dont' have this parameter in Environmental variables, only can parse from Context. - Context is not global and is supposed to be passed by your `lambda_handler` during initialization. - - As a fallback we have an autodetection mechanism, but it is pretty heavy (~0.3 seconds). - So it is not called by default. This method should be used only if you really need it. + We don't have this parameter in Environmental variables, only can parse from Context. It is stored + in ``global_vars`` and is supposed to be passed by your `lambda_handler` during initialization. - It is highly recommended to pass the `context` during initialization. + As a fallback for cases when we use ``Processor`` not in the Lambda environment, we have a lazy autodetection + mechanism using STS, but it is pretty heavy (~0.3 seconds). Some things to note: - We store this value in class variable for fast access - - If not yet set on the first call we initialise it. + - It uses Lazy initialization. - We first try from context and only if not provided - use the autodetection. """ @@ -444,8 +444,8 @@ def get_lambda_handler(processor_class, global_vars=None, custom_config=None): """ if global_vars is None: - logging.error(f"Your Lambda did not pass global_vars. It should be an instance of LambdaGlobals class, " - f"initialised in your Lambda function at the root level. Some functionality will break soon.") + logger.error("Your Lambda did not pass global_vars. It should be an instance of LambdaGlobals class, " + "initialised in your Lambda function at the root level. Some functionality will break soon.") global_vars = LambdaGlobals() @@ -461,9 +461,10 @@ def get_lambda_handler(processor_class, global_vars=None, custom_config=None): if event.get('logging_level'): logger.setLevel(event.get('logging_level')) - logger.info(f"Called {os.environ.get('AWS_LAMBDA_FUNCTION_NAME')} lambda of " - f"version {os.environ.get('AWS_LAMBDA_FUNCTION_VERSION')} with __name__: {__name__}," - f"event: {event}, context: {context}") + logger.info("Called %s lambda of version %s with __name__: %s, context: %s", + os.environ.get('AWS_LAMBDA_FUNCTION_NAME'), os.environ.get('AWS_LAMBDA_FUNCTION_VERSION'), + __name__, context) + logger.info(event) test = event.get('test') or True if os.environ.get('STAGE') in ['test', 'autotest'] else False @@ -474,12 +475,13 @@ def get_lambda_handler(processor_class, global_vars=None, custom_config=None): result = global_vars.processor(event) - logger.info(f"stats: {global_vars.processor.get_stats()}") - global_vars.processor.reset_stats() - logger.info(f"result: {result}") + logger.info(global_vars.processor.get_stats()) + global_vars.processor.reset_stats() global_vars.processor.reset_stats(recursive=True) + logger.info(result) + return result diff --git a/sosw/components/config.py b/sosw/components/config.py index 2e5cd82..8e9c552 100644 --- a/sosw/components/config.py +++ b/sosw/components/config.py @@ -132,13 +132,13 @@ class SecretsManager: can_paginate = getattr(secretsmanager_client, 'can_paginate')(f) if can_paginate: - logging.debug("SecretsManager.%s can natively paginate", f) + logger.debug("SecretsManager.%s can natively paginate", f) paginator = secretsmanager_client.get_paginator(f) response = paginator.paginate(**kwargs) return response else: - logging.debug("SecretsManager.%s can not natively paginate", f) + logger.debug("SecretsManager.%s can not natively paginate", f) response_list = [] response = func(**kwargs) response_list.append(response) @@ -187,7 +187,7 @@ class SecretsManager: secret_value = secretsmanager_client.get_secret_value(SecretId=secret['ARN']) secrets_dict[secret['Name']] = secret_value['SecretString'] else: - logging.warning('No credentials found in SecretsManager for %s with %s', filter_type, value) + logger.warning('No credentials found in SecretsManager for %s with %s', filter_type, value) return secrets_dict return secrets_dict
Fix `self.aws_account` initialization In `app.Processor.__init__` And make sure it doesn't break other use-cases Should try to work when run both in Lambda and from local script. - When running in Lambda definitely take from the context. - When running locally - call STS. And this one has to be covered carefully with both Unit and Integration tests in different runtimes. This issue appeared somewhere when upgrading from older versions of Python.
sosw/sosw
diff --git a/sosw/test/unit/test_app.py b/sosw/test/unit/test_app.py index b2e993a..9236d6e 100644 --- a/sosw/test/unit/test_app.py +++ b/sosw/test/unit/test_app.py @@ -2,7 +2,6 @@ import boto3 import os import unittest -from unittest import mock from unittest.mock import MagicMock, patch os.environ["STAGE"] = "test" @@ -26,21 +25,26 @@ class app_UnitTestCase(unittest.TestCase): def setUp(self): pass - def tearDown(self): try: del (os.environ['AWS_LAMBDA_FUNCTION_NAME']) except Exception: pass + # global_vars.processor is a property that refers to another global. So we have to reset it explicitly. + # And at the same time we don't want to reset it during reinitialization in the working environment + global _processor, global_vars + global_vars = LambdaGlobals() + global_vars.processor = None + - @mock.patch("boto3.client") + @patch("boto3.client") def test_app_init(self, mock_boto_client): Processor(custom_config=self.TEST_CONFIG) self.assertTrue(True) - @mock.patch("boto3.client") + @patch("boto3.client") def test_app__pre_call__reset_stats(self, _): processor = Processor(custom_config=self.TEST_CONFIG) processor.__call__(event={'k': 'success'}) @@ -50,7 +54,7 @@ class app_UnitTestCase(unittest.TestCase): self.assertEqual(processor.stats['total_processor_calls'], 1) - @mock.patch("boto3.client") + @patch("boto3.client") def test_app_init__with_some_clients(self, mock_boto_client): custom_config = { 'init_clients': ['Sns', 'Siblings'], @@ -65,7 +69,7 @@ class app_UnitTestCase(unittest.TestCase): self.assertIsNotNone(getattr(processor, 'siblings_client')) - @mock.patch("boto3.client") + @patch("boto3.client") def test_app_init__boto_and_components_custom_clients(self, mock_boto_client): custom_config = { 'init_clients': ['dynamodb', 'Siblings'], @@ -82,7 +86,7 @@ class app_UnitTestCase(unittest.TestCase): self.assertEqual(str(type(getattr(processor, 'dynamodb_client'))), str(type(boto3.client('dynamodb')))) - @mock.patch("boto3.client") + @patch("boto3.client") def test_app_init__with_some_invalid_client(self, mock_boto_client): custom_config = { 'init_clients': ['NotExists'] @@ -91,7 +95,7 @@ class app_UnitTestCase(unittest.TestCase): mock_boto_client.assert_called_with('not_exists') - @mock.patch("sosw.app.get_config") + @patch("sosw.app.get_config") def test_app_calls_get_config(self, mock_ssm): mock_ssm.return_value = {'mock': 'called'} @@ -113,6 +117,9 @@ class app_UnitTestCase(unittest.TestCase): def test_lambda_handler(self): + mock_context = MagicMock() + mock_context.invoked_function_arn = 'arn:aws:lambda:us-east-1:123456789012:function:example:42' + global_vars = LambdaGlobals() self.assertIsNone(global_vars.processor) self.assertIsNone(global_vars.lambda_context) @@ -121,25 +128,53 @@ class app_UnitTestCase(unittest.TestCase): self.assertIsNotNone(lambda_handler) for i in range(3): - result = lambda_handler(event={'k': 'success'}, context={'context': 'test'}) + result = lambda_handler(event={'k': 'success'}, context=mock_context) self.assertEqual(type(global_vars.processor), self.Child) - self.assertEqual(global_vars.lambda_context, {'context': 'test'}) + self.assertEqual(global_vars.lambda_context, mock_context) self.assertEqual(result, 'success') self.assertEqual(global_vars.processor.stats['total_processor_calls'], i + 1) self.assertEqual(global_vars.processor.stats['total_calls_register_clients'], 1) - @mock.patch("boto3.client") + def test_property_account__initialized_from_context(self): + mock_context = MagicMock() + mock_context.invoked_function_arn = 'arn:aws:lambda:us-east-1:123456789000:function:example:42' + + self.assertIsNone(global_vars.lambda_context) + + lambda_handler = get_lambda_handler(self.Child, global_vars, self.TEST_CONFIG) + lambda_handler(event={'k': 'success'}, context=mock_context) + + self.assertEqual('123456789000', global_vars.processor._account) + + + @patch("boto3.client") + def test_property_account__initialized_from_sts(self, boto_client_mock): + + get_caller_identity_mock = MagicMock() + get_caller_identity_mock.get.return_value='001234567890' + + client_mock = MagicMock() + client_mock.get_caller_identity.return_value = get_caller_identity_mock + + boto_client_mock.return_value = client_mock + + p = Processor() + self.assertEqual('001234567890', p._account) + get_caller_identity_mock.get.assert_called_once_with('Account') + + + @patch("boto3.client") @patch.object(logger, 'setLevel') def test_lambda_handler__logger_level(self, logger_set_level, client_mock): global_vars = LambdaGlobals() lambda_handler = get_lambda_handler(self.Child, global_vars, self.TEST_CONFIG) event = {'k': 'm', 'logging_level': 20} - lambda_handler(event=event, context={'context': 'test'}) + lambda_handler(event=event, context=None) logger_set_level.assert_called_once_with(20) - @mock.patch("boto3.client") + @patch("boto3.client") def test_die(self, mock_boto): p = Processor(custom_config=self.TEST_CONFIG) @@ -148,7 +183,7 @@ class app_UnitTestCase(unittest.TestCase): p.die() - @mock.patch("boto3.client") + @patch("boto3.client") def test_die__uncatchable_death(self, mock_boto): class Child(Processor): @@ -164,7 +199,7 @@ class app_UnitTestCase(unittest.TestCase): p.catch_me() - @mock.patch("boto3.client") + @patch("boto3.client") def test_die__calls_sns(self, mock_boto): mock_boto_client = MagicMock()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest ./sosw/test/suite_unit.py --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 ApiDoc==1.4.0 autodoc==0.5.0 babel==2.17.0 beautifulsoup4==4.13.3 boto3==1.37.23 botocore==1.37.23 certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 decorator==5.2.1 docutils==0.19 exceptiongroup==1.2.2 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 Jinja2==2.7.3 jmespath==1.0.1 jsonschema==2.4.0 MarkupSafe==3.0.2 packaging==24.2 pluggy==1.5.0 Pygments==2.19.1 pyparsing==3.2.3 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==3.11 requests==2.32.3 s3transfer==0.11.4 six==1.17.0 snowballstemmer==2.2.0 -e git+https://github.com/sosw/sosw.git@8811c1e633ade255fbd4c009f83bef4ece0e1e6a#egg=sosw soupsieve==2.6 Sphinx==5.1.1 sphinx-sitemap==2.6.0 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 sphinxcontrib-websupport==2.0.0 tomli==2.2.1 typing_extensions==4.13.0 urllib3==1.26.20 waitress==3.0.2 WebOb==1.8.9 WebTest==3.0.4 zipp==3.21.0
name: sosw channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - apidoc==1.4.0 - autodoc==0.5.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - boto3==1.37.23 - botocore==1.37.23 - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - decorator==5.2.1 - docutils==0.19 - exceptiongroup==1.2.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jinja2==2.7.3 - jmespath==1.0.1 - jsonschema==2.4.0 - markupsafe==3.0.2 - packaging==24.2 - pluggy==1.5.0 - pygments==2.19.1 - pyparsing==3.2.3 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==3.11 - requests==2.32.3 - s3transfer==0.11.4 - six==1.17.0 - snowballstemmer==2.2.0 - soupsieve==2.6 - sphinx==5.1.1 - sphinx-sitemap==2.6.0 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - sphinxcontrib-websupport==2.0.0 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==1.26.20 - waitress==3.0.2 - webob==1.8.9 - webtest==3.0.4 - zipp==3.21.0 prefix: /opt/conda/envs/sosw
[ "sosw/test/suite_unit.py::app_UnitTestCase::test_property_account__initialized_from_context", "sosw/test/unit/test_app.py::app_UnitTestCase::test_property_account__initialized_from_context" ]
[]
[ "sosw/test/suite_unit.py::app_UnitTestCase::test_app__pre_call__reset_stats", "sosw/test/suite_unit.py::app_UnitTestCase::test_app_calls_get_config", "sosw/test/suite_unit.py::app_UnitTestCase::test_app_init", "sosw/test/suite_unit.py::app_UnitTestCase::test_app_init__boto_and_components_custom_clients", "sosw/test/suite_unit.py::app_UnitTestCase::test_app_init__with_some_clients", "sosw/test/suite_unit.py::app_UnitTestCase::test_app_init__with_some_invalid_client", "sosw/test/suite_unit.py::app_UnitTestCase::test_die", "sosw/test/suite_unit.py::app_UnitTestCase::test_die__calls_sns", "sosw/test/suite_unit.py::app_UnitTestCase::test_die__uncatchable_death", "sosw/test/suite_unit.py::app_UnitTestCase::test_lambda_handler", "sosw/test/suite_unit.py::app_UnitTestCase::test_lambda_handler__logger_level", "sosw/test/suite_unit.py::app_UnitTestCase::test_property_account__initialized_from_sts", "sosw/test/suite_unit.py::Labourer_UnitTestCase::test_get_attr", "sosw/test/suite_unit.py::Labourer_UnitTestCase::test_init", "sosw/test/suite_unit.py::Labourer_UnitTestCase::test_init__strict_raises", "sosw/test/suite_unit.py::Labourer_UnitTestCase::test_init_attrs", "sosw/test/suite_unit.py::Labourer_UnitTestCase::test_set_custom_attributes", "sosw/test/suite_unit.py::Labourer_UnitTestCase::test_set_defaults", "sosw/test/suite_unit.py::Labourer_UnitTestCase::test_set_defaults__called", "sosw/test/suite_unit.py::Labourer_UnitTestCase::test_set_defaults_overrides", "sosw/test/suite_unit.py::Orchestrator_UnitTestCase::test_get_desired_invocation_number_for_labourer", "sosw/test/suite_unit.py::Orchestrator_UnitTestCase::test_get_desired_invocation_number_for_labourer__default", "sosw/test/suite_unit.py::Orchestrator_UnitTestCase::test_invoke_for_labourer__calls__get_desired_invocation_number_for_labourer", "sosw/test/suite_unit.py::Orchestrator_UnitTestCase::test_invoke_for_labourer__calls_invoke_tasks__and__meta_handler", "sosw/test/suite_unit.py::Orchestrator_UnitTestCase::test_invoke_for_labourer__desired_zero", "sosw/test/suite_unit.py::Orchestrator_UnitTestCase::test_true", "sosw/test/suite_unit.py::Scavenger_UnitTestCase::test_calculate_delay_for_task_retry", "sosw/test/suite_unit.py::Scavenger_UnitTestCase::test_call", "sosw/test/suite_unit.py::Scavenger_UnitTestCase::test_handle_expired_tasks_for_labourer", "sosw/test/suite_unit.py::Scavenger_UnitTestCase::test_process_expired_task__close", "sosw/test/suite_unit.py::Scavenger_UnitTestCase::test_process_expired_task__dont_close", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test__queue_bucket", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test__remote_queue_file", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test__remote_queue_locked_file", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_apply_job_schema", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_apply_job_schema__chunkable_attrs_reinitialized", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_apply_job_schema__default", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_apply_job_schema__default_preserved", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_call__sample", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_dates", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_dates__last_x_days", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_dates__pops_period", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_dates__preserve_skeleton", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_dates__preserve_skeleton__if_no_chunking", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_dates__raises_invalid_period_pattern", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job__max_items_per_batch", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job__not_chunkable_config", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job__not_raises__notchunkable__if_no_isolation", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job__not_raises_unchunkable_subtask__but_preserves_in_payload", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job__raises__unsupported_vals__list_not_as_value", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job__raises__unsupported_vals__string", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job__root_level_isolate", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_chunk_job__unchunckable_preserve_custom_attrs", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_construct_job_data", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_construct_job_data__empty_job", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_construct_job_data__preserve_skeleton_through_chunkers", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_construct_job_data__real_payload__for_debuging_logs", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_custom_period_patterns", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_extract_job_from_payload", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_extract_job_from_payload_raises", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_get_and_lock_queue_file__local_file_exists", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_get_and_lock_queue_file__s3_calls", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_get_index_from_list", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_get_isolate_attributes_from_job", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_get_next_chunkable_attr", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_init__chunkable_attrs_not_end_with_s", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_last_week", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_last_x_days", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_needs_chunking__isolate_root", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_needs_chunking__isolate_subdata", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_needs_chunking__isolate_subdata_deep", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_needs_chunking__max_items_per_batch", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_parse_job_to_file", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_parse_job_to_file__multiple_rows", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_pop_rows_from_file", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_pop_rows_from_file__missing_or_empty_file", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_pop_rows_from_file__reads_from_top", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_previous_x_days", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_process_file", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_sleeptime_for_dynamo", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_today", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_validate_list_of_vals", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_x_days_back", "sosw/test/suite_unit.py::Scheduler_UnitTestCase::test_yesterday", "sosw/test/suite_unit.py::Worker_UnitTestCase::test_mark_task_as_completed__called", "sosw/test/suite_unit.py::WorkerAssistant_UnitTestCase::test_call__mark_task_as_closed", "sosw/test/suite_unit.py::WorkerAssistant_UnitTestCase::test_call__mark_task_as_closed__no_task_id__raises", "sosw/test/suite_unit.py::WorkerAssistant_UnitTestCase::test_call__unknown_action__raises", "sosw/test/suite_unit.py::Config_UnitTestCase::test_custom_client", "sosw/test/suite_unit.py::Config_UnitTestCase::test_custom_client__multiple", "sosw/test/suite_unit.py::Config_UnitTestCase::test_default_sources", "sosw/test/suite_unit.py::Config_UnitTestCase::test_get_config", "sosw/test/suite_unit.py::Config_UnitTestCase::test_update_config", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test__parse_filter_expression", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test__parse_filter_expression__raises", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_batch_get_items_one_table__not_strict", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_batch_get_items_one_table__strict", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_create__calls_boto_client", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_create__calls_put", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_create__raises__if_no_hash_col_configured", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dict_to_dynamo__not_strict__map_type", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dict_to_dynamo__numeric_float", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dict_to_dynamo_not_strict", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dict_to_dynamo_prefix", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dict_to_dynamo_strict", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dynamo_to_dict", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dynamo_to_dict__do_json_loads", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dynamo_to_dict__dont_json_loads", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dynamo_to_dict__mapping_doesnt_match__raises", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_dynamo_to_dict_no_strict_row_mapper", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_get_by_query__between", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_get_by_query__expr_attr", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_get_by_query__max_items_and_count__raises", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_get_by_query__strongly_consistent_read", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_get_by_query__validates_comparison", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_get_table_indexes__ppr", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_get_table_indexes__pt", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_on_demand_provisioned_throughput__get_capacity", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_on_demand_provisioned_throughput__get_table_indexes", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_patch__transfers_attrs_to_remove", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_sleep_db__", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_sleep_db__fell_asleep", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_sleep_db__get_capacity_called", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_sleep_db__returns_none_for_on_demand", "sosw/test/suite_unit.py::dynamodb_client_UnitTestCase::test_sleep_db__wrong_action", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_chunks", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_construct_dates_from_event__conflict_of_attributes", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_construct_dates_from_event__missing_attributes", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_construct_dates_from_event__ok", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_convert_string_to_words", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_dunder_to_dict", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_dunder_to_dict__exceptions", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_first_or_none", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_get_list_of_multiple_or_one_or_empty_from_dict", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_get_message_dict_from_sns_event", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_get_message_dict_from_sns_event__from_sqs", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_get_message_dict_from_sns_event__many_messages__raises", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_get_message_dict_from_sns_event__raises", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_get_one_from_dict", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_get_one_or_none_from_dict", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_is_event_from_sns_false", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_is_event_from_sns_invalid_events", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_is_event_from_sns_true", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_is_event_from_sqs__many", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_is_event_from_sqs__signle", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_make_hash", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_negative_validate_date_from_something", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_nested_dict_from_keys", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_recursive_match_extract", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_recursive_matches_soft", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_recursive_matches_strict", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_recursive_update", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_recursive_update_2", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_recursive_update__does_overwrite_with_none", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_recursive_update__inserts_new_keys", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_recursive_update__unhashable_types_in_lists", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_rstrip_all", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_small_int_from_string", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_to_bool", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_trim_arn_to_account", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_trim_arn_to_name", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_unwrap_event_recursively__not_wrapped", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_unwrap_event_recursively__sns", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_unwrap_event_recursively__sns2", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_unwrap_event_recursively__sns_inside_sqs", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_unwrap_event_recursively__sqs_dict", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_account_to_dashed_invalid", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_account_to_dashed_valid", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_date_from_something", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_date_list_from_event_or_days_back", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_datetime_from_something", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_list_of_numbers_from_csv", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_list_of_words_from_csv_or_list__ok", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_list_of_words_from_csv_or_list__raises", "sosw/test/suite_unit.py::helpers_UnitTestCase::test_validate_string_matches_datetime_format", "sosw/test/suite_unit.py::siblings_TestCase::test_any_events_rules_enabled", "sosw/test/suite_unit.py::siblings_TestCase::test_get_approximate_concurrent_executions", "sosw/test/suite_unit.py::siblings_TestCase::test_spawn_sibling", "sosw/test/suite_unit.py::sns_TestCase::test_commit_and_queue_on_change_subject", "sosw/test/suite_unit.py::sns_TestCase::test_commit_auto_on_change_recipient", "sosw/test/suite_unit.py::sns_TestCase::test_commit_on_change_message_attributes", "sosw/test/suite_unit.py::sns_TestCase::test_commit_on_change_subject", "sosw/test/suite_unit.py::sns_TestCase::test_commit_queue", "sosw/test/suite_unit.py::sns_TestCase::test_create_subscription_invalid_params", "sosw/test/suite_unit.py::sns_TestCase::test_create_topic_invalid_name", "sosw/test/suite_unit.py::sns_TestCase::test_create_topic_return_value", "sosw/test/suite_unit.py::sns_TestCase::test_get_message_attribute_validate_output", "sosw/test/suite_unit.py::sns_TestCase::test_init__reads_config", "sosw/test/suite_unit.py::sns_TestCase::test_no_commit_on_change_recipient_if_recipient_is_same", "sosw/test/suite_unit.py::sns_TestCase::test_no_commit_on_change_subject_if_subject_is_same", "sosw/test/suite_unit.py::sns_TestCase::test_no_commit_on_same_subject", "sosw/test/suite_unit.py::sns_TestCase::test_queue_message", "sosw/test/suite_unit.py::sns_TestCase::test_queue_message_with_subject", "sosw/test/suite_unit.py::sns_TestCase::test_validate_recipient", "sosw/test/suite_unit.py::sigv4_TestCase::test_call", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_authorization_header", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_canonical_headers", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_canonical_querystring", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_canonical_uri", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_canonical_uri__with_pah", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_headers_and_credential_date", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_payload_hash__get_method", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_payload_hash__post_method", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_payload_hash__post_method_no_body", "sosw/test/suite_unit.py::sigv4_TestCase::test_get_signature_key", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test__jsonify_payload_of_task", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_archive_task", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_construct_payload_for_task", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_create_task", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_create_task__combine_complex_payload", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_average_labourer_duration__calculates_average", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_average_labourer_duration__calls_dynamo_twice", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_count_of_running_tasks_for_labourer", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_db_field_name", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_labourers", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_newest_greenfield_for_labourer__no_queued_tasks", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_oldest_greenfield_for_labourer__no_queued_tasks", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_tasks_to_retry_for_labourer", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_tasks_to_retry_for_labourer__limit", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_get_tasks_to_retry_for_labourer__respects_greenfield", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_health_metrics_received", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_invoke_task__calls__get_task_by_id", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_invoke_task__calls__lambda_client", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_invoke_task__calls__mark_task_invoked", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_invoke_task__not_calls__lambda_client_if_raised_conditional_exception", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_invoke_task__validates_task", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_invoke_task__with_explicit_task__not_calls_get_task_by_id", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_mark_task_invoked__calls_dynamo", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_move_task_to_retry_table", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_move_task_to_retry_table__dumps_payload", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_register_labourers", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_register_labourers__calls_register_task_manager", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_validate_task__bad", "sosw/test/suite_unit.py::task_manager_UnitTestCase::test_validate_task__good", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_add_running_tasks_for_labourer", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_count_running_tasks_for_labourer__calls_task_manager", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_count_running_tasks_for_labourer__raises_not_task_client", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_count_running_tasks_for_labourer__use_local_cache", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_eco_statuses", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_fetch_metric_stats__calculates_time", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_fetch_metric_stats__calls_boto", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_fetch_metric_stats__use_defaults", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_get_health", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_get_health__invalid", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_get_labourer_status", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_get_labourer_status__uses_cache", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_get_max_labourer_duration", "sosw/test/suite_unit.py::ecology_manager_UnitTestCase::test_register_task_manager__resets_stats", "sosw/test/suite_unit.py::meta_handler_UnitTestCase::test_post__check_create_call", "sosw/test/suite_unit.py::meta_handler_UnitTestCase::test_post__check_create_call_with_args_from_kwargs", "sosw/test/suite_unit.py::meta_handler_UnitTestCase::test_post__raise_kwargs_intersection_with_lambda_context", "sosw/test/unit/test_app.py::app_UnitTestCase::test_app_calls_get_config", "sosw/test/unit/test_app.py::app_UnitTestCase::test_app_init", "sosw/test/unit/test_app.py::app_UnitTestCase::test_app_init__boto_and_components_custom_clients", "sosw/test/unit/test_app.py::app_UnitTestCase::test_app_init__with_some_clients", "sosw/test/unit/test_app.py::app_UnitTestCase::test_app_init__with_some_invalid_client", "sosw/test/unit/test_app.py::app_UnitTestCase::test_die", "sosw/test/unit/test_app.py::app_UnitTestCase::test_die__calls_sns", "sosw/test/unit/test_app.py::app_UnitTestCase::test_die__uncatchable_death", "sosw/test/unit/test_app.py::app_UnitTestCase::test_lambda_handler", "sosw/test/unit/test_app.py::app_UnitTestCase::test_lambda_handler__logger_level", "sosw/test/unit/test_app.py::app_UnitTestCase::test_property_account__initialized_from_sts" ]
[ "sosw/test/unit/test_app.py::app_UnitTestCase::test_app__pre_call__reset_stats" ]
MIT License
18,717
1,486
[ "sosw/app.py", "sosw/components/config.py" ]
openmc-dev__openmc-3045
e33e66aa888453efaf43afcc94e7d6b2c74b1e7c
2024-06-18 20:34:55
e33e66aa888453efaf43afcc94e7d6b2c74b1e7c
diff --git a/openmc/model/surface_composite.py b/openmc/model/surface_composite.py index 1fa4234fb..7c134e843 100644 --- a/openmc/model/surface_composite.py +++ b/openmc/model/surface_composite.py @@ -233,7 +233,7 @@ class IsogonalOctagon(CompositeSurface): r"""Infinite isogonal octagon composite surface An isogonal octagon is composed of eight planar surfaces. The prism is - parallel to the x, y, or z axis. The remaining two axes (y and z, z and x, + parallel to the x, y, or z axis. The remaining two axes (y and z, x and z, or x and y) serve as a basis for constructing the surfaces. Two surfaces are parallel to the first basis axis, two surfaces are parallel to the second basis axis, and the remaining four surfaces intersect both @@ -241,7 +241,7 @@ class IsogonalOctagon(CompositeSurface): This class acts as a proper surface, meaning that unary `+` and `-` operators applied to it will produce a half-space. The negative side is - defined to be the region inside of the octogonal prism. + defined to be the region inside of the octagonal prism. .. versionadded:: 0.13.1 @@ -249,7 +249,7 @@ class IsogonalOctagon(CompositeSurface): ---------- center : iterable of float Coordinate for the central axis of the octagon in the - (y, z), (z, x), or (x, y) basis. + (y, z), (x, z), or (x, y) basis depending on the axis parameter. r1 : float Half-width of octagon across its basis axis-parallel sides in units of cm. Must be less than :math:`r_2\sqrt{2}`. @@ -290,7 +290,7 @@ class IsogonalOctagon(CompositeSurface): def __init__(self, center, r1, r2, axis='z', **kwargs): c1, c2 = center - # Coords for axis-perpendicular planes + # Coordinates for axis-perpendicular planes cright = c1 + r1 cleft = c1 - r1 @@ -307,7 +307,7 @@ class IsogonalOctagon(CompositeSurface): L_basis_ax = (r2 * sqrt(2) - r1) - # Coords for quadrant planes + # Coordinates for quadrant planes p1_ur = np.array([L_basis_ax, r1, 0.]) p2_ur = np.array([r1, L_basis_ax, 0.]) p3_ur = np.array([r1, L_basis_ax, 1.]) @@ -335,17 +335,18 @@ class IsogonalOctagon(CompositeSurface): self.right = openmc.XPlane(cright, **kwargs) self.left = openmc.XPlane(cleft, **kwargs) elif axis == 'y': - coord_map = [1, 2, 0] - self.top = openmc.XPlane(ctop, **kwargs) - self.bottom = openmc.XPlane(cbottom, **kwargs) - self.right = openmc.ZPlane(cright, **kwargs) - self.left = openmc.ZPlane(cleft, **kwargs) + coord_map = [0, 2, 1] + self.top = openmc.ZPlane(ctop, **kwargs) + self.bottom = openmc.ZPlane(cbottom, **kwargs) + self.right = openmc.XPlane(cright, **kwargs) + self.left = openmc.XPlane(cleft, **kwargs) elif axis == 'x': coord_map = [2, 0, 1] self.top = openmc.ZPlane(ctop, **kwargs) self.bottom = openmc.ZPlane(cbottom, **kwargs) self.right = openmc.YPlane(cright, **kwargs) self.left = openmc.YPlane(cleft, **kwargs) + self.axis = axis # Put our coordinates in (x,y,z) order and add the offset for p in points: @@ -363,14 +364,27 @@ class IsogonalOctagon(CompositeSurface): **kwargs) def __neg__(self): - return -self.top & +self.bottom & -self.right & +self.left & \ - +self.upper_right & +self.lower_right & -self.lower_left & \ - -self.upper_left + if self.axis == 'y': + region = -self.top & +self.bottom & -self.right & +self.left & \ + -self.upper_right & -self.lower_right & +self.lower_left & \ + +self.upper_left + else: + region = -self.top & +self.bottom & -self.right & +self.left & \ + +self.upper_right & +self.lower_right & -self.lower_left & \ + -self.upper_left + + return region def __pos__(self): - return +self.top | -self.bottom | +self.right | -self.left | \ - -self.upper_right | -self.lower_right | +self.lower_left | \ - +self.upper_left + if self.axis == 'y': + region = +self.top | -self.bottom | +self.right | -self.left | \ + +self.upper_right | +self.lower_right | -self.lower_left | \ + -self.upper_left + else: + region = +self.top | -self.bottom | +self.right | -self.left | \ + -self.upper_right | -self.lower_right | +self.lower_left | \ + +self.upper_left + return region class RightCircularCylinder(CompositeSurface):
Make `IsogonalOctagon` objects parallel to `y` axis use `xz` basis. ## Description <!--What is the feature or enhancement?--> Currently, `IsogonalOctagon` objects parallel to the `y` axis will assume a `zx` basis. This was done to make the implementation easier. In practice, it is confusing for users, so we should switch to a `xz` basis. ## Alternatives <!--If alternative solutions have been considered, describe them here and the reasoning for the chosen solution ---> The alternative is leaving the implementation as is ## Compatibility <!--Will the enhancement change existing APIs or add something new?--> The only API chagne will be that the `center` parameter when the ` axis` parameter is `'y'` will now assume an `(x,z)` format instead of a `(z,x)` format
openmc-dev/openmc
diff --git a/tests/unit_tests/test_surface_composite.py b/tests/unit_tests/test_surface_composite.py index 62ec18b32..01c827223 100644 --- a/tests/unit_tests/test_surface_composite.py +++ b/tests/unit_tests/test_surface_composite.py @@ -255,7 +255,7 @@ def test_cylinder_sector_from_theta_alpha(): @pytest.mark.parametrize( "axis, plane_tb, plane_lr, axis_idx", [ ("x", "Z", "Y", 0), - ("y", "X", "Z", 1), + ("y", "Z", "X", 1), ("z", "Y", "X", 2), ] )
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.10", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asttokens==3.0.0 contourpy==1.3.1 coverage==7.8.0 cycler==0.12.1 decorator==5.2.1 exceptiongroup==1.2.2 execnet==2.1.1 executing==2.2.0 fonttools==4.56.0 h5py==3.13.0 iniconfig==2.1.0 ipython==8.34.0 jedi==0.19.2 kiwisolver==1.4.8 lxml==5.3.1 matplotlib==3.10.1 matplotlib-inline==0.1.7 numpy==2.2.4 -e git+https://github.com/openmc-dev/openmc.git@e33e66aa888453efaf43afcc94e7d6b2c74b1e7c#egg=openmc packaging==24.2 pandas==2.2.3 parso==0.8.4 pexpect==4.9.0 pillow==11.1.0 pluggy==1.5.0 prompt_toolkit==3.0.50 ptyprocess==0.7.0 pure_eval==0.2.3 Pygments==2.19.1 pyparsing==3.2.3 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 scipy==1.15.2 six==1.17.0 stack-data==0.6.3 tomli==2.2.1 traitlets==5.14.3 typing_extensions==4.13.0 tzdata==2025.2 uncertainties==3.2.2 wcwidth==0.2.13
name: openmc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py310h06a4308_0 - python=3.10.16=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py310h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py310h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asttokens==3.0.0 - contourpy==1.3.1 - coverage==7.8.0 - cycler==0.12.1 - decorator==5.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - executing==2.2.0 - fonttools==4.56.0 - h5py==3.13.0 - iniconfig==2.1.0 - ipython==8.34.0 - jedi==0.19.2 - kiwisolver==1.4.8 - lxml==5.3.1 - matplotlib==3.10.1 - matplotlib-inline==0.1.7 - numpy==2.2.4 - openmc==0.14.1.dev0 - packaging==24.2 - pandas==2.2.3 - parso==0.8.4 - pexpect==4.9.0 - pillow==11.1.0 - pluggy==1.5.0 - prompt-toolkit==3.0.50 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pygments==2.19.1 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - scipy==1.15.2 - six==1.17.0 - stack-data==0.6.3 - tomli==2.2.1 - traitlets==5.14.3 - typing-extensions==4.13.0 - tzdata==2025.2 - uncertainties==3.2.2 - wcwidth==0.2.13 prefix: /opt/conda/envs/openmc
[ "tests/unit_tests/test_surface_composite.py::test_isogonal_octagon[y-Z-X-1]" ]
[]
[ "tests/unit_tests/test_surface_composite.py::test_rectangular_parallelepiped", "tests/unit_tests/test_surface_composite.py::test_right_circular_cylinder[X-indices0]", "tests/unit_tests/test_surface_composite.py::test_right_circular_cylinder[Y-indices1]", "tests/unit_tests/test_surface_composite.py::test_right_circular_cylinder[Z-indices2]", "tests/unit_tests/test_surface_composite.py::test_cone_one_sided[X-point_pos0-point_neg0-ll_true0]", "tests/unit_tests/test_surface_composite.py::test_cone_one_sided[Y-point_pos1-point_neg1-ll_true1]", "tests/unit_tests/test_surface_composite.py::test_cone_one_sided[Z-point_pos2-point_neg2-ll_true2]", "tests/unit_tests/test_surface_composite.py::test_cylinder_sector[X-indices0-center0]", "tests/unit_tests/test_surface_composite.py::test_cylinder_sector[Y-indices1-center1]", "tests/unit_tests/test_surface_composite.py::test_cylinder_sector[Z-indices2-center2]", "tests/unit_tests/test_surface_composite.py::test_cylinder_sector[X-indices3-center3]", "tests/unit_tests/test_surface_composite.py::test_cylinder_sector[Y-indices4-center4]", "tests/unit_tests/test_surface_composite.py::test_cylinder_sector[Z-indices5-center5]", "tests/unit_tests/test_surface_composite.py::test_cylinder_sector_from_theta_alpha", "tests/unit_tests/test_surface_composite.py::test_isogonal_octagon[x-Z-Y-0]", "tests/unit_tests/test_surface_composite.py::test_isogonal_octagon[z-Y-X-2]", "tests/unit_tests/test_surface_composite.py::test_polygon", "tests/unit_tests/test_surface_composite.py::test_cruciform_prism[x]", "tests/unit_tests/test_surface_composite.py::test_cruciform_prism[y]", "tests/unit_tests/test_surface_composite.py::test_cruciform_prism[z]" ]
[]
MIT License
18,721
1,345
[ "openmc/model/surface_composite.py" ]
int-brain-lab__ibllib-787
73c912ef85099b711753310bca3bf2771f77e433
2024-06-19 10:18:48
73c912ef85099b711753310bca3bf2771f77e433
diff --git a/ibllib/io/extractors/mesoscope.py b/ibllib/io/extractors/mesoscope.py index ade22240..8754869a 100644 --- a/ibllib/io/extractors/mesoscope.py +++ b/ibllib/io/extractors/mesoscope.py @@ -746,6 +746,15 @@ class MesoscopeSyncTimeline(extractors_base.BaseExtractor): Calculate the time shifts for each field of view (FOV) and the relative offsets for each scan line. + For a 2 scan field, 2 depth recording (so 4 FOVs): + + Frame 1, lines 1-512 correspond to FOV_00 + Frame 1, lines 551-1062 correspond to FOV_01 + Frame 2, lines 1-512 correspond to FOV_02 + Frame 2, lines 551-1062 correspond to FOV_03 + Frame 3, lines 1-512 correspond to FOV_00 + ... + Parameters ---------- raw_imaging_meta : dict @@ -765,26 +774,27 @@ class MesoscopeSyncTimeline(extractors_base.BaseExtractor): FOVs = raw_imaging_meta['FOV'] # Double-check meta extracted properly - raw_meta = raw_imaging_meta['rawScanImageMeta'] - artist = raw_meta['Artist'] - assert sum(x['enable'] for x in artist['RoiGroups']['imagingRoiGroup']['rois']) == len(FOVs) - + # assert meta.FOV.Zs is ascending but use slice_id field. This may not be necessary but is expected. + slice_ids = np.array([fov['slice_id'] for fov in FOVs]) + assert np.all(np.diff([x['Zs'] for x in FOVs]) >= 0), 'FOV depths not in ascending order' + assert np.all(np.diff(slice_ids) >= 0), 'slice IDs not ordered' # Number of scan lines per FOV, i.e. number of Y pixels / image height n_lines = np.array([x['nXnYnZ'][1] for x in FOVs]) - n_valid_lines = np.sum(n_lines) # Number of lines imaged excluding flybacks - # Number of lines during flyback - n_lines_per_gap = int((raw_meta['Height'] - n_valid_lines) / (len(FOVs) - 1)) - # The start and end indices of each FOV in the raw images - fov_start_idx = np.insert(np.cumsum(n_lines[:-1] + n_lines_per_gap), 0, 0) - fov_end_idx = fov_start_idx + n_lines - line_period = raw_imaging_meta['scanImageParams']['hRoiManager']['linePeriod'] - - line_indices = [] - fov_time_shifts = fov_start_idx * line_period - line_time_shifts = [] - for ln, s, e in zip(n_lines, fov_start_idx, fov_end_idx): - line_indices.append(np.arange(s, e)) - line_time_shifts.append(np.arange(0, ln) * line_period) + # We get indices from MATLAB extracted metadata so below two lines are no longer needed + # n_valid_lines = np.sum(n_lines) # Number of lines imaged excluding flybacks + # n_lines_per_gap = int((raw_meta['Height'] - n_valid_lines) / (len(FOVs) - 1)) # N lines during flyback + line_period = raw_imaging_meta['scanImageParams']['hRoiManager']['linePeriod'] + frame_time_shifts = slice_ids / raw_imaging_meta['scanImageParams']['hRoiManager']['scanFrameRate'] + + # Line indices are now extracted by the MATLAB function mesoscopeMetadataExtraction.m + # They are indexed from 1 so we subtract 1 to convert to zero-indexed + line_indices = [np.array(fov['lineIdx']) - 1 for fov in FOVs] # Convert to zero-indexed from MATLAB 1-indexed + assert all(lns.size == n for lns, n in zip(line_indices, n_lines)), 'unexpected number of scan lines' + # The start indices of each FOV in the raw images + fov_start_idx = np.array([lns[0] for lns in line_indices]) + roi_time_shifts = fov_start_idx * line_period # The time offset for each FOV + fov_time_shifts = roi_time_shifts + frame_time_shifts + line_time_shifts = [(lns - ln0) * line_period for lns, ln0 in zip(line_indices, fov_start_idx)] return line_indices, fov_time_shifts, line_time_shifts diff --git a/ibllib/pipes/mesoscope_tasks.py b/ibllib/pipes/mesoscope_tasks.py index fae64a1f..ba103337 100644 --- a/ibllib/pipes/mesoscope_tasks.py +++ b/ibllib/pipes/mesoscope_tasks.py @@ -626,10 +626,10 @@ class MesoscopeSync(base_tasks.MesoscopeTask): (f'_{self.sync_namespace}_DAQdata.timestamps.npy', self.sync_collection, True), (f'_{self.sync_namespace}_DAQdata.meta.json', self.sync_collection, True), ('_ibl_rawImagingData.meta.json', self.device_collection, True), - ('rawImagingData.times_scanImage.npy', self.device_collection, True), + ('rawImagingData.times_scanImage.npy', self.device_collection, True, True), # register raw (f'_{self.sync_namespace}_softwareEvents.log.htsv', self.sync_collection, False), ], 'output_files': [('mpci.times.npy', 'alf/mesoscope/FOV*', True), - ('mpciStack.timeshift.npy', 'alf/mesoscope/FOV*', True), ] + ('mpciStack.timeshift.npy', 'alf/mesoscope/FOV*', True),] } return signature diff --git a/ibllib/pipes/tasks.py b/ibllib/pipes/tasks.py index e03be0d5..a409ed1e 100644 --- a/ibllib/pipes/tasks.py +++ b/ibllib/pipes/tasks.py @@ -88,6 +88,7 @@ from ibllib.oneibl.registration import get_lab from iblutil.util import Bunch import one.params from one.api import ONE +from one.util import ensure_list from one import webclient _logger = logging.getLogger(__name__) @@ -107,7 +108,7 @@ class Task(abc.ABC): time_elapsed_secs = None time_out_secs = 3600 * 2 # time-out after which a task is considered dead version = ibllib.__version__ - signature = {'input_files': [], 'output_files': []} # list of tuples (filename, collection, required_flag) + signature = {'input_files': [], 'output_files': []} # list of tuples (filename, collection, required_flag[, register]) force = False # whether to re-download missing input files on local server if not present job_size = 'small' # either 'small' or 'large', defines whether task should be run as part of the large or small job services env = None # the environment name within which to run the task (NB: the env is not activated automatically!) @@ -173,6 +174,13 @@ class Task(abc.ABC): -1: Errored -2: Didn't run as a lock was encountered -3: Incomplete + + Notes + ----- + - The `run_alyx_task` will update the Alyx Task status depending on both status and outputs + (i.e. the output of subclassed `_run` method): + Assuming a return value of 0... if Task.outputs is None, the status will be Empty; + if Task.outputs is a list (empty or otherwise), the status will be Complete. """ # if task id of one properties are not available, local run only without alyx use_alyx = self.one is not None and self.taskid is not None @@ -201,12 +209,13 @@ class Task(abc.ABC): start_time = time.time() try: setup = self.setUp(**kwargs) + self.outputs = self._input_files_to_register() _logger.info(f'Setup value is: {setup}') self.status = 0 if not setup: # case where outputs are present but don't have input files locally to rerun task # label task as complete - _, self.outputs = self.assert_expected_outputs() + _, outputs = self.assert_expected_outputs() else: # run task if self.gpu >= 1: @@ -218,8 +227,15 @@ class Task(abc.ABC): _logger.removeHandler(ch) ch.close() return self.status - self.outputs = self._run(**kwargs) + outputs = self._run(**kwargs) _logger.info(f'Job {self.__class__} complete') + if outputs is None: + # If run method returns None and no raw input files were registered, self.outputs + # should be None, meaning task will have an 'Empty' status. If run method returns + # a list, the status will be 'Complete' regardless of whether there are output files. + self.outputs = outputs if not self.outputs else self.outputs # ensure None if no inputs registered + else: + self.outputs.extend(ensure_list(outputs)) # Add output files to list of inputs to register except Exception: _logger.error(traceback.format_exc()) _logger.info(f'Job {self.__class__} errored') @@ -263,6 +279,41 @@ class Task(abc.ABC): _ = self.register_images() return self.data_handler.uploadData(self.outputs, self.version, **kwargs) + def _input_files_to_register(self, assert_all_exist=False): + """ + Return input datasets to be registered to Alyx. + + These datasets are typically raw data files and are registered even if the task fails to complete. + + Parameters + ---------- + assert_all_exist + Raise AssertionError if not all required input datasets exist on disk. + + Returns + ------- + list of pathlib.Path + A list of input files to register. + """ + try: + input_files = self.input_files + except AttributeError: + raise RuntimeError('Task.setUp must be run before calling this method.') + to_register, missing = [], [] + for filename, collection, required, _ in filter(lambda f: len(f) > 3 and f[3], input_files): + filepath = self.session_path.joinpath(collection, filename) + if filepath.exists(): + to_register.append(filepath) + elif required: + missing.append(filepath) + if any(missing): + missing_str = ', '.join(map(lambda x: x.relative_to(self.session_path).as_posix(), missing)) + if assert_all_exist: + raise AssertionError(f'Missing required input files: {missing_str}') + else: + _logger.error(f'Missing required input files: {missing_str}') + return list(set(to_register) - set(missing)) + def register_images(self, **kwargs): """ Registers images to alyx database @@ -766,7 +817,7 @@ def run_alyx_task(tdict=None, session_path=None, one=None, job_deck=None, patch_data = {'time_elapsed_secs': task.time_elapsed_secs, 'log': task.log, 'version': task.version} # if there is no data to register, set status to Empty - if task.outputs is None: + if task.outputs is None: # NB: an empty list is still considered Complete. patch_data['status'] = 'Empty' # otherwise register data and set (provisional) status to Complete else:
mesoscope extractor expects nr of FOVs == nr or ROIs in raw SI tif For multi-depth imaging, the nr of FOVs we define in the metadata (one per unique scanfield*depth) is not equal to the nr of 'enabled' ROIs in the header of the scanimage tifs (one per unique scanfield). However, the mesoscope extractor currently asserts this and returns an error if it doesn't, causing MesoscopeSync task to fail. This assertion should either be removed or replaced with something more general referring to the unique roiUUIDs e.g. something like `assert sum(x['enable'] for x in artist['RoiGroups']['imagingRoiGroup']['rois']) == len(np.unique(raw_imaging_meta['FOV']['roiUUID'])) ` https://github.com/int-brain-lab/ibllib/blob/ced2259847fb2663f460c762649e4317b67abb2a/ibllib/io/extractors/mesoscope.py#L770
int-brain-lab/ibllib
diff --git a/ibllib/tests/extractors/test_mesoscope.py b/ibllib/tests/extractors/test_mesoscope.py new file mode 100644 index 00000000..b9447b63 --- /dev/null +++ b/ibllib/tests/extractors/test_mesoscope.py @@ -0,0 +1,64 @@ +"""Tests for ibllib.io.extractors.mesoscope module.""" +import unittest +from itertools import repeat, chain + +import numpy as np + +from ibllib.io.extractors import mesoscope + + +class TestMesoscopeSyncTimeline(unittest.TestCase): + """Tests for MesoscopeSyncTimeline extractor class.""" + def setUp(self) -> None: + """Simulate for meta data for 9 FOVs at 3 different depths. + + These simulated values match those from SP048/2024-02-05/001. + """ + n_lines_flyback = 75 + self.n_lines = 512 + self.n_FOV = 9 + n_depths = 3 + assert self.n_FOV > n_depths and self.n_FOV % n_depths == 0 + reps = int(self.n_FOV / n_depths) + start_depth = 60 + delta_depth = 40 + self.line_period = 4.158e-05 + + self.meta = { + 'scanImageParams': {'hRoiManager': {'linePeriod': self.line_period, 'scanFrameRate': 13.6803}}, + 'FOV': [] + } + nXnYnZ = [self.n_lines, self.n_lines, 1] + for i, slice_id in enumerate(chain.from_iterable(map(lambda x: list(repeat(x, reps)), range(n_depths)))): + offset = (i % n_depths) * (self.n_lines + n_lines_flyback) - ((i % n_depths) - 1) + offset = offset or 1 # start at 1 for MATLAB indexing + fov = {'slice_id': slice_id, 'Zs': start_depth + (delta_depth * slice_id), + 'nXnYnZ': nXnYnZ, 'lineIdx': list(range(offset, self.n_lines + offset))} + self.meta['FOV'].append(fov) + + def test_get_timeshifts_multidepth(self): + """Test MescopeSyncTimeline.get_timeshifts method. + + This tests output when given multiple FOVs at different depths. The tasks/mesoscope_tasks.py + module in iblscripts more thoroughly tests single-depth imaging with real data. + """ + line_indices, fov_time_shifts, line_time_shifts = mesoscope.MesoscopeSyncTimeline.get_timeshifts(self.meta) + expected = [np.array(x['lineIdx']) for x in self.meta['FOV']] + self.assertTrue(np.all(x == y) for x, y in zip(expected, line_indices)) + self.assertEqual(self.n_FOV, len(fov_time_shifts)) + self.assertEqual(self.n_FOV, len(line_time_shifts)) + self.assertTrue(all(len(x) == self.n_lines for x in line_time_shifts)) + + expected = self.line_period * np.arange(self.n_lines) + for i, line_shifts in enumerate(line_time_shifts): + with self.subTest(f'FOV == {i}'): + self.assertEqual(self.n_lines, len(line_shifts)) + np.testing.assert_almost_equal(expected, line_shifts) + + # NB: The following values are fixed for the setup parameters + expected = [0., 0.02436588, 0.04873176, 0.07309781, 0.09746369, 0.12182957, 0.14619562, 0.1705615, 0.19492738] + np.testing.assert_almost_equal(expected, fov_time_shifts) + + +if __name__ == '__main__': + unittest.main() diff --git a/ibllib/tests/test_mesoscope.py b/ibllib/tests/test_mesoscope.py index 7ae3e5cd..f62d42fa 100644 --- a/ibllib/tests/test_mesoscope.py +++ b/ibllib/tests/test_mesoscope.py @@ -1,4 +1,4 @@ -"""Tests for ibllib.pipes.mesoscope_tasks""" +"""Tests for ibllib.pipes.mesoscope_tasks.""" import sys import unittest from unittest import mock diff --git a/ibllib/tests/test_tasks.py b/ibllib/tests/test_tasks.py index a3f5cff0..482697b3 100644 --- a/ibllib/tests/test_tasks.py +++ b/ibllib/tests/test_tasks.py @@ -113,6 +113,7 @@ class TaskGpuLock(ibllib.pipes.tasks.Task): def setUp(self): self.make_lock_file() self.data_handler = self.get_data_handler() + self.input_files = [] return True def _run(self, overwrite=False): @@ -357,6 +358,42 @@ class TestDynamicTask(unittest.TestCase): self.assertEqual('raw_ephys_data/probe00', collection) +class TestTask(unittest.TestCase): + def setUp(self): + tmpdir = tempfile.TemporaryDirectory() + self.addCleanup(tmpdir.cleanup) + self.tmpdir = Path(tmpdir.name) + self.session_path = self.tmpdir.joinpath('subject', '1900-01-01', '001') + self.session_path.mkdir(parents=True) + + def test_input_files_to_register(self): + """Test for Task._input_files_to_register method.""" + task = Task00(self.session_path) + self.assertRaises(RuntimeError, task._input_files_to_register) + task.input_files = [('register.optional.ext', 'alf', False, True), + ('register.optional_foo.ext', 'alf', False, True), + ('register.required.ext', 'alf', True, True), + ('ignore.required.ext', 'alf', True), + ('ignore.optional.ext', 'alf', False)] + self.session_path.joinpath('alf').mkdir() + for f in task.input_files: + self.session_path.joinpath(f[1], f[0]).touch() + files = task._input_files_to_register(assert_all_exist=True) + expected = [self.session_path.joinpath('alf', 'register.required.ext'), + self.session_path.joinpath('alf', 'register.optional.ext'), + self.session_path.joinpath('alf', 'register.optional_foo.ext')] + self.assertCountEqual(files, expected) + expected[2].unlink() + with self.assertNoLogs(ibllib.pipes.tasks.__name__, level='ERROR'): + files = task._input_files_to_register(assert_all_exist=True) + self.assertCountEqual(files, expected[:2]) + expected[0].unlink() + with self.assertLogs(ibllib.pipes.tasks.__name__, level='ERROR'): + files = task._input_files_to_register(assert_all_exist=False) + self.assertEqual(files, expected[1:2]) + self.assertRaises(AssertionError, task._input_files_to_register, assert_all_exist=True) + + class TestMisc(unittest.TestCase): """Tests for misc functions in ibllib.pipes.tasks module."""
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 3 }
2.36
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
boto3==1.37.23 botocore==1.37.23 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 click==8.1.8 cloudpickle==3.1.1 colorcet==3.1.0 colorlog==6.9.0 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 exceptiongroup==1.2.2 flake8==7.2.0 fonttools==4.56.0 fsspec==2025.3.1 globus-sdk==3.53.0 graphviz==0.20.3 ibl-neuropixel==1.4.0 iblatlas==0.5.4 -e git+https://github.com/int-brain-lab/ibllib.git@73c912ef85099b711753310bca3bf2771f77e433#egg=ibllib iblutil==1.16.0 idna==3.10 imageio==2.37.0 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 jmespath==1.0.1 joblib==1.4.2 kiwisolver==1.4.7 lazy_loader==0.4 llvmlite==0.43.0 locket==1.0.0 matplotlib==3.9.4 mccabe==0.7.0 mtscomp==1.0.2 networkx==3.2.1 npTDMS==1.10.0 numba==0.60.0 numpy==2.0.2 ONE-api==2.11.2 opencv-python-headless==4.11.0.86 packaging==24.2 pandas==2.2.3 partd==1.4.2 patsy==1.0.1 phylib==2.6.0 pillow==11.1.0 pluggy==1.5.0 Psychofit==1.0.0.post0 pyarrow==19.0.1 pycodestyle==2.13.0 pycparser==2.22 pyflakes==3.3.2 PyJWT==2.10.1 pynrrd==1.1.3 pyparsing==3.2.3 PyQt5==5.15.11 PyQt5-Qt5==5.15.16 PyQt5_sip==12.17.0 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 requests==2.32.3 s3transfer==0.11.4 scikit-image==0.24.0 scikit-learn==1.6.1 scipy==1.13.1 seaborn==0.13.2 six==1.17.0 slidingRP==1.1.1 sparse==0.15.5 statsmodels==0.14.4 threadpoolctl==3.6.0 tifffile==2024.8.30 tomli==2.2.1 toolz==1.0.0 tqdm==4.67.1 typing_extensions==4.13.0 tzdata==2025.2 urllib3==1.26.20 zipp==3.21.0
name: ibllib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - boto3==1.37.23 - botocore==1.37.23 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - click==8.1.8 - cloudpickle==3.1.1 - colorcet==3.1.0 - colorlog==6.9.0 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - exceptiongroup==1.2.2 - flake8==7.2.0 - fonttools==4.56.0 - fsspec==2025.3.1 - globus-sdk==3.53.0 - graphviz==0.20.3 - ibl-neuropixel==1.4.0 - iblatlas==0.5.4 - iblutil==1.16.0 - idna==3.10 - imageio==2.37.0 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - jmespath==1.0.1 - joblib==1.4.2 - kiwisolver==1.4.7 - lazy-loader==0.4 - llvmlite==0.43.0 - locket==1.0.0 - matplotlib==3.9.4 - mccabe==0.7.0 - mtscomp==1.0.2 - networkx==3.2.1 - nptdms==1.10.0 - numba==0.60.0 - numpy==2.0.2 - one-api==2.11.2 - opencv-python-headless==4.11.0.86 - packaging==24.2 - pandas==2.2.3 - partd==1.4.2 - patsy==1.0.1 - phylib==2.6.0 - pillow==11.1.0 - pluggy==1.5.0 - psychofit==1.0.0.post0 - pyarrow==19.0.1 - pycodestyle==2.13.0 - pycparser==2.22 - pyflakes==3.3.2 - pyjwt==2.10.1 - pynrrd==1.1.3 - pyparsing==3.2.3 - pyqt5==5.15.11 - pyqt5-qt5==5.15.16 - pyqt5-sip==12.17.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - requests==2.32.3 - s3transfer==0.11.4 - scikit-image==0.24.0 - scikit-learn==1.6.1 - scipy==1.13.1 - seaborn==0.13.2 - six==1.17.0 - slidingrp==1.1.1 - sparse==0.15.5 - statsmodels==0.14.4 - threadpoolctl==3.6.0 - tifffile==2024.8.30 - tomli==2.2.1 - toolz==1.0.0 - tqdm==4.67.1 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==1.26.20 - zipp==3.21.0 prefix: /opt/conda/envs/ibllib
[ "ibllib/tests/extractors/test_mesoscope.py::TestMesoscopeSyncTimeline::test_get_timeshifts_multidepth" ]
[ "ibllib/tests/test_tasks.py::TestTask::test_input_files_to_register" ]
[ "ibllib/tests/test_mesoscope.py::TestMesoscopePreprocess::test_get_default_tau", "ibllib/tests/test_mesoscope.py::TestMesoscopePreprocess::test_meta", "ibllib/tests/test_mesoscope.py::TestMesoscopeFOV::test_find_triangle", "ibllib/tests/test_mesoscope.py::TestMesoscopeFOV::test_get_provenance", "ibllib/tests/test_mesoscope.py::TestMesoscopeFOV::test_nearest_neighbour_1d", "ibllib/tests/test_mesoscope.py::TestMesoscopeFOV::test_surface_normal", "ibllib/tests/test_mesoscope.py::TestMesoscopeFOV::test_update_surgery_json", "ibllib/tests/test_mesoscope.py::TestRegisterFOV::test_register_fov", "ibllib/tests/test_mesoscope.py::TestImagingMeta::test_patch_imaging_meta", "ibllib/tests/test_tasks.py::TestPipelineAlyx::test_pipeline_alyx", "ibllib/tests/test_tasks.py::TestLocks::test_gpu_lock_and_local_data_handler", "ibllib/tests/test_tasks.py::TestExperimentDescriptionRegisterRaw::test_experiment_description_registration", "ibllib/tests/test_tasks.py::TestDynamicTask::test_get_device_collection", "ibllib/tests/test_tasks.py::TestMisc::test_str2class" ]
[]
MIT License
18,724
2,782
[ "ibllib/io/extractors/mesoscope.py", "ibllib/pipes/mesoscope_tasks.py", "ibllib/pipes/tasks.py" ]
ipython__ipython-14466
1454013b8b615ce75d30d38b7710e3fccca16263
2024-06-20 11:01:28
1454013b8b615ce75d30d38b7710e3fccca16263
diff --git a/IPython/lib/pretty.py b/IPython/lib/pretty.py index 631445b24..8a24632d6 100644 --- a/IPython/lib/pretty.py +++ b/IPython/lib/pretty.py @@ -406,8 +406,16 @@ def pretty(self, obj): meth = cls._repr_pretty_ if callable(meth): return meth(obj, self, cycle) - if cls is not object \ - and callable(cls.__dict__.get('__repr__')): + if ( + cls is not object + # check if cls defines __repr__ + and "__repr__" in cls.__dict__ + # check if __repr__ is callable. + # Note: we need to test getattr(cls, '__repr__') + # instead of cls.__dict__['__repr__'] + # in order to work with descriptors like partialmethod, + and callable(_safe_getattr(cls, "__repr__", None)) + ): return _repr_pprint(obj, self, cycle) return _default_pprint(obj, self, cycle)
`display` does not honor custom `__repr__` for `NamedTuple` when defined by `partialmethod` The issue occurs when the custom `__repr__` is defined via `partialmethod`: ```python from functools import partialmethod from typing import NamedTuple def my_pprint(obj, **options): return "Hello World" def add_custom_pprint(cls=None, **options): if cls is None: def decorator(cls): return add_custom_pprint(cls, **options) return decorator cls.__repr__ = partialmethod(my_pprint, **options) return cls @add_custom_pprint class MyNamedTuple(NamedTuple): x: int y: int x = MyNamedTuple(1, 2) print(x) # "Hello World" display(x) # (1, 2) ``` <details><summary> without partialmethod, both display and print give the same result: </summary> ```python from typing import NamedTuple def my_pprint(obj, **options): return "Hello World" def add_custom_pprint(cls=None, **options): if cls is None: def decorator(cls): return add_custom_pprint(cls, **options) return decorator cls.__repr__ = my_pprint return cls @add_custom_pprint class MyNamedTuple(NamedTuple): x: int y: int x = MyNamedTuple(1, 2) print(x) # "Hello World" display(x) # "Hello World" ``` </details>
ipython/ipython
diff --git a/IPython/core/tests/test_formatters.py b/IPython/core/tests/test_formatters.py index c642befac..cd8c83e55 100644 --- a/IPython/core/tests/test_formatters.py +++ b/IPython/core/tests/test_formatters.py @@ -103,7 +103,7 @@ def set_fp(p): def test_for_type(): f = PlainTextFormatter() - + # initial return, None assert f.for_type(C, foo_printer) is None # no func queries @@ -116,9 +116,9 @@ def test_for_type(): def test_for_type_string(): f = PlainTextFormatter() - + type_str = '%s.%s' % (C.__module__, 'C') - + # initial return, None assert f.for_type(type_str, foo_printer) is None # no func queries @@ -130,9 +130,9 @@ def test_for_type_string(): def test_for_type_by_name(): f = PlainTextFormatter() - + mod = C.__module__ - + # initial return, None assert f.for_type_by_name(mod, "C", foo_printer) is None # no func queries @@ -146,7 +146,7 @@ def test_for_type_by_name(): def test_lookup(): f = PlainTextFormatter() - + f.for_type(C, foo_printer) assert f.lookup(C()) is foo_printer with pytest.raises(KeyError): @@ -155,7 +155,7 @@ def test_lookup(): def test_lookup_string(): f = PlainTextFormatter() type_str = '%s.%s' % (C.__module__, 'C') - + f.for_type(type_str, foo_printer) assert f.lookup(C()) is foo_printer # should move from deferred to imported dict @@ -173,16 +173,16 @@ def test_lookup_by_type_string(): f = PlainTextFormatter() type_str = '%s.%s' % (C.__module__, 'C') f.for_type(type_str, foo_printer) - + # verify insertion assert _mod_name_key(C) in f.deferred_printers assert C not in f.type_printers - + assert f.lookup_by_type(type_str) is foo_printer # lookup by string doesn't cause import assert _mod_name_key(C) in f.deferred_printers assert C not in f.type_printers - + assert f.lookup_by_type(C) is foo_printer # should move from deferred to imported dict assert _mod_name_key(C) not in f.deferred_printers @@ -220,10 +220,10 @@ def test_pop(): def test_pop_string(): f = PlainTextFormatter() type_str = '%s.%s' % (C.__module__, 'C') - + with pytest.raises(KeyError): f.pop(type_str) - + f.for_type(type_str, foo_printer) f.pop(type_str) with pytest.raises(KeyError): @@ -238,7 +238,7 @@ def test_pop_string(): with pytest.raises(KeyError): f.pop(type_str) assert f.pop(type_str, None) is None - + def test_error_method(): f = HTMLFormatter() @@ -341,14 +341,14 @@ def __getattr__(self, key): assert text_hat._repr_html_ == "_repr_html_" with capture_output() as captured: result = f(text_hat) - + assert result is None assert "FormatterWarning" not in captured.stderr class CallableMagicHat(object): def __getattr__(self, key): return lambda : key - + call_hat = CallableMagicHat() with capture_output() as captured: result = f(call_hat) @@ -358,11 +358,11 @@ def __getattr__(self, key): class BadReprArgs(object): def _repr_html_(self, extra, args): return "html" - + bad = BadReprArgs() with capture_output() as captured: result = f(bad) - + assert result is None assert "FormatterWarning" not in captured.stderr @@ -406,13 +406,13 @@ def _ipython_display_(self): class NotSelfDisplaying(object): def __repr__(self): return "NotSelfDisplaying" - + def _ipython_display_(self): raise NotImplementedError - + save_enabled = f.ipython_display_formatter.enabled f.ipython_display_formatter.enabled = True - + yes = SelfDisplaying() no = NotSelfDisplaying() @@ -444,7 +444,7 @@ def _repr_png_(self): return 'should-be-overwritten' def _repr_html_(self): return '<b>hi!</b>' - + f = get_ipython().display_formatter html_f = f.formatters['text/html'] save_enabled = html_f.enabled @@ -507,7 +507,7 @@ def _repr_mimebundle_(self, include=None, exclude=None): } } return (data, metadata) - + f = get_ipython().display_formatter obj = HasReprMimeMeta() d, md = f.format(obj) @@ -529,3 +529,18 @@ def _repr_mimebundle_(self, include=None, exclude=None): obj = BadReprMime() d, md = f.format(obj) assert "text/plain" in d + + +def test_custom_repr_namedtuple_partialmethod(): + from functools import partialmethod + from typing import NamedTuple + + class Foo(NamedTuple): + ... + + Foo.__repr__ = partialmethod(lambda obj: "Hello World") + foo = Foo() + + f = PlainTextFormatter() + assert f.pprint + assert f(foo) == "Hello World"
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
8.25
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-json-report" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.10", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==1.0.0 asttokens==3.0.0 babel==2.17.0 certifi==2025.1.31 charset-normalizer==3.4.1 comm==0.2.2 contourpy==1.3.1 coverage==7.8.0 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 docrepr==0.2.0 docutils==0.21.2 exceptiongroup==1.2.2 executing==2.2.0 fonttools==4.56.0 idna==3.10 imagesize==1.4.1 iniconfig==2.1.0 intersphinx_registry==0.2501.23 ipykernel==6.29.5 -e git+https://github.com/ipython/ipython.git@1454013b8b615ce75d30d38b7710e3fccca16263#egg=ipython jedi==0.19.2 Jinja2==3.1.6 jupyter_client==8.6.3 jupyter_core==5.7.2 kiwisolver==1.4.8 MarkupSafe==3.0.2 matplotlib==3.10.1 matplotlib-inline==0.1.7 nest-asyncio==1.6.0 numpy==2.2.4 packaging==24.2 parso==0.8.4 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 prompt_toolkit==3.0.50 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 Pygments==2.19.1 pyparsing==3.2.3 pytest==8.3.5 pytest-asyncio==0.21.2 pytest-cov==6.0.0 pytest-json-report==1.5.0 pytest-metadata==3.1.1 python-dateutil==2.9.0.post0 pyzmq==26.3.0 requests==2.32.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==8.1.3 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 stack-data==0.6.3 testpath==0.6.0 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 typing_extensions==4.13.0 urllib3==2.3.0 wcwidth==0.2.13
name: ipython channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py310h06a4308_0 - python=3.10.16=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py310h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py310h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==1.0.0 - asttokens==3.0.0 - babel==2.17.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - comm==0.2.2 - contourpy==1.3.1 - coverage==7.8.0 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - docrepr==0.2.0 - docutils==0.21.2 - exceptiongroup==1.2.2 - executing==2.2.0 - fonttools==4.56.0 - idna==3.10 - imagesize==1.4.1 - iniconfig==2.1.0 - intersphinx-registry==0.2501.23 - ipykernel==6.29.5 - ipython==8.26.0.dev0 - jedi==0.19.2 - jinja2==3.1.6 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - kiwisolver==1.4.8 - markupsafe==3.0.2 - matplotlib==3.10.1 - matplotlib-inline==0.1.7 - nest-asyncio==1.6.0 - numpy==2.2.4 - packaging==24.2 - parso==0.8.4 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - prompt-toolkit==3.0.50 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pygments==2.19.1 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-asyncio==0.21.2 - pytest-cov==6.0.0 - pytest-json-report==1.5.0 - pytest-metadata==3.1.1 - python-dateutil==2.9.0.post0 - pyzmq==26.3.0 - requests==2.32.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==8.1.3 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - stack-data==0.6.3 - testpath==0.6.0 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - typing-extensions==4.13.0 - urllib3==2.3.0 - wcwidth==0.2.13 prefix: /opt/conda/envs/ipython
[ "IPython/core/tests/test_formatters.py::test_custom_repr_namedtuple_partialmethod" ]
[]
[ "IPython/core/tests/test_formatters.py::test_pretty", "IPython/core/tests/test_formatters.py::test_deferred", "IPython/core/tests/test_formatters.py::test_precision", "IPython/core/tests/test_formatters.py::test_bad_precision", "IPython/core/tests/test_formatters.py::test_for_type", "IPython/core/tests/test_formatters.py::test_for_type_string", "IPython/core/tests/test_formatters.py::test_for_type_by_name", "IPython/core/tests/test_formatters.py::test_lookup", "IPython/core/tests/test_formatters.py::test_lookup_string", "IPython/core/tests/test_formatters.py::test_lookup_by_type", "IPython/core/tests/test_formatters.py::test_lookup_by_type_string", "IPython/core/tests/test_formatters.py::test_in_formatter", "IPython/core/tests/test_formatters.py::test_string_in_formatter", "IPython/core/tests/test_formatters.py::test_pop", "IPython/core/tests/test_formatters.py::test_pop_string", "IPython/core/tests/test_formatters.py::test_error_method", "IPython/core/tests/test_formatters.py::test_nowarn_notimplemented", "IPython/core/tests/test_formatters.py::test_warn_error_for_type", "IPython/core/tests/test_formatters.py::test_error_pretty_method", "IPython/core/tests/test_formatters.py::test_bad_repr_traceback", "IPython/core/tests/test_formatters.py::test_pdf_formatter", "IPython/core/tests/test_formatters.py::test_print_method_bound", "IPython/core/tests/test_formatters.py::test_print_method_weird", "IPython/core/tests/test_formatters.py::test_format_config", "IPython/core/tests/test_formatters.py::test_pretty_max_seq_length", "IPython/core/tests/test_formatters.py::test_ipython_display_formatter", "IPython/core/tests/test_formatters.py::test_repr_mime", "IPython/core/tests/test_formatters.py::test_pass_correct_include_exclude", "IPython/core/tests/test_formatters.py::test_repr_mime_meta", "IPython/core/tests/test_formatters.py::test_repr_mime_failure" ]
[]
BSD 3-Clause "New" or "Revised" License
18,736
263
[ "IPython/lib/pretty.py" ]
pysal__momepy-622
555c51e73c958c42a36c7899d44b97036afe6b85
2024-06-20 12:34:13
f1965cccd48759faf6a2a37739bda310d851124d
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/pysal/momepy/pull/622?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pysal) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 97.7%. Comparing base [(`4037c70`)](https://app.codecov.io/gh/pysal/momepy/commit/4037c703ae35c0258939c4a2f326dbf08538bc20?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pysal) to head [(`efbb4d5`)](https://app.codecov.io/gh/pysal/momepy/commit/efbb4d506108c97e70314c78ae0c48da063f4ca7?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pysal). > Report is 58 commits behind head on main. <details><summary>Additional details and impacted files</summary> [![Impacted file tree graph](https://app.codecov.io/gh/pysal/momepy/pull/622/graphs/tree.svg?width=650&height=150&src=pr&token=VNn0WR5JWT&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pysal)](https://app.codecov.io/gh/pysal/momepy/pull/622?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pysal) ```diff @@ Coverage Diff @@ ## main #622 +/- ## ======================================= + Coverage 97.4% 97.7% +0.3% ======================================= Files 26 39 +13 Lines 4328 6226 +1898 ======================================= + Hits 4214 6082 +1868 - Misses 114 144 +30 ``` | [Files](https://app.codecov.io/gh/pysal/momepy/pull/622?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pysal) | Coverage Δ | | |---|---|---| | [momepy/functional/tests/test\_multi\_index.py](https://app.codecov.io/gh/pysal/momepy/pull/622?src=pr&el=tree&filepath=momepy%2Ffunctional%2Ftests%2Ftest_multi_index.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pysal#diff-bW9tZXB5L2Z1bmN0aW9uYWwvdGVzdHMvdGVzdF9tdWx0aV9pbmRleC5weQ==) | `100.0% <100.0%> (ø)` | | ... and [1 file with indirect coverage changes](https://app.codecov.io/gh/pysal/momepy/pull/622/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pysal) </details>
diff --git a/momepy/functional/_elements.py b/momepy/functional/_elements.py index 1b6b2f3..a30def3 100644 --- a/momepy/functional/_elements.py +++ b/momepy/functional/_elements.py @@ -10,7 +10,7 @@ from joblib import Parallel, delayed from libpysal.cg import voronoi_frames from libpysal.graph import Graph from packaging.version import Version -from pandas import Series +from pandas import MultiIndex, Series GPD_GE_013 = Version(gpd.__version__) >= Version("0.13.0") GPD_GE_10 = Version(gpd.__version__) >= Version("1.0dev") @@ -103,6 +103,12 @@ def morphological_tessellation( 4 POLYGON ((1603084.231 6464104.386, 1603083.773... """ + + if isinstance(geometry.index, MultiIndex): + raise ValueError( + "MultiIndex is not supported in `momepy.morphological_tessellation`." + ) + if isinstance(clip, GeoSeries | GeoDataFrame): clip = clip.union_all() if GPD_GE_10 else clip.unary_union @@ -218,6 +224,11 @@ def enclosed_tessellation( 126 POLYGON ((1603528.593 6464221.033, 1603527.796... 0 """ + if isinstance(geometry.index, MultiIndex): + raise ValueError( + "MultiIndex is not supported in `momepy.enclosed_tessellation`." + ) + # convert to GeoDataFrame and add position (we will need it later) enclosures = enclosures.geometry.to_frame() enclosures["position"] = range(len(enclosures)) @@ -360,6 +371,12 @@ def verify_tessellation(tessellation, geometry): >>> excluded, multipolygons = momepy.verify_tessellation(tessellation, buildings) """ + + if isinstance(geometry.index, MultiIndex) or isinstance( + tessellation.index, MultiIndex + ): + raise ValueError("MultiIndex is not supported in `momepy.verify_tessellation`.") + # check against input layer ids_original = geometry.index ids_generated = tessellation.index @@ -397,7 +414,7 @@ def get_nearest_street( buildings: GeoSeries | GeoDataFrame, streets: GeoSeries | GeoDataFrame, max_distance: float | None = None, -) -> np.ndarray: +) -> Series: """Identify the nearest street for each building. Parameters @@ -429,30 +446,26 @@ def get_nearest_street( Get street index. >>> momepy.get_nearest_street(buildings, streets) - array([ 0., 33., 10., 8., 8., 8., 8., 8., 33., 11., 11., 28., 28., - 28., 28., 28., 16., 8., 8., 8., 8., 8., 8., 11., 28., 28., - 28., 8., 8., 8., 8., 16., 28., 28., 28., 28., 28., 1., 21., - 21., 21., 21., 21., 12., 12., 12., 26., 26., 26., 19., 19., 19., - 19., 21., 21., 21., 32., 32., 32., 32., 32., 26., 26., 5., 5., - 5., 5., 2., 2., 2., 2., 2., 2., 25., 25., 25., 19., 19., - 19., 19., 5., 25., 6., 33., 33., 33., 33., 33., 33., 33., 34., - 34., 34., 34., 34., 34., 34., 34., 6., 6., 6., 6., 6., 34., - 33., 6., 34., 34., 34., 34., 0., 0., 0., 0., 0., 0., 34., - 34., 34., 0., 0., 14., 2., 2., 25., 24., 2., 2., 2., 2., - 24., 24., 24., 24., 24., 28., 12., 28., 34., 34., 32., 21., 16., - 19.], dtype=float32) + 0 0.0 + 1 33.0 + 2 10.0 + 3 8.0 + 4 8.0 + ... + 139 34.0 + 140 32.0 + 141 21.0 + 142 16.0 + 143 19.0 + Length: 144, dtype: float64 """ blg_idx, str_idx = streets.sindex.nearest( buildings.geometry, return_all=False, max_distance=max_distance ) - if streets.index.dtype == "object": - ids = np.empty(len(buildings), dtype=object) - else: - ids = np.empty(len(buildings), dtype=np.float32) - ids[:] = np.nan + ids = pd.Series(None, index=buildings.index, dtype=streets.index.dtype) - ids[blg_idx] = streets.index[str_idx] + ids.iloc[blg_idx] = streets.index[str_idx] return ids @@ -522,6 +535,15 @@ def get_nearest_node( 143 22.0 Length: 144, dtype: float64 """ + + if ( + isinstance(buildings.index, MultiIndex) + or isinstance(nearest_edge.index, MultiIndex) + or isinstance(nodes.index, MultiIndex) + or isinstance(edges.index, MultiIndex) + ): + raise ValueError("MultiIndex is not supported in `momepy.get_nearest_node`.") + # treat possibly missing edge index a = np.empty(len(buildings)) na_mask = np.isnan(nearest_edge) @@ -606,6 +628,12 @@ def generate_blocks( >>> tessellation["block_id"] = tessellation_id """ + if ( + isinstance(buildings.index, MultiIndex) + or isinstance(tessellation.index, MultiIndex) + or isinstance(edges.index, MultiIndex) + ): + raise ValueError("MultiIndex is not supported in `momepy.generate_blocks`.") id_name: str = "bID" # slice the tessellations by the street network diff --git a/momepy/functional/_shape.py b/momepy/functional/_shape.py index 8e1d734..a4de964 100644 --- a/momepy/functional/_shape.py +++ b/momepy/functional/_shape.py @@ -4,7 +4,7 @@ import shapely from geopandas import GeoDataFrame, GeoSeries from numpy.typing import NDArray from packaging.version import Version -from pandas import DataFrame, Series +from pandas import DataFrame, MultiIndex, Series from momepy.functional import _dimension @@ -724,6 +724,10 @@ def centroid_corner_distance( "momepy.centroid_corner_distance requires geopandas 0.13 or later. " ) + result_index = geometry.index + if isinstance(geometry.index, MultiIndex): + geometry = geometry.reset_index(drop=True) + def _ccd(points: DataFrame, eps: float) -> Series: centroid = points.values[0, 2:] pts = points.values[:-1, :2] @@ -738,7 +742,7 @@ def centroid_corner_distance( coords = geometry.exterior.get_coordinates(index_parts=False) coords[["cent_x", "cent_y"]] = geometry.centroid.get_coordinates(index_parts=False) ccd = coords.groupby(level=0).apply(_ccd, eps=eps) - ccd.index = geometry.index + ccd.index = result_index return ccd
BUG: verify handling of MultiIndex It seems that when your GeoDataFrame is using MultiIindex, it does affect some parts of `momepy` and will likely break when using Graph. We should test and verify that it behaves as we want, both here and in libpysal. In some cases, raising may be the best option but if we can support it, it is better. I don't think that there's scope in supporting MultiIndex in Graph so it may need to be checked only in functions that do not use graphs.
pysal/momepy
diff --git a/momepy/functional/tests/test_elements.py b/momepy/functional/tests/test_elements.py index f6b0b26..1fc2215 100644 --- a/momepy/functional/tests/test_elements.py +++ b/momepy/functional/tests/test_elements.py @@ -222,7 +222,7 @@ class TestElements: streets.index = streets.index.astype(str) nearest = mm.get_nearest_street(self.df_buildings, streets, 10) - assert (nearest == None).sum() == 137 # noqa: E711 + assert pd.isna(nearest).sum() == 137 # noqa: E711 def test_get_nearest_node(self): nodes, edges = mm.nx_to_gdf(mm.gdf_to_nx(self.df_streets)) @@ -332,6 +332,37 @@ class TestElements: else: assert len(blocks.sindex.query_bulk(blocks.geometry, "overlaps")[0]) == 0 + def test_multi_index(self): + buildings = self.df_buildings.set_index(["uID", "uID"]) + with pytest.raises( + ValueError, + match="MultiIndex is not supported in `momepy.morphological_tessellation`.", + ): + mm.morphological_tessellation(buildings) + with pytest.raises( + ValueError, + match="MultiIndex is not supported in `momepy.enclosed_tessellation`.", + ): + mm.enclosed_tessellation(buildings, self.enclosures) + with pytest.raises( + ValueError, + match="MultiIndex is not supported in `momepy.verify_tessellation`.", + ): + mm.verify_tessellation(buildings, self.enclosures) + + with pytest.raises( + ValueError, + match="MultiIndex is not supported in `momepy.get_nearest_node`.", + ): + mm.get_nearest_node( + buildings, self.enclosures, self.enclosures, self.enclosures + ) + + with pytest.raises( + ValueError, match="MultiIndex is not supported in `momepy.generate_blocks`" + ): + mm.generate_blocks(buildings, self.enclosures, self.enclosures) + def test_tess_single_building_edge_case(self): tessellations = mm.enclosed_tessellation( self.df_buildings, self.enclosures.geometry, n_jobs=-1
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
0.8
{ "env_vars": null, "env_yml_path": [ "environment.yml" ], "install": "pip install -e .[plus]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "environment.yml", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.10", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine @ file:///home/conda/feedstock_root/build_artifacts/affine_1733762038348/work anyio @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_anyio_1742243108/work argon2-cffi @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi_1733311059102/work argon2-cffi-bindings @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi-bindings_1725356557095/work arrow @ file:///home/conda/feedstock_root/build_artifacts/arrow_1733584251875/work asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1733250440834/work async-lru @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_async-lru_1742153708/work attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1741918516150/work babel @ file:///home/conda/feedstock_root/build_artifacts/babel_1738490167835/work beautifulsoup4 @ file:///home/conda/feedstock_root/build_artifacts/beautifulsoup4_1738740337718/work bleach @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_bleach_1737382993/work branca @ file:///home/conda/feedstock_root/build_artifacts/branca_1734433375112/work Brotli @ file:///home/conda/feedstock_root/build_artifacts/brotli-split_1725267488082/work cached-property @ file:///home/conda/feedstock_root/build_artifacts/cached_property_1615209429212/work certifi @ file:///home/conda/feedstock_root/build_artifacts/certifi_1739515848642/work/certifi cffi @ file:///home/conda/feedstock_root/build_artifacts/cffi_1725560520483/work charset-normalizer @ file:///home/conda/feedstock_root/build_artifacts/charset-normalizer_1735929714516/work click @ file:///home/conda/feedstock_root/build_artifacts/click_1734858813237/work click-plugins @ file:///home/conda/feedstock_root/build_artifacts/click-plugins_1733731077999/work cligj @ file:///home/conda/feedstock_root/build_artifacts/cligj_1733749956636/work colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1733218098505/work comm @ file:///home/conda/feedstock_root/build_artifacts/comm_1733502965406/work contourpy @ file:///home/conda/feedstock_root/build_artifacts/contourpy_1731428322366/work coverage==7.8.0 cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1733332471406/work debugpy @ file:///home/conda/feedstock_root/build_artifacts/debugpy_1741148395697/work decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1740384970518/work defusedxml @ file:///home/conda/feedstock_root/build_artifacts/defusedxml_1615232257335/work esda @ file:///home/conda/feedstock_root/build_artifacts/esda_1738873094265/work exceptiongroup @ file:///home/conda/feedstock_root/build_artifacts/exceptiongroup_1733208806608/work executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1733569351617/work fastjsonschema @ file:///home/conda/feedstock_root/build_artifacts/python-fastjsonschema_1733235979760/work/dist folium @ file:///home/conda/feedstock_root/build_artifacts/folium_1740766619747/work fonttools @ file:///home/conda/feedstock_root/build_artifacts/fonttools_1738940303262/work fqdn @ file:///home/conda/feedstock_root/build_artifacts/fqdn_1733327382592/work/dist geopandas @ file:///home/conda/feedstock_root/build_artifacts/geopandas_1734346029138/work h11 @ file:///home/conda/feedstock_root/build_artifacts/h11_1733327467879/work h2 @ file:///home/conda/feedstock_root/build_artifacts/h2_1738578511449/work hpack @ file:///home/conda/feedstock_root/build_artifacts/hpack_1737618293087/work httpcore @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_httpcore_1731707562/work httpx @ file:///home/conda/feedstock_root/build_artifacts/httpx_1733663348460/work hyperframe @ file:///home/conda/feedstock_root/build_artifacts/hyperframe_1737618333194/work idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1733211830134/work importlib_metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1737420181517/work importlib_resources @ file:///home/conda/feedstock_root/build_artifacts/importlib_resources_1736252299705/work inequality @ file:///home/conda/feedstock_root/build_artifacts/inequality_1738179721853/work iniconfig==2.1.0 ipykernel @ file:///home/conda/feedstock_root/build_artifacts/ipykernel_1719845459717/work ipython @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_ipython_1741457802/work ipywidgets @ file:///home/conda/feedstock_root/build_artifacts/ipywidgets_1733493556527/work isoduration @ file:///home/conda/feedstock_root/build_artifacts/isoduration_1733493628631/work/dist jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1733300866624/work Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1741263328855/work joblib @ file:///home/conda/feedstock_root/build_artifacts/joblib_1733736026804/work json5 @ file:///home/conda/feedstock_root/build_artifacts/json5_1733272076743/work jsonpointer @ file:///home/conda/feedstock_root/build_artifacts/jsonpointer_1725302897999/work jsonschema @ file:///home/conda/feedstock_root/build_artifacts/jsonschema_1733472696581/work jsonschema-specifications @ file:///tmp/tmpk0f344m9/src jupyter @ file:///home/conda/feedstock_root/build_artifacts/jupyter_1733818543322/work jupyter-console @ file:///home/conda/feedstock_root/build_artifacts/jupyter_console_1733817997778/work jupyter-events @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_jupyter_events_1738765986/work jupyter-lsp @ file:///home/conda/feedstock_root/build_artifacts/jupyter-lsp-meta_1733492907176/work/jupyter-lsp jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1733440914442/work jupyter_core @ file:///home/conda/feedstock_root/build_artifacts/jupyter_core_1727163409502/work jupyter_server @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_1734702637701/work jupyter_server_terminals @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_terminals_1733427956852/work jupyterlab @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_1741964057182/work jupyterlab_pygments @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_pygments_1733328101776/work jupyterlab_server @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_server_1733599573484/work jupyterlab_widgets @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_widgets_1733428046021/work kiwisolver @ file:///home/conda/feedstock_root/build_artifacts/kiwisolver_1725459213453/work libpysal @ file:///home/conda/feedstock_root/build_artifacts/libpysal_1734433669370/work llvmlite==0.44.0 mapclassify @ file:///home/conda/feedstock_root/build_artifacts/mapclassify_1733731066416/work MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1733219680183/work matplotlib==3.10.1 matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1733416936468/work mistune @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_mistune_1742402716/work -e git+https://github.com/pysal/momepy.git@555c51e73c958c42a36c7899d44b97036afe6b85#egg=momepy munkres==1.1.4 nbclient @ file:///home/conda/feedstock_root/build_artifacts/nbclient_1734628800805/work nbconvert @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_nbconvert-core_1738067871/work nbformat @ file:///home/conda/feedstock_root/build_artifacts/nbformat_1733402752141/work nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1733325553580/work networkx @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_networkx_1731521053/work notebook @ file:///home/conda/feedstock_root/build_artifacts/notebook_1741968175534/work notebook_shim @ file:///home/conda/feedstock_root/build_artifacts/notebook-shim_1733408315203/work numba @ file:///home/conda/feedstock_root/build_artifacts/numba_1739224673889/work numpy @ file:///home/conda/feedstock_root/build_artifacts/numpy_1730588026426/work/dist/numpy-2.1.3-cp310-cp310-linux_x86_64.whl#sha256=589b636d43e6856ab6eab6a1a707eef18871d272782f92400ea890827e0bf64b osmnx @ file:///home/conda/feedstock_root/build_artifacts/osmnx_1743172660704/work overrides @ file:///home/conda/feedstock_root/build_artifacts/overrides_1734587627321/work packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1733203243479/work pandas @ file:///home/conda/feedstock_root/build_artifacts/pandas_1726878398774/work pandocfilters @ file:///home/conda/feedstock_root/build_artifacts/pandocfilters_1631603243851/work parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1733271261340/work pexpect @ file:///home/conda/feedstock_root/build_artifacts/pexpect_1733301927746/work pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1733327343728/work pillow @ file:///home/conda/feedstock_root/build_artifacts/pillow_1735929693232/work pkgutil_resolve_name @ file:///home/conda/feedstock_root/build_artifacts/pkgutil-resolve-name_1733344503739/work platformdirs @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_platformdirs_1742485085/work pluggy==1.5.0 prometheus_client @ file:///home/conda/feedstock_root/build_artifacts/prometheus_client_1733327310477/work prompt_toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1737453357274/work psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1740663128538/work ptyprocess @ file:///home/conda/feedstock_root/build_artifacts/ptyprocess_1733302279685/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl#sha256=92c32ff62b5fd8cf325bec5ab90d7be3d2a8ca8c8a3813ff487a8d2002630d1f pure_eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1733569405015/work pycparser @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_pycparser_1733195786/work Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1736243443484/work pyogrio @ file:///home/conda/feedstock_root/build_artifacts/pyogrio_1732013380254/work pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1743089729650/work pyproj @ file:///home/conda/feedstock_root/build_artifacts/pyproj_1742323235700/work PySide6==6.8.3 PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1733217236728/work pytest==8.3.5 pytest-cov==6.0.0 python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1733215673016/work python-json-logger @ file:///home/conda/feedstock_root/build_artifacts/python-json-logger_1677079630776/work pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1706886791323/work PyYAML @ file:///home/conda/feedstock_root/build_artifacts/pyyaml_1737454647378/work pyzmq @ file:///home/conda/feedstock_root/build_artifacts/pyzmq_1741805149626/work rasterio @ file:///home/conda/feedstock_root/build_artifacts/rasterio_1742428573226/work referencing @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_referencing_1737836872/work requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1733217035951/work rfc3339_validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3339-validator_1733599910982/work rfc3986-validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3986-validator_1598024191506/work rio-vrt @ file:///home/conda/feedstock_root/build_artifacts/rio-vrt_1734898616182/work rpds-py @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_rpds-py_1743037662/work scikit-learn @ file:///home/conda/feedstock_root/build_artifacts/scikit-learn_1736496756180/work/dist/scikit_learn-1.6.1-cp310-cp310-linux_x86_64.whl#sha256=8b3481924bda36bf9a85c5f500f48e43e1178ead014b2d2ecf10f7b9b49935b4 scipy @ file:///home/conda/feedstock_root/build_artifacts/scipy-split_1739790642651/work/dist/scipy-1.15.2-cp310-cp310-linux_x86_64.whl#sha256=9e52bad6c3294d1a5b04a13632118ca2157130603c6c018c2d710162b223b27e Send2Trash @ file:///home/conda/feedstock_root/build_artifacts/send2trash_1733322040660/work shapely @ file:///home/conda/feedstock_root/build_artifacts/shapely_1741166961581/work shiboken6==6.8.3 six @ file:///home/conda/feedstock_root/build_artifacts/six_1733380938961/work sniffio @ file:///home/conda/feedstock_root/build_artifacts/sniffio_1733244044561/work snuggs @ file:///home/conda/feedstock_root/build_artifacts/snuggs_1733818638588/work soupsieve @ file:///home/conda/feedstock_root/build_artifacts/soupsieve_1693929250441/work stack_data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1733569443808/work terminado @ file:///home/conda/feedstock_root/build_artifacts/terminado_1710262609923/work threadpoolctl @ file:///home/conda/feedstock_root/build_artifacts/threadpoolctl_1741878222898/work tinycss2 @ file:///home/conda/feedstock_root/build_artifacts/tinycss2_1729802851396/work tomli @ file:///home/conda/feedstock_root/build_artifacts/tomli_1733256695513/work tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1732615898999/work tqdm @ file:///home/conda/feedstock_root/build_artifacts/tqdm_1735661334605/work traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1733367359838/work types-python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/types-python-dateutil_1733612335562/work typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_typing_extensions_1743201626/work typing_utils @ file:///home/conda/feedstock_root/build_artifacts/typing_utils_1733331286120/work tzdata @ file:///home/conda/feedstock_root/build_artifacts/python-tzdata_1742745135198/work unicodedata2 @ file:///home/conda/feedstock_root/build_artifacts/unicodedata2_1736692496989/work uri-template @ file:///home/conda/feedstock_root/build_artifacts/uri-template_1733323593477/work/dist urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1734859416348/work wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1733231326287/work webcolors @ file:///home/conda/feedstock_root/build_artifacts/webcolors_1733359735138/work webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1733236011802/work websocket-client @ file:///home/conda/feedstock_root/build_artifacts/websocket-client_1733157342724/work widgetsnbextension @ file:///home/conda/feedstock_root/build_artifacts/widgetsnbextension_1733128559935/work xyzservices @ file:///home/conda/feedstock_root/build_artifacts/xyzservices_1737234886776/work zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1732827521216/work zstandard==0.23.0
name: momepy channels: - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=conda_forge - _openmp_mutex=4.5=2_gnu - affine=2.4.0=pyhd8ed1ab_1 - alsa-lib=1.2.13=hb9d3cd8_0 - anyio=4.9.0=pyh29332c3_0 - aom=3.9.1=hac33072_0 - argon2-cffi=23.1.0=pyhd8ed1ab_1 - argon2-cffi-bindings=21.2.0=py310ha75aee5_5 - arrow=1.3.0=pyhd8ed1ab_1 - asttokens=3.0.0=pyhd8ed1ab_1 - async-lru=2.0.5=pyh29332c3_0 - attrs=25.3.0=pyh71513ae_0 - babel=2.17.0=pyhd8ed1ab_0 - beautifulsoup4=4.13.3=pyha770c72_0 - bleach=6.2.0=pyh29332c3_4 - bleach-with-css=6.2.0=h82add2a_4 - blosc=1.21.6=he440d0b_1 - branca=0.8.1=pyhd8ed1ab_0 - brotli=1.1.0=hb9d3cd8_2 - brotli-bin=1.1.0=hb9d3cd8_2 - brotli-python=1.1.0=py310hf71b8c6_2 - bzip2=1.0.8=h4bc722e_7 - c-ares=1.34.4=hb9d3cd8_0 - ca-certificates=2025.1.31=hbcca054_0 - cached-property=1.5.2=hd8ed1ab_1 - cached_property=1.5.2=pyha770c72_1 - cairo=1.18.4=h3394656_0 - certifi=2025.1.31=pyhd8ed1ab_0 - cffi=1.17.1=py310h8deb56e_0 - charset-normalizer=3.4.1=pyhd8ed1ab_0 - click=8.1.8=pyh707e725_0 - click-plugins=1.1.1=pyhd8ed1ab_1 - cligj=0.7.2=pyhd8ed1ab_2 - colorama=0.4.6=pyhd8ed1ab_1 - comm=0.2.2=pyhd8ed1ab_1 - contourpy=1.3.1=py310h3788b33_0 - cycler=0.12.1=pyhd8ed1ab_1 - cyrus-sasl=2.1.27=h54b06d7_7 - dav1d=1.2.1=hd590300_0 - dbus=1.13.6=h5008d03_3 - debugpy=1.8.13=py310hf71b8c6_0 - decorator=5.2.1=pyhd8ed1ab_0 - defusedxml=0.7.1=pyhd8ed1ab_0 - double-conversion=3.3.1=h5888daf_0 - esda=2.7.0=pyhd8ed1ab_0 - exceptiongroup=1.2.2=pyhd8ed1ab_1 - executing=2.1.0=pyhd8ed1ab_1 - expat=2.6.4=h5888daf_0 - folium=0.19.5=pyhd8ed1ab_0 - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 - font-ttf-inconsolata=3.000=h77eed37_0 - font-ttf-source-code-pro=2.038=h77eed37_0 - font-ttf-ubuntu=0.83=h77eed37_3 - fontconfig=2.15.0=h7e30c49_1 - fonts-conda-ecosystem=1=0 - fonts-conda-forge=1=0 - fonttools=4.56.0=py310h89163eb_0 - fqdn=1.5.1=pyhd8ed1ab_1 - freetype=2.13.3=h48d6fc4_0 - freexl=2.0.0=h9dce30a_2 - geopandas=1.0.1=pyhd8ed1ab_3 - geopandas-base=1.0.1=pyha770c72_3 - geos=3.13.1=h97f6797_0 - geotiff=1.7.4=h239500f_2 - giflib=5.2.2=hd590300_0 - graphite2=1.3.13=h59595ed_1003 - gtest=1.16.0=h84d6215_0 - h11=0.14.0=pyhd8ed1ab_1 - h2=4.2.0=pyhd8ed1ab_0 - harfbuzz=11.0.0=h76408a6_0 - hpack=4.1.0=pyhd8ed1ab_0 - httpcore=1.0.7=pyh29332c3_1 - httpx=0.28.1=pyhd8ed1ab_0 - hyperframe=6.1.0=pyhd8ed1ab_0 - icu=75.1=he02047a_0 - idna=3.10=pyhd8ed1ab_1 - importlib-metadata=8.6.1=pyha770c72_0 - importlib_resources=6.5.2=pyhd8ed1ab_0 - inequality=1.1.1=pyhd8ed1ab_0 - ipykernel=6.29.5=pyh3099207_0 - ipython=8.34.0=pyh907856f_0 - ipywidgets=8.1.5=pyhd8ed1ab_1 - isoduration=20.11.0=pyhd8ed1ab_1 - jedi=0.19.2=pyhd8ed1ab_1 - jinja2=3.1.6=pyhd8ed1ab_0 - joblib=1.4.2=pyhd8ed1ab_1 - json-c=0.18=h6688a6e_0 - json5=0.10.0=pyhd8ed1ab_1 - jsonpointer=3.0.0=py310hff52083_1 - jsonschema=4.23.0=pyhd8ed1ab_1 - jsonschema-specifications=2024.10.1=pyhd8ed1ab_1 - jsonschema-with-format-nongpl=4.23.0=hd8ed1ab_1 - jupyter=1.1.1=pyhd8ed1ab_1 - jupyter-lsp=2.2.5=pyhd8ed1ab_1 - jupyter_client=8.6.3=pyhd8ed1ab_1 - jupyter_console=6.6.3=pyhd8ed1ab_1 - jupyter_core=5.7.2=pyh31011fe_1 - jupyter_events=0.12.0=pyh29332c3_0 - jupyter_server=2.15.0=pyhd8ed1ab_0 - jupyter_server_terminals=0.5.3=pyhd8ed1ab_1 - jupyterlab=4.3.6=pyhd8ed1ab_0 - jupyterlab_pygments=0.3.0=pyhd8ed1ab_2 - jupyterlab_server=2.27.3=pyhd8ed1ab_1 - jupyterlab_widgets=3.0.13=pyhd8ed1ab_1 - keyutils=1.6.1=h166bdaf_0 - kiwisolver=1.4.7=py310h3788b33_0 - krb5=1.21.3=h659f571_0 - lcms2=2.17=h717163a_0 - ld_impl_linux-64=2.43=h712a8e2_4 - lerc=4.0.0=h27087fc_0 - libarchive=3.7.7=h4585015_3 - libavif16=1.2.1=hbb36593_2 - libblas=3.9.0=31_h59b9bed_openblas - libbrotlicommon=1.1.0=hb9d3cd8_2 - libbrotlidec=1.1.0=hb9d3cd8_2 - libbrotlienc=1.1.0=hb9d3cd8_2 - libcblas=3.9.0=31_he106b2a_openblas - libclang-cpp20.1=20.1.1=default_hb5137d0_0 - libclang13=20.1.1=default_h9c6a7e4_0 - libcups=2.3.3=h4637d8d_4 - libcurl=8.12.1=h332b0f4_0 - libde265=1.0.15=h00ab1b0_0 - libdeflate=1.23=h4ddbbb0_0 - libdrm=2.4.124=hb9d3cd8_0 - libedit=3.1.20250104=pl5321h7949ede_0 - libegl=1.7.0=ha4b6fd6_2 - libev=4.33=hd590300_2 - libexpat=2.6.4=h5888daf_0 - libffi=3.4.6=h2dba641_0 - libgcc=14.2.0=h767d61c_2 - libgcc-ng=14.2.0=h69a702a_2 - libgdal-core=3.10.2=hae73b24_5 - libgfortran=14.2.0=h69a702a_2 - libgfortran5=14.2.0=hf1ad2bd_2 - libgl=1.7.0=ha4b6fd6_2 - libglib=2.84.0=h2ff4ddf_0 - libglvnd=1.7.0=ha4b6fd6_2 - libglx=1.7.0=ha4b6fd6_2 - libgomp=14.2.0=h767d61c_2 - libheif=1.19.7=gpl_hc18d805_100 - libiconv=1.18=h4ce23a2_1 - libjpeg-turbo=3.0.0=hd590300_1 - libkml=1.3.0=hf539b9f_1021 - liblapack=3.9.0=31_h7ac8fdf_openblas - libllvm20=20.1.1=ha7bfdaf_0 - liblzma=5.6.4=hb9d3cd8_0 - libnghttp2=1.64.0=h161d5f1_0 - libnsl=2.0.1=hd590300_0 - libntlm=1.8=hb9d3cd8_0 - libopenblas=0.3.29=pthreads_h94d23a6_0 - libopengl=1.7.0=ha4b6fd6_2 - libpciaccess=0.18=hd590300_0 - libpng=1.6.47=h943b412_0 - libpq=17.4=h27ae623_0 - libpysal=4.12.1=pyhd8ed1ab_1 - librttopo=1.1.0=hd718a1a_18 - libsodium=1.0.20=h4ab18f5_0 - libspatialite=5.1.0=he17ca71_14 - libsqlite=3.49.1=hee588c1_2 - libssh2=1.11.1=hf672d98_0 - libstdcxx=14.2.0=h8f9b012_2 - libstdcxx-ng=14.2.0=h4852527_2 - libtiff=4.7.0=hd9ff511_3 - libuuid=2.38.1=h0b41bf4_0 - libwebp-base=1.5.0=h851e524_0 - libxcb=1.17.0=h8a09558_0 - libxcrypt=4.4.36=hd590300_1 - libxkbcommon=1.8.1=hc4a0caf_0 - libxml2=2.13.7=h8d12d68_0 - libxslt=1.1.39=h76b75d6_0 - libzlib=1.3.1=hb9d3cd8_2 - llvmlite=0.44.0=py310h1a6248f_1 - lz4-c=1.10.0=h5888daf_1 - lzo=2.10=hd590300_1001 - mapclassify=2.8.1=pyhd8ed1ab_1 - markupsafe=3.0.2=py310h89163eb_1 - matplotlib=3.10.1=py310hff52083_0 - matplotlib-base=3.10.1=py310h68603db_0 - matplotlib-inline=0.1.7=pyhd8ed1ab_1 - minizip=4.0.7=h05a5f5f_3 - mistune=3.1.3=pyh29332c3_0 - munkres=1.1.4=pyh9f0ad1d_0 - mysql-common=9.0.1=h266115a_5 - mysql-libs=9.0.1=he0572af_5 - nbclient=0.10.2=pyhd8ed1ab_0 - nbconvert-core=7.16.6=pyh29332c3_0 - nbformat=5.10.4=pyhd8ed1ab_1 - ncurses=6.5=h2d0b736_3 - nest-asyncio=1.6.0=pyhd8ed1ab_1 - networkx=3.4.2=pyh267e887_2 - notebook=7.3.3=pyhd8ed1ab_0 - notebook-shim=0.2.4=pyhd8ed1ab_1 - numba=0.61.0=py310h699fe88_1 - numpy=2.1.3=py310hd6e36ab_0 - openjpeg=2.5.3=h5fbd93e_0 - openldap=2.6.9=he970967_0 - openssl=3.4.1=h7b32b05_0 - osmnx=2.0.2=ha770c72_1 - osmnx-base=2.0.2=pyhd8ed1ab_1 - overrides=7.7.0=pyhd8ed1ab_1 - packaging=24.2=pyhd8ed1ab_2 - pandas=2.2.3=py310h5eaa309_1 - pandocfilters=1.5.0=pyhd8ed1ab_0 - parso=0.8.4=pyhd8ed1ab_1 - pcre2=10.44=hba22ea6_2 - pexpect=4.9.0=pyhd8ed1ab_1 - pickleshare=0.7.5=pyhd8ed1ab_1004 - pillow=11.1.0=py310h7e6dc6c_0 - pip=25.0.1=pyh8b19718_0 - pixman=0.44.2=h29eaf8c_0 - pkgutil-resolve-name=1.3.10=pyhd8ed1ab_2 - platformdirs=4.3.7=pyh29332c3_0 - proj=9.6.0=h0054346_0 - prometheus_client=0.21.1=pyhd8ed1ab_0 - prompt-toolkit=3.0.50=pyha770c72_0 - prompt_toolkit=3.0.50=hd8ed1ab_0 - psutil=7.0.0=py310ha75aee5_0 - pthread-stubs=0.4=hb9d3cd8_1002 - ptyprocess=0.7.0=pyhd8ed1ab_1 - pure_eval=0.2.3=pyhd8ed1ab_1 - pycparser=2.22=pyh29332c3_1 - pygments=2.19.1=pyhd8ed1ab_0 - pyogrio=0.10.0=py310h0aed7a2_1 - pyparsing=3.2.3=pyhd8ed1ab_1 - pyproj=3.7.1=py310h71d0299_1 - pyside6=6.8.3=py310hfd10a26_0 - pysocks=1.7.1=pyha55dd90_7 - python=3.10.16=he725a3c_1_cpython - python-dateutil=2.9.0.post0=pyhff2d567_1 - python-fastjsonschema=2.21.1=pyhd8ed1ab_0 - python-json-logger=2.0.7=pyhd8ed1ab_0 - python-tzdata=2025.2=pyhd8ed1ab_0 - python_abi=3.10=5_cp310 - pytz=2024.1=pyhd8ed1ab_0 - pyyaml=6.0.2=py310h89163eb_2 - pyzmq=26.3.0=py310h71f11fc_0 - qhull=2020.2=h434a139_5 - qt6-main=6.8.3=h6441bc3_1 - rasterio=1.4.3=py310hb0078ae_1 - rav1e=0.6.6=he8a937b_2 - readline=8.2=h8c095d6_2 - referencing=0.36.2=pyh29332c3_0 - requests=2.32.3=pyhd8ed1ab_1 - rfc3339-validator=0.1.4=pyhd8ed1ab_1 - rfc3986-validator=0.1.1=pyh9f0ad1d_0 - rio-vrt=0.3.1=pyhd8ed1ab_1 - rpds-py=0.24.0=py310hc1293b2_0 - scikit-learn=1.6.1=py310h27f47ee_0 - scipy=1.15.2=py310h1d65ade_0 - send2trash=1.8.3=pyh0d859eb_1 - setuptools=75.8.2=pyhff2d567_0 - shapely=2.0.7=py310h247727d_1 - six=1.17.0=pyhd8ed1ab_0 - snappy=1.2.1=h8bd8927_1 - sniffio=1.3.1=pyhd8ed1ab_1 - snuggs=1.4.7=pyhd8ed1ab_2 - soupsieve=2.5=pyhd8ed1ab_1 - sqlite=3.49.1=h9eae976_2 - stack_data=0.6.3=pyhd8ed1ab_1 - svt-av1=3.0.2=h5888daf_0 - terminado=0.18.1=pyh0d859eb_0 - threadpoolctl=3.6.0=pyhecae5ae_0 - tinycss2=1.4.0=pyhd8ed1ab_0 - tk=8.6.13=noxft_h4845f30_101 - tomli=2.2.1=pyhd8ed1ab_1 - tornado=6.4.2=py310ha75aee5_0 - tqdm=4.67.1=pyhd8ed1ab_1 - traitlets=5.14.3=pyhd8ed1ab_1 - types-python-dateutil=2.9.0.20241206=pyhd8ed1ab_0 - typing-extensions=4.13.0=h9fa5a19_1 - typing_extensions=4.13.0=pyh29332c3_1 - typing_utils=0.1.0=pyhd8ed1ab_1 - tzdata=2025b=h78e105d_0 - unicodedata2=16.0.0=py310ha75aee5_0 - uri-template=1.3.0=pyhd8ed1ab_1 - uriparser=0.9.8=hac33072_0 - urllib3=2.3.0=pyhd8ed1ab_0 - wayland=1.23.1=h3e06ad9_0 - wcwidth=0.2.13=pyhd8ed1ab_1 - webcolors=24.11.1=pyhd8ed1ab_0 - webencodings=0.5.1=pyhd8ed1ab_3 - websocket-client=1.8.0=pyhd8ed1ab_1 - wheel=0.45.1=pyhd8ed1ab_1 - widgetsnbextension=4.0.13=pyhd8ed1ab_1 - x265=3.5=h924138e_3 - xcb-util=0.4.1=hb711507_2 - xcb-util-cursor=0.1.5=hb9d3cd8_0 - xcb-util-image=0.4.0=hb711507_2 - xcb-util-keysyms=0.4.1=hb711507_0 - xcb-util-renderutil=0.3.10=hb711507_0 - xcb-util-wm=0.4.2=hb711507_0 - xerces-c=3.2.5=h988505b_2 - xkeyboard-config=2.43=hb9d3cd8_0 - xorg-libice=1.1.2=hb9d3cd8_0 - xorg-libsm=1.2.6=he73a12e_0 - xorg-libx11=1.8.12=h4f16b4b_0 - xorg-libxau=1.0.12=hb9d3cd8_0 - xorg-libxcomposite=0.4.6=hb9d3cd8_2 - xorg-libxcursor=1.2.3=hb9d3cd8_0 - xorg-libxdamage=1.1.6=hb9d3cd8_0 - xorg-libxdmcp=1.1.5=hb9d3cd8_0 - xorg-libxext=1.3.6=hb9d3cd8_0 - xorg-libxfixes=6.0.1=hb9d3cd8_0 - xorg-libxi=1.8.2=hb9d3cd8_0 - xorg-libxrandr=1.5.4=hb9d3cd8_0 - xorg-libxrender=0.9.12=hb9d3cd8_0 - xorg-libxtst=1.2.5=hb9d3cd8_3 - xorg-libxxf86vm=1.1.6=hb9d3cd8_0 - xyzservices=2025.1.0=pyhd8ed1ab_0 - yaml=0.2.5=h7f98852_2 - zeromq=4.3.5=h3b0a872_7 - zipp=3.21.0=pyhd8ed1ab_1 - zlib=1.3.1=hb9d3cd8_2 - zstandard=0.23.0=py310ha75aee5_1 - zstd=1.5.7=hb8e6e7a_2 - pip: - coverage==7.8.0 - iniconfig==2.1.0 - momepy==0.8.0a3.dev14+g555c51e - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 prefix: /opt/conda/envs/momepy
[ "momepy/functional/tests/test_elements.py::TestElements::test_multi_index" ]
[]
[ "momepy/functional/tests/test_elements.py::TestElements::test_morphological_tessellation", "momepy/functional/tests/test_elements.py::TestElements::test_morphological_tessellation_buffer_clip", "momepy/functional/tests/test_elements.py::TestElements::test_morphological_tessellation_errors", "momepy/functional/tests/test_elements.py::TestElements::test_enclosed_tessellation", "momepy/functional/tests/test_elements.py::TestElements::test_verify_tessellation", "momepy/functional/tests/test_elements.py::TestElements::test_get_nearest_street", "momepy/functional/tests/test_elements.py::TestElements::test_get_nearest_node", "momepy/functional/tests/test_elements.py::TestElements::test_get_nearest_node_missing", "momepy/functional/tests/test_elements.py::TestElements::test_buffered_limit", "momepy/functional/tests/test_elements.py::TestElements::test_buffered_limit_adaptive", "momepy/functional/tests/test_elements.py::TestElements::test_buffered_limit_error", "momepy/functional/tests/test_elements.py::TestElements::test_blocks", "momepy/functional/tests/test_elements.py::TestElements::test_blocks_inner", "momepy/functional/tests/test_elements.py::TestElements::test_tess_single_building_edge_case", "momepy/functional/tests/test_elements.py::TestElementsEquivalence::test_blocks" ]
[]
BSD 3-Clause "New" or "Revised" License
18,738
2,185
[ "momepy/functional/_elements.py", "momepy/functional/_shape.py" ]
tobymao__sqlglot-3682
ac0e89c4401f2f278d32c3e956670b262ab21ce7
2024-06-20 14:59:44
a1a02782f22b471ee3c896d57f15237dc86565d1
diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 0d2cc2b9..0aae2e40 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -4486,10 +4486,22 @@ class Parser(metaclass=_Parser): def _parse_struct_types(self, type_required: bool = False) -> t.Optional[exp.Expression]: index = self._index - this = ( - self._parse_type(parse_interval=False, fallback_to_identifier=True) - or self._parse_id_var() - ) + + if ( + self._curr + and self._next + and self._curr.token_type in self.TYPE_TOKENS + and self._next.token_type in self.TYPE_TOKENS + ): + # Takes care of special cases like `STRUCT<list ARRAY<...>>` where the identifier is also a + # type token. Without this, the list will be parsed as a type and we'll eventually crash + this = self._parse_id_var() + else: + this = ( + self._parse_type(parse_interval=False, fallback_to_identifier=True) + or self._parse_id_var() + ) + self._match(TokenType.COLON) if (
sqlglot fails to parse BigQuery type cast **Fully reproducible code snippet** ```python import sqlglot sqlglot.parse_one(sql="select sources::STRUCT<list ARRAY<STRUCT<element STRUCT<property STRING, dataset STRING, record_id STRING, confidence FLOAT64>>>> from bar", dialect="bigquery") ``` Produces ``` sqlglot.errors.ParseError: Required keyword: 'expression' missing for <class 'sqlglot.expressions.BitwiseRightShift'>. Line 1, Col: 134 ```
tobymao/sqlglot
diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py index 42cb27f7..a7affe68 100644 --- a/tests/dialects/test_bigquery.py +++ b/tests/dialects/test_bigquery.py @@ -103,6 +103,7 @@ LANGUAGE js AS select_with_quoted_udf = self.validate_identity("SELECT `p.d.UdF`(data) FROM `p.d.t`") self.assertEqual(select_with_quoted_udf.selects[0].name, "p.d.UdF") + self.validate_identity("CAST(x AS STRUCT<list ARRAY<INT64>>)") self.validate_identity("assert.true(1 = 1)") self.validate_identity("SELECT ARRAY_TO_STRING(list, '--') AS text") self.validate_identity("SELECT jsondoc['some_key']")
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
25.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 Pygments==2.19.1 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@ac0e89c4401f2f278d32c3e956670b262ab21ce7#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pygments==2.19.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery" ]
[]
[ "tests/dialects/test_bigquery.py::TestBigQuery::test_errors", "tests/dialects/test_bigquery.py::TestBigQuery::test_gap_fill", "tests/dialects/test_bigquery.py::TestBigQuery::test_group_concat", "tests/dialects/test_bigquery.py::TestBigQuery::test_json_object", "tests/dialects/test_bigquery.py::TestBigQuery::test_merge", "tests/dialects/test_bigquery.py::TestBigQuery::test_mod", "tests/dialects/test_bigquery.py::TestBigQuery::test_models", "tests/dialects/test_bigquery.py::TestBigQuery::test_pushdown_cte_column_names", "tests/dialects/test_bigquery.py::TestBigQuery::test_remove_precision_parameterized_types", "tests/dialects/test_bigquery.py::TestBigQuery::test_rename_table", "tests/dialects/test_bigquery.py::TestBigQuery::test_user_defined_functions", "tests/dialects/test_bigquery.py::TestBigQuery::test_warnings" ]
[]
MIT License
18,740
301
[ "sqlglot/parser.py" ]
sdv-dev__SDMetrics-598
fa72f857e8b132231540e6270fd16ef1376f7c57
2024-06-21 12:01:55
af28309a1d5d77f816d96989ec9dc3faf22a330b
sdv-team: Task linked: [CU-86b0uyzmn SDMetrics - Update ReferentialIntegrity to support NaNs in child column #587](https://app.clickup.com/t/86b0uyzmn)
diff --git a/sdmetrics/reports/single_table/_properties/column_pair_trends.py b/sdmetrics/reports/single_table/_properties/column_pair_trends.py index 3286991..a30536a 100644 --- a/sdmetrics/reports/single_table/_properties/column_pair_trends.py +++ b/sdmetrics/reports/single_table/_properties/column_pair_trends.py @@ -123,7 +123,7 @@ class ColumnPairTrends(BaseSingleTableProperty): column_name, processed_data[column_name] ) - return processed_data, pd.DataFrame(discretized_dict) + return processed_data, pd.DataFrame(discretized_dict, index=processed_data.index) def _get_columns_data_and_metric( self,
Update Referential Integrity metric to support NaNs in child column ### Problem Description - For the Referential Integrity metric, we currently do the following: - If the foreign key in the real data has any NaN values, those are dropped in the foreign key in the synthetic data. - We also verify that all foreign keys have valid parent. - To support NaNs values in foreign keys, we need to update this logic. ### Expected behavior - Update `ReferentialIntegrity.compute_breakdown()` to do the following: - If the real data has NaN values, and the synthetic data has NaN values in the FK, then it is okay. - If the real data does not have NaN values, but the synthetic data has NaN values in the FK, this will result in a lower score. - The score can be lowered by the number of extra NaNs present in the synthetic data. - Update test_referential_interity.py - Update documentation ### Additional context - Function to update: https://github.com/sdv-dev/SDMetrics/blob/51f3ac2904c065462097c80f4387b973657ad6d9/sdmetrics/column_pairs/statistical/referential_integrity.py#L36
sdv-dev/SDMetrics
diff --git a/tests/integration/reports/single_table/_properties/test_column_pair_trends.py b/tests/integration/reports/single_table/_properties/test_column_pair_trends.py index b0fed1f..3f34ed0 100644 --- a/tests/integration/reports/single_table/_properties/test_column_pair_trends.py +++ b/tests/integration/reports/single_table/_properties/test_column_pair_trends.py @@ -20,8 +20,8 @@ class TestColumnPairTrends: } # Run - column_shape_property = ColumnPairTrends() - score = column_shape_property.get_score(real_data, synthetic_data, metadata) + column_pair_trends = ColumnPairTrends() + score = column_pair_trends.get_score(real_data, synthetic_data, metadata) # Assert expected_details_dict = { @@ -61,7 +61,7 @@ class TestColumnPairTrends: 'Synthetic Correlation': [-0.11506297326956302, np.nan, np.nan, np.nan, np.nan, np.nan], } expected_details = pd.DataFrame(expected_details_dict) - pd.testing.assert_frame_equal(column_shape_property.details, expected_details) + pd.testing.assert_frame_equal(column_pair_trends.details, expected_details) assert score == 0.8050699533533958 def test_get_score_warnings(self, recwarn): @@ -77,7 +77,7 @@ class TestColumnPairTrends: real_data['second_perc'].iloc[2] = 'a' # Run - column_shape_property = ColumnPairTrends() + column_pair_trends = ColumnPairTrends() exp_message_1 = "ValueError: could not convert string to float: 'a'" @@ -85,10 +85,10 @@ class TestColumnPairTrends: exp_error_serie = pd.Series([exp_message_1, None, None, exp_message_2, exp_message_2, None]) - score = column_shape_property.get_score(real_data, synthetic_data, metadata) + score = column_pair_trends.get_score(real_data, synthetic_data, metadata) # Assert - details = column_shape_property.details + details = column_pair_trends.details pd.testing.assert_series_equal(details['Error'], exp_error_serie, check_names=False) assert score == 0.7751937984496124 @@ -103,8 +103,8 @@ class TestColumnPairTrends: } # Run - column_shape_property = ColumnPairTrends() - score = column_shape_property.get_score(real_data, synthetic_data, metadata) + column_pair_trends = ColumnPairTrends() + score = column_pair_trends.get_score(real_data, synthetic_data, metadata) # Assert expected_details_dict = { @@ -137,5 +137,21 @@ class TestColumnPairTrends: 'Synthetic Correlation': [np.nan] * 6, } expected_details = pd.DataFrame(expected_details_dict) - pd.testing.assert_frame_equal(column_shape_property.details, expected_details) + pd.testing.assert_frame_equal(column_pair_trends.details, expected_details) assert score == 0.8930232558139535 + + def test_with_different_indexes(self): + """Test the property when the real and synthetic data only differ by their indexes.""" + # Setup + real_data = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'a']}, index=[0, 1, 2]) + + synthetic_data = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'a']}, index=[0, 4, 2]) + + metadata = {'columns': {'A': {'sdtype': 'numerical'}, 'B': {'sdtype': 'categorical'}}} + + # Run + column_pair_trends = ColumnPairTrends() + score = column_pair_trends.get_score(real_data, synthetic_data, metadata) + + # Assert + assert score == 1.0 diff --git a/tests/unit/column_pairs/statistical/test_referential_integrity.py b/tests/unit/column_pairs/statistical/test_referential_integrity.py index 6214542..a68cc77 100644 --- a/tests/unit/column_pairs/statistical/test_referential_integrity.py +++ b/tests/unit/column_pairs/statistical/test_referential_integrity.py @@ -68,32 +68,56 @@ class TestReferentialIntegrity: assert result == 0.6 def test_compute_with_nan_foreign_keys_real_data(self): - """Test the ``compute`` method with NaN foreign keys inside the real data.""" + """Test the ``compute`` method with NaN foreign keys inside the real data. + + Here, the score should be 1.0, whether or not the synthetic data have NaN values + values, as the real data have null foreign keys. + """ # Setup parent_keys = pd.Series(['a', 'b', 'c']) - foreign_keys = pd.Series(['a', 'a', 'b', 'c', np.nan]) + real_fk = pd.Series(['a', 'a', 'b', 'c', np.nan]) + synthetic_fk = pd.Series(['a', 'a', 'b', 'c', 'a']) + synthetic_fk_with_nan = pd.Series(['a', 'a', 'b', 'c', np.nan]) metric = ReferentialIntegrity() # Run result = metric.compute( - real_data=(parent_keys, foreign_keys), synthetic_data=(parent_keys, foreign_keys) + real_data=(parent_keys, real_fk), synthetic_data=(parent_keys, synthetic_fk) + ) + result_with_nan = metric.compute( + real_data=(parent_keys, real_fk), synthetic_data=(parent_keys, synthetic_fk_with_nan) ) # Assert assert result == 1.0 + assert result_with_nan == 1.0 def test_compute_with_nan_foreign_keys_only_synthetic_data(self): - """Test the ``compute`` method with NaN foreign keys inside the synthetic data.""" + """Test the ``compute`` method with NaN foreign keys inside the synthetic data. + + Here, the real data have no null foreign keys, so the score should decrease as + the number of NaN values in the synthetic data increases. + """ # Setup parent_keys = pd.Series(['a', 'b', 'c']) - foreign_keys = pd.Series(['a', 'a', 'b', 'c', 'a']) - synth_foreign_keys = pd.Series(['a', 'a', 'b', 'c', np.nan]) + real_fk = pd.Series(['a', 'a', 'b', 'c', 'a']) + synth_fk_0_nan = pd.Series(['a', 'a', 'b', 'c']) + synth_fk_1_nan = pd.Series(['a', 'a', 'b', 'c', np.nan]) + synth_fk_2_nan = pd.Series(['a', 'a', 'b', 'c', np.nan, np.nan]) metric = ReferentialIntegrity() # Run - result = metric.compute( - real_data=(parent_keys, foreign_keys), synthetic_data=(parent_keys, synth_foreign_keys) + result_0 = metric.compute( + real_data=(parent_keys, real_fk), synthetic_data=(parent_keys, synth_fk_0_nan) + ) + result_1 = metric.compute( + real_data=(parent_keys, real_fk), synthetic_data=(parent_keys, synth_fk_1_nan) + ) + result_2 = metric.compute( + real_data=(parent_keys, real_fk), synthetic_data=(parent_keys, synth_fk_2_nan) ) # Assert - assert result == 0.8 + assert result_0 == 1.0 + assert result_1 == 0.8 + assert result_2 == 2 / 3 diff --git a/tests/unit/reports/single_table/_properties/test_column_pair_trends.py b/tests/unit/reports/single_table/_properties/test_column_pair_trends.py index 861e1f7..8384ab8 100644 --- a/tests/unit/reports/single_table/_properties/test_column_pair_trends.py +++ b/tests/unit/reports/single_table/_properties/test_column_pair_trends.py @@ -66,12 +66,15 @@ class TestColumnPairTrends: def test__get_processed_data(self): """Test the ``_get_processed_data`` method.""" # Setup - data = pd.DataFrame({ - 'col1': [1, 2, 3], - 'col2': [False, True, True], - 'col3': ['a', 'b', 'c'], - 'col4': pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-03']), - }) + data = pd.DataFrame( + { + 'col1': [1, 2, 3], + 'col2': [False, True, True], + 'col3': ['a', 'b', 'c'], + 'col4': pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-03']), + }, + index=[4, 5, 6], + ) metadata = { 'columns': { 'col1': {'sdtype': 'numerical'}, @@ -89,17 +92,23 @@ class TestColumnPairTrends: expected_datetime = pd.to_numeric( pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-03']) ) - expected_processed_data = pd.DataFrame({ - 'col1': [1, 2, 3], - 'col2': [False, True, True], - 'col3': ['a', 'b', 'c'], - 'col4': expected_datetime, - }) + expected_processed_data = pd.DataFrame( + { + 'col1': [1, 2, 3], + 'col2': [False, True, True], + 'col3': ['a', 'b', 'c'], + 'col4': expected_datetime, + }, + index=[4, 5, 6], + ) - expected_discrete_data = pd.DataFrame({ - 'col1': [1, 6, 11], - 'col4': [1, 6, 11], - }) + expected_discrete_data = pd.DataFrame( + { + 'col1': [1, 6, 11], + 'col4': [1, 6, 11], + }, + index=[4, 5, 6], + ) pd.testing.assert_frame_equal(processed_data, expected_processed_data) pd.testing.assert_frame_equal(discrete_data, expected_discrete_data)
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-rerunfailures", "jupyter", "rundoc", "tomli", "invoke", "pytest-runner" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.7.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backports.tarfile==1.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 bracex==2.5.post1 build==1.2.2.post1 bump-my-version==0.33.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 chardet==5.2.0 charset-normalizer==3.4.1 click==7.1.2 colorama==0.4.6 comm==0.2.2 copulas==0.12.1 coverage==7.8.0 cryptography==44.0.2 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fqdn==1.5.1 fsspec==2025.3.1 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 invoke==2.2.0 ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 isoduration==20.11.0 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jedi==0.19.2 jeepney==0.9.0 Jinja2==3.1.6 joblib==1.4.2 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 keyring==25.6.0 Markdown==2.6.11 markdown-it-py==3.0.0 markdown-rundoc==0.3.1 MarkupSafe==3.0.2 matplotlib-inline==0.1.7 mdurl==0.1.2 mistune==3.1.3 more-itertools==10.6.0 mpmath==1.3.0 narwhals==1.32.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 networkx==3.2.1 nh3==0.2.21 notebook==7.3.3 notebook_shim==0.2.4 numpy==1.26.4 nvidia-cublas-cu12==12.4.5.8 nvidia-cuda-cupti-cu12==12.4.127 nvidia-cuda-nvrtc-cu12==12.4.127 nvidia-cuda-runtime-cu12==12.4.127 nvidia-cudnn-cu12==9.1.0.70 nvidia-cufft-cu12==11.2.1.3 nvidia-curand-cu12==10.3.5.147 nvidia-cusolver-cu12==11.6.1.9 nvidia-cusparse-cu12==12.3.1.170 nvidia-cusparselt-cu12==0.6.2 nvidia-nccl-cu12==2.21.5 nvidia-nvjitlink-cu12==12.4.127 nvidia-nvtx-cu12==12.4.127 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 pkginfo==1.10.0 platformdirs==4.3.7 plotly==6.0.1 pluggy==1.5.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 py==1.11.0 pycparser==2.22 pydantic==2.11.1 pydantic-settings==2.8.1 pydantic_core==2.33.0 Pygments==2.19.1 pyproject-api==1.9.0 pyproject_hooks==1.2.0 pytest==6.2.5 pytest-cov==2.12.1 pytest-rerunfailures==12.0 pytest-runner==6.0.1 python-dateutil==2.9.0.post0 python-dotenv==1.1.0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 readme_renderer==44.0 referencing==0.36.2 requests==2.32.3 requests-toolbelt==1.0.0 rfc3339-validator==0.1.4 rfc3986==2.0.0 rfc3986-validator==0.1.1 rich==14.0.0 rich-click==1.8.8 rpds-py==0.24.0 ruff==0.11.2 rundoc==0.4.5 scikit-learn==1.6.1 scipy==1.13.1 -e git+https://github.com/sdv-dev/SDMetrics.git@fa72f857e8b132231540e6270fd16ef1376f7c57#egg=sdmetrics SecretStorage==3.3.3 Send2Trash==1.8.3 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 sympy==1.13.1 terminado==0.18.1 threadpoolctl==3.6.0 tinycss2==1.4.0 toml==0.10.2 tomli==2.2.1 tomlkit==0.13.2 torch==2.6.0 tornado==6.4.2 tox==4.25.0 tqdm==4.67.1 traitlets==5.14.3 triton==3.2.0 twine==5.1.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 virtualenv==20.29.3 watchdog==4.0.2 wcmatch==10.0 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 zipp==3.21.0
name: SDMetrics channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.7.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backports-tarfile==1.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - bracex==2.5.post1 - build==1.2.2.post1 - bump-my-version==0.33.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==7.1.2 - colorama==0.4.6 - comm==0.2.2 - copulas==0.12.1 - coverage==7.8.0 - cryptography==44.0.2 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fqdn==1.5.1 - fsspec==2025.3.1 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.28.1 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - invoke==2.2.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jedi==0.19.2 - jeepney==0.9.0 - jinja2==3.1.6 - joblib==1.4.2 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - keyring==25.6.0 - markdown==2.6.11 - markdown-it-py==3.0.0 - markdown-rundoc==0.3.1 - markupsafe==3.0.2 - matplotlib-inline==0.1.7 - mdurl==0.1.2 - mistune==3.1.3 - more-itertools==10.6.0 - mpmath==1.3.0 - narwhals==1.32.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - networkx==3.2.1 - nh3==0.2.21 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==1.26.4 - nvidia-cublas-cu12==12.4.5.8 - nvidia-cuda-cupti-cu12==12.4.127 - nvidia-cuda-nvrtc-cu12==12.4.127 - nvidia-cuda-runtime-cu12==12.4.127 - nvidia-cudnn-cu12==9.1.0.70 - nvidia-cufft-cu12==11.2.1.3 - nvidia-curand-cu12==10.3.5.147 - nvidia-cusolver-cu12==11.6.1.9 - nvidia-cusparse-cu12==12.3.1.170 - nvidia-cusparselt-cu12==0.6.2 - nvidia-nccl-cu12==2.21.5 - nvidia-nvjitlink-cu12==12.4.127 - nvidia-nvtx-cu12==12.4.127 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - pkginfo==1.10.0 - platformdirs==4.3.7 - plotly==6.0.1 - pluggy==1.5.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - py==1.11.0 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pydantic-settings==2.8.1 - pygments==2.19.1 - pyproject-api==1.9.0 - pyproject-hooks==1.2.0 - pytest==6.2.5 - pytest-cov==2.12.1 - pytest-rerunfailures==12.0 - pytest-runner==6.0.1 - python-dateutil==2.9.0.post0 - python-dotenv==1.1.0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - readme-renderer==44.0 - referencing==0.36.2 - requests==2.32.3 - requests-toolbelt==1.0.0 - rfc3339-validator==0.1.4 - rfc3986==2.0.0 - rfc3986-validator==0.1.1 - rich==14.0.0 - rich-click==1.8.8 - rpds-py==0.24.0 - ruff==0.11.2 - rundoc==0.4.5 - scikit-learn==1.6.1 - scipy==1.13.1 - sdmetrics==0.14.2.dev0 - secretstorage==3.3.3 - send2trash==1.8.3 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - sympy==1.13.1 - terminado==0.18.1 - threadpoolctl==3.6.0 - tinycss2==1.4.0 - toml==0.10.2 - tomli==2.2.1 - tomlkit==0.13.2 - torch==2.6.0 - tornado==6.4.2 - tox==4.25.0 - tqdm==4.67.1 - traitlets==5.14.3 - triton==3.2.0 - twine==5.1.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - virtualenv==20.29.3 - watchdog==4.0.2 - wcmatch==10.0 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - zipp==3.21.0 prefix: /opt/conda/envs/SDMetrics
[ "tests/integration/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test_with_different_indexes", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test__get_processed_data" ]
[]
[ "tests/integration/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test_get_score", "tests/integration/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test_get_score_warnings", "tests/integration/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test_only_categorical_columns", "tests/unit/column_pairs/statistical/test_referential_integrity.py::TestReferentialIntegrity::test_compute_breakdown", "tests/unit/column_pairs/statistical/test_referential_integrity.py::TestReferentialIntegrity::test_compute_breakdown_with_missing_relations_real_data", "tests/unit/column_pairs/statistical/test_referential_integrity.py::TestReferentialIntegrity::test_compute", "tests/unit/column_pairs/statistical/test_referential_integrity.py::TestReferentialIntegrity::test_compute_with_nan_foreign_keys_real_data", "tests/unit/column_pairs/statistical/test_referential_integrity.py::TestReferentialIntegrity::test_compute_with_nan_foreign_keys_only_synthetic_data", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test__convert_datetime_columns_to_numeric", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test__discretize_column", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test__get_processed_data_with_nans", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test_get_columns_data_and_metric", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test_preprocessing_failed", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test__generate_details", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test__get_correlation_matrix_score", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test__get_correlation_matrix_correlation", "tests/unit/reports/single_table/_properties/test_column_pair_trends.py::TestColumnPairTrends::test_get_visualization" ]
[]
MIT License
18,751
174
[ "sdmetrics/reports/single_table/_properties/column_pair_trends.py" ]
yukinarit__pyserde-561
750581a83c381df55149bd762966ef17ec8ed904
2024-06-21 13:56:32
0587025a1b205e649bff0ceb22a91f64c9dafdbf
diff --git a/serde/compat.py b/serde/compat.py index 5a78a47..2b3ccb9 100644 --- a/serde/compat.py +++ b/serde/compat.py @@ -355,17 +355,15 @@ def iter_unions(cls: TypeLike) -> list[TypeLike]: """ Iterate over all unions that are used in the dataclass """ - lst: set[TypeLike] = set() + lst: list[TypeLike] = [] stack: list[TypeLike] = [] # To prevent infinite recursion def recursive(cls: TypeLike) -> None: - if cls in lst: - return if cls in stack: return if is_union(cls): - lst.add(cls) + lst.append(cls) for arg in type_args(cls): recursive(arg) if is_dataclass(cls): @@ -391,7 +389,7 @@ def iter_unions(cls: TypeLike) -> list[TypeLike]: recursive(args[1]) recursive(cls) - return list(lst) + return lst def iter_literals(cls: type[Any]) -> list[TypeLike]:
Error when parsing Union types with different ordering Tested versions: - Python: **3.10.4** - Pyserde: **0.12.6** If you define two unions with the same members, but different orders, then attempting to parse a document throws an error. Example: ```python from serde import serde from serde.json import from_json @serde class Expr: expr: str MaybeExpr = str | Expr MaybeExpr2 = Expr | str @serde class Test: a: MaybeExpr b: MaybeExpr2 if __name__ == '__main__': print(from_json(Test, '{"a": "x", "b": "y"}')) ``` Result: ``` Traceback (most recent call last): File "/Users/sstagg/tmp/pystest/test.py", line 18, in <module> print(from_json(Test, '{"a": "x", "b": "y"}')) File "/Users/sstagg/.pyenv/versions/3.10.4/lib/python3.10/site-packages/serde/json.py", line 95, in from_json return from_dict(c, de.deserialize(s, **opts), reuse_instances=False) File "/Users/sstagg/.pyenv/versions/3.10.4/lib/python3.10/site-packages/serde/de.py", line 494, in from_dict return from_obj(cls, o, named=True, reuse_instances=reuse_instances) File "/Users/sstagg/.pyenv/versions/3.10.4/lib/python3.10/site-packages/serde/de.py", line 460, in from_obj raise SerdeError(e) from None serde.compat.SerdeError: 'union_de_Expr_str' ``` Arguably this is a something trivially fixed by not having multiple Unions with different types, but the error message is a bit tricky to debug here, and is very possible with more complex scenarios. It looks a bit like member order is ignored when constructing the ser/de methods (makes sense), but is relied on when looking up the ser/de method. I guess it might make sense to sort the member names in the method name for a union?
yukinarit/pyserde
diff --git a/tests/test_union.py b/tests/test_union.py index 8021446..75fa80d 100644 --- a/tests/test_union.py +++ b/tests/test_union.py @@ -804,3 +804,21 @@ def test_union_with_any() -> None: c = Class([FooWithString("string"), BarWithDict({"key": "value"})]) assert c == from_json(Class, to_json(c)) + + +def test_union_with_different_ordering() -> None: + + @serde + class Expr: + expr: str + + @serde + class Foo: + a: Union[str, Expr] + b: Union[Expr, str] + c: Union[Expr, str] + + f = Foo("1", Expr("2"), "3") + s = '{"a":"1","b":{"Expr":{"expr":"2"}},"c":"3"}' + assert s == to_json(f) + assert f == from_json(Foo, s)
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.19
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "pytest-watch", "pytest-flake8", "coverage" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
beartype==0.20.2 casefy==1.1.0 colorama==0.4.6 coverage==7.8.0 docopt==0.6.2 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work flake8==7.2.0 greenlet==3.1.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 mccabe==0.7.0 msgpack==1.1.0 mypy-extensions==1.0.0 numpy==1.26.4 orjson==3.10.16 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work plum-dispatch==2.2.2 pycodestyle==2.13.0 pyflakes==3.3.1 -e git+https://github.com/yukinarit/pyserde.git@750581a83c381df55149bd762966ef17ec8ed904#egg=pyserde pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 pytest-flake8==1.3.0 pytest-watch==4.2.0 PyYAML==6.0.2 SQLAlchemy==2.0.40 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tomli_w==1.2.0 typing-inspect==0.9.0 typing_extensions==4.13.0 watchdog==6.0.0
name: pyserde channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - beartype==0.20.2 - casefy==1.1.0 - colorama==0.4.6 - coverage==7.8.0 - docopt==0.6.2 - flake8==7.2.0 - greenlet==3.1.1 - jinja2==3.1.6 - markupsafe==3.0.2 - mccabe==0.7.0 - msgpack==1.1.0 - mypy-extensions==1.0.0 - numpy==1.26.4 - orjson==3.10.16 - plum-dispatch==2.2.2 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pyserde==0.19.1 - pytest-cov==6.0.0 - pytest-flake8==1.3.0 - pytest-watch==4.2.0 - pyyaml==6.0.2 - sqlalchemy==2.0.40 - tomli-w==1.2.0 - typing-extensions==4.13.0 - typing-inspect==0.9.0 - watchdog==6.0.0 prefix: /opt/conda/envs/pyserde
[ "tests/test_union.py::test_union_with_different_ordering" ]
[]
[ "tests/test_union.py::test_union", "tests/test_union.py::test_union_optional", "tests/test_union.py::test_union_containers", "tests/test_union.py::test_union_with_literal", "tests/test_union.py::test_union_with_complex_types", "tests/test_union.py::test_union_with_complex_types_and_reuse_instances", "tests/test_union.py::test_optional_union_with_complex_types", "tests/test_union.py::test_optional_complex_type_with_default", "tests/test_union.py::test_union_with_complex_types_in_containers", "tests/test_union.py::test_union_exception_if_nothing_matches", "tests/test_union.py::test_union_in_union", "tests/test_union.py::test_union_in_other_type", "tests/test_union.py::test_union_rename_all", "tests/test_union.py::test_union_with_list_of_other_class", "tests/test_union.py::test_union_with_union_in_nested_types", "tests/test_union.py::test_union_with_union_in_nested_tuple", "tests/test_union.py::test_generic_union", "tests/test_union.py::test_external_tagging", "tests/test_union.py::test_internal_tagging", "tests/test_union.py::test_adjacent_tagging", "tests/test_union.py::test_untagged", "tests/test_union.py::test_newtype_and_untagged_union", "tests/test_union.py::test_union_directly", "tests/test_union.py::test_union_frozenset_with_prim", "tests/test_union.py::test_union_with_any" ]
[]
MIT License
18,755
277
[ "serde/compat.py" ]
mhostetter__galois-551
058c8f1e42c2a7f20221035b5543894435bf2954
2024-06-22 16:06:28
058c8f1e42c2a7f20221035b5543894435bf2954
diff --git a/src/galois/_domains/_calculate.py b/src/galois/_domains/_calculate.py index 708a72234..c93cd68cd 100644 --- a/src/galois/_domains/_calculate.py +++ b/src/galois/_domains/_calculate.py @@ -464,7 +464,7 @@ class reciprocal_itoh_tsujii(_lookup.reciprocal_ufunc): ORDER = self.field.order MULTIPLY = self.field._multiply.ufunc POSITIVE_POWER = self.field._positive_power.ufunc - SUBFIELD_RECIPROCAL = self.field.prime_subfield._reciprocal.ufunc + SUBFIELD_RECIPROCAL = getattr(self.field.prime_subfield._reciprocal, self.field.ufunc_mode.replace("-", "_")) @staticmethod def calculate(a: int) -> int: diff --git a/src/galois/_domains/_meta.py b/src/galois/_domains/_meta.py index 5ff81fdf5..892bf549f 100644 --- a/src/galois/_domains/_meta.py +++ b/src/galois/_domains/_meta.py @@ -41,10 +41,10 @@ class ArrayMeta(abc.ABCMeta): cls._ufunc_modes = ["python-calculate"] elif cls._order <= 2**20: cls._default_ufunc_mode = "jit-lookup" - cls._ufunc_modes = ["jit-lookup", "jit-calculate"] + cls._ufunc_modes = ["jit-lookup", "jit-calculate", "python-calculate"] else: cls._default_ufunc_mode = "jit-calculate" - cls._ufunc_modes = ["jit-lookup", "jit-calculate"] + cls._ufunc_modes = ["jit-lookup", "jit-calculate", "python-calculate"] cls._ufunc_mode = None # This is set in the first call to compile cls._name = "Undefined" # Needs overridden diff --git a/src/galois/_domains/_ufunc.py b/src/galois/_domains/_ufunc.py index 6f85b633d..72168b6da 100644 --- a/src/galois/_domains/_ufunc.py +++ b/src/galois/_domains/_ufunc.py @@ -516,6 +516,8 @@ class log_ufunc(UFunc): inputs = list(inputs) + [int(self.field.primitive_element)] inputs, kwargs = self._view_inputs_as_ndarray(inputs, kwargs) output = getattr(self.ufunc, method)(*inputs, **kwargs) + if output.dtype == np.object_: + output = output.astype(int) return output diff --git a/src/galois/_fields/_array.py b/src/galois/_fields/_array.py index 61b590727..5cf847d38 100644 --- a/src/galois/_fields/_array.py +++ b/src/galois/_fields/_array.py @@ -1730,6 +1730,8 @@ class FieldArray(Array, metaclass=FieldArrayMeta): if np.isscalar(output): output = int(output) + if output.dtype == np.object_: + output = output.astype(int) return output diff --git a/src/galois/_fields/_gf2.py b/src/galois/_fields/_gf2.py index ad40b40f8..212feed11 100644 --- a/src/galois/_fields/_gf2.py +++ b/src/galois/_fields/_gf2.py @@ -153,5 +153,5 @@ class GF2( GF2._default_ufunc_mode = "jit-calculate" -GF2._ufunc_modes = ["jit-calculate"] +GF2._ufunc_modes = ["jit-calculate", "python-calculate"] GF2.compile("auto")
JIT alternative Hello, Galois package has been very useful but I am having issues with the JIT compiled code using numba. Is there a way to turn the JIT compiling off using numba easily? Also, could you point me to where you are using numba for calculating rref and rank in _linalg? Im aware i will be sacrificing speed but im mainly interested in the fields arithmetic only. Thanks!
mhostetter/galois
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 618c48c9d..8217082ed 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -80,19 +80,9 @@ jobs: if: ${{ github.event_name == 'pull_request' }} strategy: matrix: - os: [ubuntu-latest, macos-latest, windows-latest] + os: [ubuntu-latest, macos-13, windows-latest] python-version: [3.7, 3.8, 3.9, '3.10', 3.11, 3.12] - # https://github.com/actions/runner-images/issues/9770#issuecomment-2085623315 - exclude: # Python < v3.8 does not support Apple Silicon ARM64 - - python-version: "3.7" - os: macos-latest - - python-version: "3.8" - os: macos-latest - include: # So run those legacy versions on Intel CPUs - - python-version: "3.7" - os: macos-13 - - python-version: "3.8" - os: macos-13 + fail-fast: false runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 @@ -153,6 +143,7 @@ jobs: include: # So run those legacy versions on Intel CPUs - python-version: "3.7" os: macos-13 + fail-fast: false runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 diff --git a/tests/fields/conftest.py b/tests/fields/conftest.py index 1b30fac64..a60645d0c 100644 --- a/tests/fields/conftest.py +++ b/tests/fields/conftest.py @@ -38,6 +38,7 @@ FIELDS = [ FIELDS_DIFF_MODES = [ # Binary field pytest.param("GF(2)-jit-calculate"), + pytest.param("GF(2)-python-calculate"), # Binary extension fields pytest.param("GF(2^2)-jit-lookup"), pytest.param("GF(2^2)-jit-calculate"), @@ -52,8 +53,10 @@ FIELDS_DIFF_MODES = [ # Prime fields pytest.param("GF(5)-jit-lookup"), pytest.param("GF(5)-jit-calculate"), + pytest.param("GF(5)-python-calculate"), pytest.param("GF(7)-jit-lookup"), pytest.param("GF(7)-jit-calculate"), + pytest.param("GF(7)-python-calculate"), pytest.param("GF(31)-jit-lookup"), pytest.param("GF(31)-jit-calculate"), pytest.param("GF(3191)-jit-lookup"), @@ -76,7 +79,7 @@ def construct_field(folder): ufunc_mode = "auto" if folder == "GF(2)": - GF = galois.GF2 + GF = galois.GF(2, compile=ufunc_mode) elif folder == "GF(5)": GF = galois.GF(5, compile=ufunc_mode) diff --git a/tests/fields/test_arithmetic.py b/tests/fields/test_arithmetic.py index d0eb7e623..5465c8425 100644 --- a/tests/fields/test_arithmetic.py +++ b/tests/fields/test_arithmetic.py @@ -5,6 +5,7 @@ A pytest module to test the accuracy of FieldArray arithmetic. import random import numpy as np +import pytest import galois @@ -218,11 +219,12 @@ def test_log_different_base(field_log): assert np.array_equal(beta**z, x) -def test_log_pollard_rho(): [email protected]("ufunc_mode", ["jit-calculate", "python-calculate"]) +def test_log_pollard_rho(ufunc_mode): """ The Pollard-rho discrete logarithm algorithm is only applicable for fields when p^m - 1 is prime. """ - GF = galois.GF(2**19, compile="jit-calculate") + GF = galois.GF(2**5, compile=ufunc_mode) assert isinstance(GF._log, galois._domains._calculate.log_pollard_rho) dtype = random.choice(GF.dtypes) x = GF.Random(10, low=1, dtype=dtype)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 5 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 coverage==7.8.0 cryptography==44.0.2 exceptiongroup==1.2.2 execnet==2.1.1 -e git+https://github.com/mhostetter/galois.git@058c8f1e42c2a7f20221035b5543894435bf2954#egg=galois idna==3.10 iniconfig==2.1.0 llvmlite==0.42.0 numba==0.59.1 numpy==1.26.4 packaging==24.2 pdfminer.six==20250327 pluggy==1.5.0 py-cpuinfo==9.0.0 pycparser==2.22 pytest==8.3.5 pytest-benchmark==5.1.0 pytest-cov==6.0.0 pytest-xdist==3.6.1 requests==2.32.3 ruff==0.4.7 tomli==2.2.1 typing_extensions==4.13.0 urllib3==2.3.0
name: galois channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - coverage==7.8.0 - cryptography==44.0.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - galois==0.3.9 - idna==3.10 - iniconfig==2.1.0 - llvmlite==0.42.0 - numba==0.59.1 - numpy==1.26.4 - packaging==24.2 - pdfminer-six==20250327 - pluggy==1.5.0 - py-cpuinfo==9.0.0 - pycparser==2.22 - pytest==8.3.5 - pytest-benchmark==5.1.0 - pytest-cov==6.0.0 - pytest-xdist==3.6.1 - requests==2.32.3 - ruff==0.4.7 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 prefix: /opt/conda/envs/galois
[ "tests/fields/test_arithmetic.py::test_add[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2)-python-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(5)-python-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(7)-python-calculate]", "tests/fields/test_arithmetic.py::test_log_pollard_rho[python-calculate]" ]
[]
[ "tests/fields/test_arithmetic.py::test_add[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_subtract[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiply[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divide[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divmod[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_mod[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_square[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^2)-jit-lookup]", "tests/fields/test_arithmetic.py::test_add[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^2)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_subtract[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiply[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divide[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divmod[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_mod[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_square[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_add[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_subtract[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiply[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divide[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divmod[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_mod[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_square[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^8)-jit-lookup]", "tests/fields/test_arithmetic.py::test_add[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^8)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(2^8,", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^8,", "tests/fields/test_arithmetic.py::test_subtract[GF(2^8,", "tests/fields/test_arithmetic.py::test_multiply[GF(2^8,", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^8,", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^8,", "tests/fields/test_arithmetic.py::test_divide[GF(2^8,", "tests/fields/test_arithmetic.py::test_divmod[GF(2^8,", "tests/fields/test_arithmetic.py::test_mod[GF(2^8,", "tests/fields/test_arithmetic.py::test_power[GF(2^8,", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^8,", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^8,", "tests/fields/test_arithmetic.py::test_square[GF(2^8,", "tests/fields/test_arithmetic.py::test_log[GF(2^8,", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^8,", "tests/fields/test_arithmetic.py::test_add[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^32)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2^100)-python-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_subtract[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiply[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divide[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divmod[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_mod[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_square[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(5)-jit-lookup]", "tests/fields/test_arithmetic.py::test_add[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(5)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_subtract[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiply[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divide[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divmod[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_mod[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_square[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(7)-jit-lookup]", "tests/fields/test_arithmetic.py::test_add[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(7)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_subtract[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiply[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divide[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divmod[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_mod[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_square[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(31)-jit-lookup]", "tests/fields/test_arithmetic.py::test_add[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(31)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_subtract[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiply[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divide[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divmod[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_mod[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_square[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(3191)-jit-lookup]", "tests/fields/test_arithmetic.py::test_add[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(3191)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(2147483647)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(36893488147419103183)-python-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_subtract[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiply[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divide[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_divmod[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_mod[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_square[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(7^3)-jit-lookup]", "tests/fields/test_arithmetic.py::test_add[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(7^3)-jit-calculate]", "tests/fields/test_arithmetic.py::test_add[GF(7^3,", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(7^3,", "tests/fields/test_arithmetic.py::test_subtract[GF(7^3,", "tests/fields/test_arithmetic.py::test_multiply[GF(7^3,", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(7^3,", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(7^3,", "tests/fields/test_arithmetic.py::test_divide[GF(7^3,", "tests/fields/test_arithmetic.py::test_divmod[GF(7^3,", "tests/fields/test_arithmetic.py::test_mod[GF(7^3,", "tests/fields/test_arithmetic.py::test_power[GF(7^3,", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(7^3,", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(7^3,", "tests/fields/test_arithmetic.py::test_square[GF(7^3,", "tests/fields/test_arithmetic.py::test_log[GF(7^3,", "tests/fields/test_arithmetic.py::test_log_different_base[GF(7^3,", "tests/fields/test_arithmetic.py::test_add[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_additive_inverse[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_subtract[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiply[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_scalar_multiply[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_multiplicative_inverse[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_divide[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_divmod[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_mod[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_power[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_zero[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_power_zero_to_positive_integer[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_square[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_log[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_log_different_base[GF(109987^4)-python-calculate]", "tests/fields/test_arithmetic.py::test_log_pollard_rho[jit-calculate]" ]
[]
MIT License
18,767
928
[ "src/galois/_domains/_calculate.py", "src/galois/_domains/_meta.py", "src/galois/_domains/_ufunc.py", "src/galois/_fields/_array.py", "src/galois/_fields/_gf2.py" ]
materialsvirtuallab__monty-688
0c4abd3f3256696be8aeaaf9e0c60d21faa2e476
2024-06-24 09:17:37
0c4abd3f3256696be8aeaaf9e0c60d21faa2e476
diff --git a/monty/json.py b/monty/json.py index 759758b..defecf3 100644 --- a/monty/json.py +++ b/monty/json.py @@ -644,7 +644,7 @@ class MontyEncoder(json.JSONEncoder): try: if pydantic is not None and isinstance(o, pydantic.BaseModel): - d = o.dict() + d = o.model_dump() elif ( dataclasses is not None and (not issubclass(o.__class__, MSONable)) @@ -709,6 +709,7 @@ class MontyDecoder(json.JSONDecoder): if cls_redirect := MSONable.REDIRECT.get(modname, {}).get(classname): classname = cls_redirect["@class"] modname = cls_redirect["@module"] + elif "@module" in d and "@callable" in d: modname = d["@module"] objname = d["@callable"] @@ -739,27 +740,28 @@ class MontyDecoder(json.JSONDecoder): classname = None if classname: - if modname and modname not in [ + if modname and modname not in { "bson.objectid", "numpy", "pandas", "torch", - ]: + }: if modname == "datetime" and classname == "datetime": try: + # Remove timezone info in the form of "+xx:00" dt = datetime.datetime.strptime( - d["string"], "%Y-%m-%d %H:%M:%S.%f" + d["string"].split("+")[0], "%Y-%m-%d %H:%M:%S.%f" ) except ValueError: dt = datetime.datetime.strptime( - d["string"], "%Y-%m-%d %H:%M:%S" + d["string"].split("+")[0], "%Y-%m-%d %H:%M:%S" ) return dt - if modname == "uuid" and classname == "UUID": + elif modname == "uuid" and classname == "UUID": return UUID(d["string"]) - if modname == "pathlib" and classname == "Path": + elif modname == "pathlib" and classname == "Path": return Path(d["string"]) mod = __import__(modname, globals(), locals(), [classname], 0) @@ -782,6 +784,7 @@ class MontyDecoder(json.JSONDecoder): ): d = {k: self.process_decoded(v) for k, v in data.items()} return cls_(**d) + elif torch is not None and modname == "torch" and classname == "Tensor": if "Complex" in d["dtype"]: return torch.tensor( # pylint: disable=E1101 @@ -791,6 +794,7 @@ class MontyDecoder(json.JSONDecoder): ], ).type(d["dtype"]) return torch.tensor(d["data"]).type(d["dtype"]) # pylint: disable=E1101 + elif np is not None and modname == "numpy" and classname == "array": if d["dtype"].startswith("complex"): return np.array( @@ -801,6 +805,7 @@ class MontyDecoder(json.JSONDecoder): dtype=d["dtype"], ) return np.array(d["data"], dtype=d["dtype"]) + elif modname == "pandas": import pandas as pd @@ -810,6 +815,7 @@ class MontyDecoder(json.JSONDecoder): if classname == "Series": decoded_data = MontyDecoder().decode(d["data"]) return pd.Series(decoded_data) + elif ( (bson is not None) and modname == "bson.objectid"
datetime serialization/deserialization broken datetime objects with time zone info break the serializatin because `__str__` doesn't output in the format that monty expects. Example: `datetime.datetime(2018, 12, 19, 21, 45, 41, 99000, tzinfo=datetime.timezone.utc).__str__()` yields `"2018-12-19 21:45:41.099000+00:00"` When deserializing, this causes monty to throw an error because the two datetime formatting strings it tries are: - "%Y-%m-%d %H:%M:%S.%f" - "%Y-%m-%d %H:%M:%S" resulting in value error like this from within `strptime`: `ValueError: unconverted data remains: .967000+00:00` We could just add the timezone format, or just use a formatting string when outputting from datetime to a string during serialization. There are also generic datetime parsing libraries like `dateutil`
materialsvirtuallab/monty
diff --git a/tests/test_json.py b/tests/test_json.py index 2653ec4..b67d4be 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -516,6 +516,14 @@ class TestJson: jsanitize(dt, strict=True) + # test timezone aware datetime API + created_at = datetime.datetime.now(tz=datetime.timezone.utc) + data = json.loads(json.dumps(created_at, cls=MontyEncoder)) + + created_at_after = MontyDecoder().process_decoded(data) + + assert str(created_at_after) == str(created_at).rstrip("+00:00") + def test_uuid(self): from uuid import UUID, uuid4
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
2024.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest>=8", "pytest-cov>=4", "types-requests", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/materialsvirtuallab/monty.git@0c4abd3f3256696be8aeaaf9e0c60d21faa2e476#egg=monty packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 tomli==2.2.1 types-requests==2.32.0.20250328 urllib3==2.3.0
name: monty channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - monty==2024.5.24 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - tomli==2.2.1 - types-requests==2.32.0.20250328 - urllib3==2.3.0 prefix: /opt/conda/envs/monty
[ "tests/test_json.py::TestJson::test_datetime" ]
[ "tests/test_json.py::TestJson::test_jsanitize", "tests/test_json.py::TestJson::test_redirect_settings_file" ]
[ "tests/test_json.py::TestMSONable::test_to_from_dict", "tests/test_json.py::TestMSONable::test_kw_only_args", "tests/test_json.py::TestMSONable::test_unsafe_hash", "tests/test_json.py::TestMSONable::test_version", "tests/test_json.py::TestMSONable::test_nested_to_from_dict", "tests/test_json.py::TestMSONable::test_enum_serialization", "tests/test_json.py::TestMSONable::test_enum_serialization_no_msonable", "tests/test_json.py::TestMSONable::test_save_load", "tests/test_json.py::TestJson::test_as_from_dict", "tests/test_json.py::TestJson::test_uuid", "tests/test_json.py::TestJson::test_path", "tests/test_json.py::TestJson::test_nan", "tests/test_json.py::TestJson::test_callable", "tests/test_json.py::TestJson::test_redirect", "tests/test_json.py::TestJson::test_dataclass", "tests/test_json.py::TestJson::test_enum" ]
[]
MIT License
18,777
870
[ "monty/json.py" ]
tobymao__sqlglot-3695
442c61defe05f4c168a7909d0a5fc5c043a2d2b4
2024-06-24 13:58:14
3b8568d37792c1916f05faf5df8af1841144b338
diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 0aae2e40..2ba64aa2 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -5960,7 +5960,7 @@ class Parser(metaclass=_Parser): return None def _parse_var_or_string(self) -> t.Optional[exp.Expression]: - return self._parse_var() or self._parse_string() + return self._parse_string() or self._parse_var(any_token=True) def _parse_primary_or_var(self) -> t.Optional[exp.Expression]: return self._parse_primary() or self._parse_var(any_token=True)
parse SQL with CAST FUNCTION exception under MySQL dialect When I parse the flowing sql using MySQL dialect , it encountered an exception like `’sqlglot.errors.ParseError: Required keyword: 'this' missing for <class 'sqlglot.expressions.CharacterSet'>. Line 1, Col: 61.’` the SQL is ` SELECT CAST(IFNULL(`id`, 'NULL') AS CHAR CHARACTER SET binary) from test`
tobymao/sqlglot
diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py index 280ebbf2..bfdb2a68 100644 --- a/tests/dialects/test_mysql.py +++ b/tests/dialects/test_mysql.py @@ -117,6 +117,7 @@ class TestMySQL(Validator): ) def test_identity(self): + self.validate_identity("SELECT CAST(COALESCE(`id`, 'NULL') AS CHAR CHARACTER SET binary)") self.validate_identity("SELECT e.* FROM e STRAIGHT_JOIN p ON e.x = p.y") self.validate_identity("ALTER TABLE test_table ALTER COLUMN test_column SET DEFAULT 1") self.validate_identity("SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:00.0000')")
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
25.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 coverage==7.8.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 Pygments==2.19.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@442c61defe05f4c168a7909d0a5fc5c043a2d2b4#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - coverage==7.8.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pygments==2.19.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_mysql.py::TestMySQL::test_identity" ]
[]
[ "tests/dialects/test_mysql.py::TestMySQL::test_bits_literal", "tests/dialects/test_mysql.py::TestMySQL::test_canonical_functions", "tests/dialects/test_mysql.py::TestMySQL::test_convert", "tests/dialects/test_mysql.py::TestMySQL::test_date_format", "tests/dialects/test_mysql.py::TestMySQL::test_ddl", "tests/dialects/test_mysql.py::TestMySQL::test_escape", "tests/dialects/test_mysql.py::TestMySQL::test_hexadecimal_literal", "tests/dialects/test_mysql.py::TestMySQL::test_introducers", "tests/dialects/test_mysql.py::TestMySQL::test_is_null", "tests/dialects/test_mysql.py::TestMySQL::test_json_object", "tests/dialects/test_mysql.py::TestMySQL::test_match_against", "tests/dialects/test_mysql.py::TestMySQL::test_monthname", "tests/dialects/test_mysql.py::TestMySQL::test_mysql", "tests/dialects/test_mysql.py::TestMySQL::test_mysql_time", "tests/dialects/test_mysql.py::TestMySQL::test_safe_div", "tests/dialects/test_mysql.py::TestMySQL::test_set_variable", "tests/dialects/test_mysql.py::TestMySQL::test_show_columns", "tests/dialects/test_mysql.py::TestMySQL::test_show_db_like_or_where_sql", "tests/dialects/test_mysql.py::TestMySQL::test_show_engine", "tests/dialects/test_mysql.py::TestMySQL::test_show_errors", "tests/dialects/test_mysql.py::TestMySQL::test_show_events", "tests/dialects/test_mysql.py::TestMySQL::test_show_grants", "tests/dialects/test_mysql.py::TestMySQL::test_show_index", "tests/dialects/test_mysql.py::TestMySQL::test_show_like_or_where", "tests/dialects/test_mysql.py::TestMySQL::test_show_name", "tests/dialects/test_mysql.py::TestMySQL::test_show_processlist", "tests/dialects/test_mysql.py::TestMySQL::test_show_profile", "tests/dialects/test_mysql.py::TestMySQL::test_show_replica_status", "tests/dialects/test_mysql.py::TestMySQL::test_show_simple", "tests/dialects/test_mysql.py::TestMySQL::test_show_tables", "tests/dialects/test_mysql.py::TestMySQL::test_string_literals", "tests/dialects/test_mysql.py::TestMySQL::test_timestamp_trunc", "tests/dialects/test_mysql.py::TestMySQL::test_types" ]
[]
MIT License
18,780
164
[ "sqlglot/parser.py" ]
tobymao__sqlglot-3697
806a7e421a9b5a54a2859d7bb4c3ea131a4a8640
2024-06-24 16:36:59
3b8568d37792c1916f05faf5df8af1841144b338
diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py index 3fd17e4e..4f557e7b 100644 --- a/sqlglot/dialects/bigquery.py +++ b/sqlglot/dialects/bigquery.py @@ -317,6 +317,7 @@ class BigQuery(Dialect): } KEYWORDS.pop("DIV") KEYWORDS.pop("VALUES") + KEYWORDS.pop("/*+") class Parser(parser.Parser): PREFIXED_PIVOT_COLUMNS = True diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py index df1b9dba..209a2894 100644 --- a/sqlglot/dialects/clickhouse.py +++ b/sqlglot/dialects/clickhouse.py @@ -147,6 +147,7 @@ class ClickHouse(Dialect): "SYSTEM": TokenType.COMMAND, "PREWHERE": TokenType.PREWHERE, } + KEYWORDS.pop("/*+") SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, diff --git a/sqlglot/dialects/drill.py b/sqlglot/dialects/drill.py index 06f49d5e..9d90a84f 100644 --- a/sqlglot/dialects/drill.py +++ b/sqlglot/dialects/drill.py @@ -70,6 +70,9 @@ class Drill(Dialect): IDENTIFIERS = ["`"] STRING_ESCAPES = ["\\"] + KEYWORDS = tokens.Tokenizer.KEYWORDS.copy() + KEYWORDS.pop("/*+") + class Parser(parser.Parser): STRICT_CAST = False diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py index 4db30b14..296405d3 100644 --- a/sqlglot/dialects/duckdb.py +++ b/sqlglot/dialects/duckdb.py @@ -220,6 +220,7 @@ class DuckDB(Dialect): "TIMESTAMP_US": TokenType.TIMESTAMP, "VARCHAR": TokenType.TEXT, } + KEYWORDS.pop("/*+") SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py index 526cb880..a4baf92c 100644 --- a/sqlglot/dialects/postgres.py +++ b/sqlglot/dialects/postgres.py @@ -331,6 +331,7 @@ class Postgres(Dialect): "REGTYPE": TokenType.OBJECT_IDENTIFIER, "FLOAT": TokenType.DOUBLE, } + KEYWORDS.pop("/*+") KEYWORDS.pop("DIV") SINGLE_TOKENS = { diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py index e4c1edf7..fd4750f6 100644 --- a/sqlglot/dialects/presto.py +++ b/sqlglot/dialects/presto.py @@ -227,7 +227,7 @@ class Presto(Dialect): "TDIGEST": TokenType.TDIGEST, "HYPERLOGLOG": TokenType.HLLSKETCH, } - + KEYWORDS.pop("/*+") KEYWORDS.pop("QUALIFY") class Parser(parser.Parser): diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py index d8b03055..8bd1f773 100644 --- a/sqlglot/dialects/snowflake.py +++ b/sqlglot/dialects/snowflake.py @@ -685,6 +685,7 @@ class Snowflake(Dialect): "WAREHOUSE": TokenType.WAREHOUSE, "STREAMLIT": TokenType.STREAMLIT, } + KEYWORDS.pop("/*+") SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, diff --git a/sqlglot/dialects/sqlite.py b/sqlglot/dialects/sqlite.py index f9e510cb..5b1ed95c 100644 --- a/sqlglot/dialects/sqlite.py +++ b/sqlglot/dialects/sqlite.py @@ -106,6 +106,9 @@ class SQLite(Dialect): IDENTIFIERS = ['"', ("[", "]"), "`"] HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", ""), ("0X", "")] + KEYWORDS = tokens.Tokenizer.KEYWORDS.copy() + KEYWORDS.pop("/*+") + class Parser(parser.Parser): FUNCTIONS = { **parser.Parser.FUNCTIONS, diff --git a/sqlglot/dialects/teradata.py b/sqlglot/dialects/teradata.py index 3aee3cd0..1203e25f 100644 --- a/sqlglot/dialects/teradata.py +++ b/sqlglot/dialects/teradata.py @@ -96,6 +96,7 @@ class Teradata(Dialect): "TOP": TokenType.TOP, "UPD": TokenType.UPDATE, } + KEYWORDS.pop("/*+") # Teradata does not support % as a modulo operator SINGLE_TOKENS = {**tokens.Tokenizer.SINGLE_TOKENS} diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py index f81e7172..74fef24c 100644 --- a/sqlglot/dialects/tsql.py +++ b/sqlglot/dialects/tsql.py @@ -477,6 +477,7 @@ class TSQL(Dialect): "UPDATE STATISTICS": TokenType.COMMAND, "XML": TokenType.XML, } + KEYWORDS.pop("/*+") COMMANDS = {*tokens.Tokenizer.COMMANDS, TokenType.END}
[Postgres/Redshift] - Treat optimizer hints as comments in Postgres/Redshift **Issue**: Postgres doesn't have any support for Optimizer hints. All seemingly-optimizer-hints should be treated as comments. Currently if a comment starts with a `+`, that is assumed as a hint placed out of position and an error is thrown. ```python from sqlglot import parse_one sample_pseudo_hint_sql = "/*+ some comment*/ select b.foo, b.bar from baz b" parse_one(sample_pseudo_hint_sql, read="postgres") #Throws error ``` Expected: Should parse `/*+ some comment*/` as a comment on the statement. Actual: `sqlglot.errors.ParseError: Invalid expression / Unexpected token.` **Official Documentation** This is the best I could find: https://wiki.postgresql.org/wiki/OptimizerHintsDiscussion which describes postgres's stance on optimizer hints. [Mysql](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html) [Doris](https://doris.apache.org/docs/query/join-optimization/join-hint) [StarRocks](https://docs.starrocks.io/docs/administration/Query_planning/#query-hint) [Oracle](https://docs.oracle.com/cd/B13789_01/server.101/b10752/hintsref.htm) [spark sql](https://spark.apache.org/docs/latest/sql-ref-syntax-qry-select-hints.html) [databricks sql](https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-qry-select-hints.html) [Tsql](https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-query?view=sql-server-ver16) are the databases that I could identify to have support for Optimizer hints.
tobymao/sqlglot
diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py index d9d56754..816a283e 100644 --- a/tests/dialects/test_postgres.py +++ b/tests/dialects/test_postgres.py @@ -75,10 +75,6 @@ class TestPostgres(Validator): self.validate_identity("EXEC AS myfunc @id = 123", check_command_warning=True) self.validate_identity("SELECT CURRENT_USER") self.validate_identity("SELECT * FROM ONLY t1") - self.validate_identity( - "SELECT ARRAY[1, 2, 3] <@ ARRAY[1, 2]", - "SELECT ARRAY[1, 2] @> ARRAY[1, 2, 3]", - ) self.validate_identity( """UPDATE "x" SET "y" = CAST('0 days 60.000000 seconds' AS INTERVAL) WHERE "x"."id" IN (2, 3)""" ) @@ -135,6 +131,14 @@ class TestPostgres(Validator): "pg_catalog.PG_TABLE_IS_VISIBLE(c.oid) " "ORDER BY 2, 3" ) + self.validate_identity( + "/*+ some comment*/ SELECT b.foo, b.bar FROM baz AS b", + "/* + some comment */ SELECT b.foo, b.bar FROM baz AS b", + ) + self.validate_identity( + "SELECT ARRAY[1, 2, 3] <@ ARRAY[1, 2]", + "SELECT ARRAY[1, 2] @> ARRAY[1, 2, 3]", + ) self.validate_identity( "SELECT ARRAY[]::INT[] AS foo", "SELECT CAST(ARRAY[] AS INT[]) AS foo",
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 10 }
25.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 identify==2.6.9 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 Pygments==2.19.1 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@806a7e421a9b5a54a2859d7bb4c3ea131a4a8640#egg=sqlglot tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - filelock==3.18.0 - identify==2.6.9 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pre-commit==4.2.0 - pygments==2.19.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/dialects/test_postgres.py::TestPostgres::test_postgres" ]
[]
[ "tests/dialects/test_postgres.py::TestPostgres::test_array_offset", "tests/dialects/test_postgres.py::TestPostgres::test_bool_or", "tests/dialects/test_postgres.py::TestPostgres::test_ddl", "tests/dialects/test_postgres.py::TestPostgres::test_operator", "tests/dialects/test_postgres.py::TestPostgres::test_regexp_binary", "tests/dialects/test_postgres.py::TestPostgres::test_string_concat", "tests/dialects/test_postgres.py::TestPostgres::test_unnest", "tests/dialects/test_postgres.py::TestPostgres::test_unnest_json_array", "tests/dialects/test_postgres.py::TestPostgres::test_variance" ]
[]
MIT License
18,784
1,448
[ "sqlglot/dialects/bigquery.py", "sqlglot/dialects/clickhouse.py", "sqlglot/dialects/drill.py", "sqlglot/dialects/duckdb.py", "sqlglot/dialects/postgres.py", "sqlglot/dialects/presto.py", "sqlglot/dialects/snowflake.py", "sqlglot/dialects/sqlite.py", "sqlglot/dialects/teradata.py", "sqlglot/dialects/tsql.py" ]
qiboteam__qibo-1371
ad50a20734905050782a7feb0378b7430f0ca820
2024-06-24 20:27:40
901b1621cf21a267b7bb0f3044f9e92bc926a1e0
diff --git a/src/qibo/hamiltonians/adiabatic.py b/src/qibo/hamiltonians/adiabatic.py index 4f69be8bf..d436861c2 100644 --- a/src/qibo/hamiltonians/adiabatic.py +++ b/src/qibo/hamiltonians/adiabatic.py @@ -1,4 +1,5 @@ from abc import ABC, abstractmethod +from itertools import chain from qibo.config import raise_error from qibo.hamiltonians import hamiltonians, terms @@ -101,26 +102,6 @@ class BaseAdiabaticHamiltonian: ) -class TrotterCircuit(hamiltonians.TrotterCircuit): - """Object that caches the Trotterized evolution circuit. - - See :class:`qibo.hamiltonians.hamiltonians.TrotterCircuit` for more details. - """ - - def set(self, dt, coefficients): - """Updates the circuit parameters for different values of ``t`` and ``dt``. - - The update is done using the ``circuit.set_parameters`` method to avoid - recreating the circuit and gates. - """ - params = { - gate: group.to_term(coefficients).exp(dt / 2.0) - for gate, group in self.gates.items() - } - self.dt = dt - self.circuit.set_parameters(params) - - class SymbolicAdiabaticHamiltonian(BaseAdiabaticHamiltonian): """Adiabatic Hamiltonian that is sum of :class:`qibo.hamiltonians.hamiltonians.SymbolicHamiltonian`.""" @@ -152,13 +133,21 @@ class SymbolicAdiabaticHamiltonian(BaseAdiabaticHamiltonian): Returns: A :class:`qibo.models.Circuit` implementing the Trotterized evolution. """ - if self.trotter_circuit is None: - self.trotter_circuit = TrotterCircuit( - self.groups, dt, self.nqubits, accelerators - ) + from qibo import Circuit # pylint: disable=import-outside-toplevel + from qibo.hamiltonians.terms import ( # pylint: disable=import-outside-toplevel + TermGroup, + ) + # pylint: disable=E1102 st = self.schedule(t / self.total_time) if t != 0 else 0 # pylint: enable=E1102 coefficients = {self.h0: 1 - st, self.h1: st} - self.trotter_circuit.set(dt, coefficients) - return self.trotter_circuit.circuit + + groups = self.groups + circuit = Circuit(self.nqubits, accelerators=accelerators) + circuit.add( + group.to_term(coefficients).expgate(dt / 2.0) + for group in chain(groups, groups[::-1]) + ) + + return circuit diff --git a/src/qibo/hamiltonians/hamiltonians.py b/src/qibo/hamiltonians/hamiltonians.py index 13366aa10..b270c5d00 100644 --- a/src/qibo/hamiltonians/hamiltonians.py +++ b/src/qibo/hamiltonians/hamiltonians.py @@ -275,43 +275,6 @@ class Hamiltonian(AbstractHamiltonian): ) -class TrotterCircuit: - """Object that caches the Trotterized evolution circuit. - - This object holds a reference to the circuit models and updates its - parameters if a different time step ``dt`` is given without recreating - every gate from scratch. - - Args: - groups (list): List of :class:`qibo.core.terms.TermGroup` objects that - correspond to the Trotter groups of terms in the time evolution - exponential operator. - dt (float): Time step for the Trotterization. - nqubits (int): Number of qubits in the system that evolves. - accelerators (dict): Dictionary with accelerators for distributed - circuits. - """ - - def __init__(self, groups, dt, nqubits, accelerators): - from qibo import Circuit # pylint: disable=import-outside-toplevel - - self.gates = {} - self.dt = dt - self.circuit = Circuit(nqubits, accelerators=accelerators) - for group in chain(groups, groups[::-1]): - gate = group.term.expgate(dt / 2.0) - self.gates[gate] = group - self.circuit.add(gate) - - def set(self, dt): - if self.dt != dt: - params = { - gate: group.term.exp(dt / 2.0) for gate, group in self.gates.items() - } - self.dt = dt - self.circuit.set_parameters(params) - - class SymbolicHamiltonian(AbstractHamiltonian): """Hamiltonian based on a symbolic representation. @@ -350,7 +313,6 @@ class SymbolicHamiltonian(AbstractHamiltonian): self.symbol_map = symbol_map # if a symbol in the given form is not a Qibo symbol it must be # included in the ``symbol_map`` - self.trotter_circuit = None from qibo.symbols import Symbol # pylint: disable=import-outside-toplevel @@ -779,20 +741,24 @@ class SymbolicHamiltonian(AbstractHamiltonian): ) def circuit(self, dt, accelerators=None): - """Circuit that implements a Trotter step of this Hamiltonian - for a given time step ``dt``. + """Circuit that implements a Trotter step of this Hamiltonian. + + Args: + dt (float): Time step used for Trotterization. + accelerators (dict): Dictionary with accelerators for distributed circuits. """ - if self.trotter_circuit is None: - from qibo.hamiltonians.terms import ( # pylint: disable=import-outside-toplevel - TermGroup, - ) + from qibo import Circuit # pylint: disable=import-outside-toplevel + from qibo.hamiltonians.terms import ( # pylint: disable=import-outside-toplevel + TermGroup, + ) - groups = TermGroup.from_terms(self.terms) - self.trotter_circuit = TrotterCircuit( - groups, dt, self.nqubits, accelerators - ) - self.trotter_circuit.set(dt) - return self.trotter_circuit.circuit + groups = TermGroup.from_terms(self.terms) + circuit = Circuit(self.nqubits, accelerators=accelerators) + circuit.add( + group.term.expgate(dt / 2.0) for group in chain(groups, groups[::-1]) + ) + + return circuit class TrotterHamiltonian:
Question about `SymbolicHamiltonian.circuit` I assume it's a bug because it has cost me 2x a couple of days of work to trouble shoot the following issue appearing deep in the `dbi` module code: ```py import numpy as np from copy import deepcopy from qibo import symbols, hamiltonians d = hamiltonians.SymbolicHamiltonian( symbols.Z(0)) a = d.circuit(0.1) b = d.circuit(0.1) print(np.linalg.norm( d.circuit(0.2).unitary() - (a+b).unitary())) a = deepcopy(d).circuit(0.1) b = deepcopy(d).circuit(0.1) print(np.linalg.norm( d.circuit(0.2).unitary() - (a+b).unitary())) ``` Output: ``` 0.28237154359997657 0.0 ``` TLDR: If you assign the return value of `SymbolicHamiltonian.circuit` and then want to use the `Circuit` instance e.g. for further addition then noise comes out. Correct result can be obtained by running on deepcopies.
qiboteam/qibo
diff --git a/tests/test_hamiltonians_trotter.py b/tests/test_hamiltonians_trotter.py index a438a61bd..a69e9c416 100644 --- a/tests/test_hamiltonians_trotter.py +++ b/tests/test_hamiltonians_trotter.py @@ -3,7 +3,7 @@ import numpy as np import pytest -from qibo import hamiltonians +from qibo import hamiltonians, symbols from qibo.backends import NumpyBackend from qibo.quantum_info import random_hermitian, random_statevector @@ -143,6 +143,16 @@ def test_trotter_hamiltonian_three_qubit_term(backend): backend.assert_allclose(final_state, target_state) +def test_symbolic_hamiltonian_circuit_different_dts(backend): + """Issue: https://github.com/qiboteam/qibo/issues/1357.""" + ham = hamiltonians.SymbolicHamiltonian(symbols.Z(0)) + a = ham.circuit(0.1) + b = ham.circuit(0.1) + matrix1 = ham.circuit(0.2).unitary(backend) + matrix2 = (a + b).unitary(backend) + np.testing.assert_allclose(matrix1, matrix2) + + def test_old_trotter_hamiltonian_errors(): """Check errors when creating the deprecated ``TrotterHamiltonian`` object.""" with pytest.raises(NotImplementedError):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
antlr4-python3-runtime==4.13.2 cloudpickle==3.1.1 cma==3.4.0 coverage==7.8.0 exceptiongroup==1.2.2 execnet==2.1.1 future==1.0.0 hyperopt==0.2.7 importlib_metadata==8.6.1 iniconfig==2.1.0 joblib==1.4.2 mpmath==1.3.0 networkx==3.2.1 numpy==1.26.4 openqasm3==1.0.1 packaging==24.2 pluggy==1.5.0 py4j==0.10.9.9 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 -e git+https://github.com/qiboteam/qibo.git@ad50a20734905050782a7feb0378b7430f0ca820#egg=qibo scipy==1.13.1 six==1.17.0 sympy==1.13.3 tabulate==0.9.0 tomli==2.2.1 tqdm==4.67.1 typing_extensions==4.13.0 zipp==3.21.0
name: qibo channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - antlr4-python3-runtime==4.13.2 - cloudpickle==3.1.1 - cma==3.4.0 - coverage==7.8.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - future==1.0.0 - hyperopt==0.2.7 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - joblib==1.4.2 - mpmath==1.3.0 - networkx==3.2.1 - numpy==1.26.4 - openqasm3==1.0.1 - packaging==24.2 - pluggy==1.5.0 - py4j==0.10.9.9 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - qibo==0.2.9 - scipy==1.13.1 - setuptools==69.5.1 - six==1.17.0 - sympy==1.13.3 - tabulate==0.9.0 - tomli==2.2.1 - tqdm==4.67.1 - typing-extensions==4.13.0 - zipp==3.21.0 prefix: /opt/conda/envs/qibo
[ "tests/test_hamiltonians_trotter.py::test_symbolic_hamiltonian_circuit_different_dts[numpy]" ]
[]
[ "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_to_dense[numpy-TFIM-3]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_to_dense[numpy-TFIM-4]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_to_dense[numpy-XXZ-3]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_to_dense[numpy-XXZ-4]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_to_dense[numpy-Y-3]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_to_dense[numpy-Y-4]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_to_dense[numpy-MaxCut-3]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_to_dense[numpy-MaxCut-4]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_scalar_mul[numpy]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_scalar_add[numpy]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_scalar_sub[numpy]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_operator_add_and_sub[numpy]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_matmul[numpy-3-False]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_matmul[numpy-4-False]", "tests/test_hamiltonians_trotter.py::test_trotter_hamiltonian_three_qubit_term[numpy]", "tests/test_hamiltonians_trotter.py::test_old_trotter_hamiltonian_errors" ]
[]
Apache License 2.0
18,787
1,609
[ "src/qibo/hamiltonians/adiabatic.py", "src/qibo/hamiltonians/hamiltonians.py" ]
tobymao__sqlglot-3699
3fba6035ac0263beab73ab62013a64a56dea9165
2024-06-25 10:35:48
3b8568d37792c1916f05faf5df8af1841144b338
diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py index 4f557e7b..f21ba38c 100644 --- a/sqlglot/dialects/bigquery.py +++ b/sqlglot/dialects/bigquery.py @@ -221,6 +221,7 @@ class BigQuery(Dialect): SUPPORTS_SEMI_ANTI_JOIN = False LOG_BASE_FIRST = False HEX_LOWERCASE = True + FORCE_EARLY_ALIAS_REF_EXPANSION = True # https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#case_sensitivity NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py index 209a2894..c0767753 100644 --- a/sqlglot/dialects/clickhouse.py +++ b/sqlglot/dialects/clickhouse.py @@ -102,6 +102,7 @@ class ClickHouse(Dialect): SUPPORTS_USER_DEFINED_TYPES = False SAFE_DIVISION = True LOG_BASE_FIRST: t.Optional[bool] = None + FORCE_EARLY_ALIAS_REF_EXPANSION = True UNESCAPED_SEQUENCES = { "\\0": "\0", diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py index 32d621a9..fca4d94c 100644 --- a/sqlglot/dialects/dialect.py +++ b/sqlglot/dialects/dialect.py @@ -325,6 +325,32 @@ class Dialect(metaclass=_Dialect): Whether COPY statement parameters are separated by comma or whitespace """ + FORCE_EARLY_ALIAS_REF_EXPANSION = False + """ + Whether alias reference expansion (_expand_alias_refs()) should run before column qualification (_qualify_columns()). + + For example: + WITH data AS ( + SELECT + 1 AS id, + 2 AS my_id + ) + SELECT + id AS my_id + FROM + data + WHERE + my_id = 1 + GROUP BY + my_id, + HAVING + my_id = 1 + + In most dialects "my_id" would refer to "data.my_id" (which is done in _qualify_columns()) across the query, except: + - BigQuery, which will forward the alias to GROUP BY + HAVING clauses i.e it resolves to "WHERE my_id = 1 GROUP BY id HAVING id = 1" + - Clickhouse, which will forward the alias across the query i.e it resolves to "WHERE id = 1 GROUP BY id HAVING id = 1" + """ + # --- Autofilled --- tokenizer_class = Tokenizer diff --git a/sqlglot/optimizer/qualify_columns.py b/sqlglot/optimizer/qualify_columns.py index 6ef982f7..93b87c7a 100644 --- a/sqlglot/optimizer/qualify_columns.py +++ b/sqlglot/optimizer/qualify_columns.py @@ -60,8 +60,8 @@ def qualify_columns( _pop_table_column_aliases(scope.derived_tables) using_column_tables = _expand_using(scope, resolver) - if schema.empty and expand_alias_refs: - _expand_alias_refs(scope, resolver) + if (schema.empty or dialect.FORCE_EARLY_ALIAS_REF_EXPANSION) and expand_alias_refs: + _expand_alias_refs(scope, resolver, expand_only_groupby=(dialect == "bigquery")) _convert_columns_to_dots(scope, resolver) _qualify_columns(scope, resolver) @@ -208,7 +208,7 @@ def _expand_using(scope: Scope, resolver: Resolver) -> t.Dict[str, t.Any]: return column_tables -def _expand_alias_refs(scope: Scope, resolver: Resolver) -> None: +def _expand_alias_refs(scope: Scope, resolver: Resolver, expand_only_groupby: bool = False) -> None: expression = scope.expression if not isinstance(expression, exp.Select): @@ -219,7 +219,7 @@ def _expand_alias_refs(scope: Scope, resolver: Resolver) -> None: def replace_columns( node: t.Optional[exp.Expression], resolve_table: bool = False, literal_index: bool = False ) -> None: - if not node: + if not node or (expand_only_groupby and not isinstance(node, exp.Group)): return for column in walk_in_scope(node, prune=lambda node: node.is_star):
wrong qualify_columns on generated columns **Before you file an issue** - Make sure you specify the "read" dialect eg. `parse_one(sql, read="spark")`: Done - Make sure you specify the "write" dialect eg. `ast.sql(dialect="duckdb")`: Done - Check if the issue still exists on main: still exist **Fully reproducible code snippet** Prepare data: ```python from sqlglot import parse_one, exp from sqlglot.optimizer.qualify_columns import qualify_columns sql ="""with data as ( select 1 as id, 2 as my_id, 'a' as name, 'de' as full_name ) select id as my_id, concat(id, name) as full_name from data group by my_id, full_name""" schema = { "catalog": { "schema1": { "customer": { "id": "INTEGER", }, } } } ``` Transpiler from bigquery to trino: ```python smt = parse_one(sql, read="bigquery") print(qualify_columns(smt, schema=schema).sql(dialect="trino", pretty=True)) ``` Output: ```sql WITH data AS ( SELECT 1 AS id, 2 AS my_id, 'a' AS name, 'de' AS full_name ) SELECT data.id AS my_id, CONCAT(CAST(data.id AS VARCHAR), CAST(data.name AS VARCHAR)) AS full_name FROM data GROUP BY data.my_id, data.full_name ``` The problem of the output is it can not be run on trino, because `data.id` and `data.name` is not an aggregate expression or appear in GROUP BY clause. Additional test: The output will expand correctly if we no not provide schema: ```python smt = parse_one(sql, read="bigquery") print(qualify_columns(smt, schema=None).sql(dialect="trino", pretty=True)) """ WITH data AS ( SELECT 1 AS id, 2 AS my_id, 'a' AS name, 'de' AS full_name ) SELECT data.id AS my_id, CONCAT(CAST(data.id AS VARCHAR), CAST(data.name AS VARCHAR)) AS full_name FROM data GROUP BY data.id, CONCAT(CAST(data.id AS VARCHAR), CAST(data.name AS VARCHAR)) """ ``` The output will break again if I disable expand_alias_ref: ```python smt = parse_one(sql, read="bigquery") print(qualify_columns(smt, schema=None, expand_alias_refs=False).sql(dialect="trino", pretty=True)) ``` ### Solution I have made a patch to fix my case, but I think we can have better solution to fix this. https://github.com/viplazylmht/sqlglot/blob/644bf67720442f964ffc4606693dcfc1b87ec6e6/sqlglot/optimizer/qualify_columns.py#L423-L431 **Official Documentation** Please include links to official SQL documentation related to your issue.
tobymao/sqlglot
diff --git a/tests/test_optimizer.py b/tests/test_optimizer.py index 81b9731b..b1d50942 100644 --- a/tests/test_optimizer.py +++ b/tests/test_optimizer.py @@ -473,15 +473,35 @@ SELECT :with,WITH :expressions,CTE :this,UNION :this,SELECT :expressions,1,:expr 'SELECT "x"."a" + 1 AS "d", "x"."a" + 1 + 1 AS "e" FROM "x" AS "x" WHERE ("x"."a" + 2) > 1 GROUP BY "x"."a" + 1 + 1', ) + unused_schema = {"l": {"c": "int"}} self.assertEqual( optimizer.qualify_columns.qualify_columns( parse_one("SELECT CAST(x AS INT) AS y FROM z AS z"), - schema={"l": {"c": "int"}}, + schema=unused_schema, infer_schema=False, ).sql(), "SELECT CAST(x AS INT) AS y FROM z AS z", ) + # BigQuery expands overlapping alias only for GROUP BY + HAVING + sql = "WITH data AS (SELECT 1 AS id, 2 AS my_id, 'a' AS name, 'b' AS full_name) SELECT id AS my_id, CONCAT(id, name) AS full_name FROM data WHERE my_id = 1 GROUP BY my_id, full_name HAVING my_id = 1" + self.assertEqual( + optimizer.qualify_columns.qualify_columns( + parse_one(sql, dialect="bigquery"), + schema=MappingSchema(schema=unused_schema, dialect="bigquery"), + ).sql(), + "WITH data AS (SELECT 1 AS id, 2 AS my_id, 'a' AS name, 'b' AS full_name) SELECT data.id AS my_id, CONCAT(data.id, data.name) AS full_name FROM data WHERE data.my_id = 1 GROUP BY data.id, CONCAT(data.id, data.name) HAVING data.id = 1", + ) + + # Clickhouse expands overlapping alias across the entire query + self.assertEqual( + optimizer.qualify_columns.qualify_columns( + parse_one(sql, dialect="clickhouse"), + schema=MappingSchema(schema=unused_schema, dialect="clickhouse"), + ).sql(), + "WITH data AS (SELECT 1 AS id, 2 AS my_id, 'a' AS name, 'b' AS full_name) SELECT data.id AS my_id, CONCAT(data.id, data.name) AS full_name FROM data WHERE data.id = 1 GROUP BY data.id, CONCAT(data.id, data.name) HAVING data.id = 1", + ) + def test_optimize_joins(self): self.check_file( "optimize_joins",
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 4 }
25.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 duckdb==1.2.1 exceptiongroup==1.2.2 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 maturin==1.8.3 mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pandas-stubs==2.2.2.240807 pdoc==15.0.1 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 Pygments==2.19.1 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 ruff==0.4.3 six==1.17.0 -e git+https://github.com/tobymao/sqlglot.git@3fba6035ac0263beab73ab62013a64a56dea9165#egg=sqlglot tomli==2.2.1 types-python-dateutil==2.9.0.20241206 types-pytz==2025.2.0.20250326 typing_extensions==4.13.0 tzdata==2025.2 virtualenv==20.29.3
name: sqlglot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - duckdb==1.2.1 - exceptiongroup==1.2.2 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - maturin==1.8.3 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pandas-stubs==2.2.2.240807 - pdoc==15.0.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pygments==2.19.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - ruff==0.4.3 - six==1.17.0 - tomli==2.2.1 - types-python-dateutil==2.9.0.20241206 - types-pytz==2025.2.0.20250326 - typing-extensions==4.13.0 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/sqlglot
[ "tests/test_optimizer.py::TestOptimizer::test_expand_alias_refs" ]
[]
[ "tests/test_optimizer.py::TestOptimizer::test_aggfunc_annotation", "tests/test_optimizer.py::TestOptimizer::test_annotate_types", "tests/test_optimizer.py::TestOptimizer::test_binary_annotation", "tests/test_optimizer.py::TestOptimizer::test_bracket_annotation", "tests/test_optimizer.py::TestOptimizer::test_cache_annotation", "tests/test_optimizer.py::TestOptimizer::test_canonicalize", "tests/test_optimizer.py::TestOptimizer::test_cast_type_annotation", "tests/test_optimizer.py::TestOptimizer::test_concat_annotation", "tests/test_optimizer.py::TestOptimizer::test_cte_column_annotation", "tests/test_optimizer.py::TestOptimizer::test_derived_tables_column_annotation", "tests/test_optimizer.py::TestOptimizer::test_eliminate_ctes", "tests/test_optimizer.py::TestOptimizer::test_eliminate_joins", "tests/test_optimizer.py::TestOptimizer::test_eliminate_subqueries", "tests/test_optimizer.py::TestOptimizer::test_file_schema", "tests/test_optimizer.py::TestOptimizer::test_function_annotation", "tests/test_optimizer.py::TestOptimizer::test_interval_math_annotation", "tests/test_optimizer.py::TestOptimizer::test_isolate_table_selects", "tests/test_optimizer.py::TestOptimizer::test_lateral_annotation", "tests/test_optimizer.py::TestOptimizer::test_map_annotation", "tests/test_optimizer.py::TestOptimizer::test_merge_subqueries", "tests/test_optimizer.py::TestOptimizer::test_nested_type_annotation", "tests/test_optimizer.py::TestOptimizer::test_no_pseudocolumn_expansion", "tests/test_optimizer.py::TestOptimizer::test_normalization_distance", "tests/test_optimizer.py::TestOptimizer::test_normalize", "tests/test_optimizer.py::TestOptimizer::test_normalize_identifiers", "tests/test_optimizer.py::TestOptimizer::test_null_annotation", "tests/test_optimizer.py::TestOptimizer::test_nullable_annotation", "tests/test_optimizer.py::TestOptimizer::test_optimize", "tests/test_optimizer.py::TestOptimizer::test_optimize_joins", "tests/test_optimizer.py::TestOptimizer::test_predicate_annotation", "tests/test_optimizer.py::TestOptimizer::test_pushdown_cte_alias_columns", "tests/test_optimizer.py::TestOptimizer::test_pushdown_predicates", "tests/test_optimizer.py::TestOptimizer::test_pushdown_projection", "tests/test_optimizer.py::TestOptimizer::test_qualify_columns", "tests/test_optimizer.py::TestOptimizer::test_qualify_columns__invalid", "tests/test_optimizer.py::TestOptimizer::test_qualify_columns__with_invisible", "tests/test_optimizer.py::TestOptimizer::test_qualify_tables", "tests/test_optimizer.py::TestOptimizer::test_quote_identifiers", "tests/test_optimizer.py::TestOptimizer::test_quotes", "tests/test_optimizer.py::TestOptimizer::test_recursive_cte", "tests/test_optimizer.py::TestOptimizer::test_root_subquery_annotation", "tests/test_optimizer.py::TestOptimizer::test_schema_with_spaces", "tests/test_optimizer.py::TestOptimizer::test_scope", "tests/test_optimizer.py::TestOptimizer::test_scope_warning", "tests/test_optimizer.py::TestOptimizer::test_semistructured", "tests/test_optimizer.py::TestOptimizer::test_simplify", "tests/test_optimizer.py::TestOptimizer::test_tpcds", "tests/test_optimizer.py::TestOptimizer::test_tpch", "tests/test_optimizer.py::TestOptimizer::test_type_annotation_cache", "tests/test_optimizer.py::TestOptimizer::test_typeddiv_annotation", "tests/test_optimizer.py::TestOptimizer::test_unknown_annotation", "tests/test_optimizer.py::TestOptimizer::test_unnest_annotation", "tests/test_optimizer.py::TestOptimizer::test_unnest_subqueries", "tests/test_optimizer.py::TestOptimizer::test_user_defined_type_annotation" ]
[]
MIT License
18,790
1,110
[ "sqlglot/dialects/bigquery.py", "sqlglot/dialects/clickhouse.py", "sqlglot/dialects/dialect.py", "sqlglot/optimizer/qualify_columns.py" ]
google__flax-4029
3b21870822bd2a6d880194799b749bb69534769f
2024-06-26 00:14:58
5694517f6fc3201fbf490a797a4d6ce44a35528b
diff --git a/flax/linen/attention.py b/flax/linen/attention.py index b7e9de6c..6e91be99 100644 --- a/flax/linen/attention.py +++ b/flax/linen/attention.py @@ -16,6 +16,7 @@ from __future__ import annotations import functools +import inspect import warnings from typing import Any, Callable, Optional, Union, overload @@ -574,33 +575,28 @@ class MultiHeadDotProductAttention(Module): m_deterministic = True # apply attention + attn_args = (query, key, value) + # This kwargs list match the default nn.dot_product_attention. + # For custom `attention_fn`s, invalid kwargs will be filtered. + attn_kwargs = dict( + mask=mask, + dropout_rng=dropout_rng, + dropout_rate=self.dropout_rate, + broadcast_dropout=self.broadcast_dropout, + deterministic=m_deterministic, + dtype=self.dtype, + precision=self.precision, + force_fp32_for_softmax=self.force_fp32_for_softmax, + ) + attn_kwargs = { + k: v + for k, v in attn_kwargs.items() + if k in inspect.signature(self.attention_fn).parameters + } if sow_weights: - x = self.attention_fn( - query, - key, - value, - mask=mask, - dropout_rng=dropout_rng, - dropout_rate=self.dropout_rate, - broadcast_dropout=self.broadcast_dropout, - deterministic=m_deterministic, - dtype=self.dtype, - precision=self.precision, - module=self, - ) # pytype: disable=wrong-keyword-args + x = self.attention_fn(*attn_args, **attn_kwargs, module=self) else: - x = self.attention_fn( - query, - key, - value, - mask=mask, - dropout_rng=dropout_rng, - dropout_rate=self.dropout_rate, - broadcast_dropout=self.broadcast_dropout, - deterministic=m_deterministic, - dtype=self.dtype, - precision=self.precision, - ) + x = self.attention_fn(*attn_args, **attn_kwargs) # back to the original inputs dimensions out = DenseGeneral( features=features,
Force `fp32` in `attention.MultiHeadDotProductAttention` for softmax operator Hi, As I was trying to implement mixed precision training under Flax for my project, I noticed that the `force_fp32_for_softmax` flag defined in `attention.MultiHeadDotProductAttention` does not get to pass into `dot_product_attention` (the default attention function). <img width="464" alt="Screenshot 2024-06-18 at 11 18 38 PM" src="https://github.com/google/flax/assets/90777911/81ee2c74-2dc9-4fd7-a76c-2d9c921df8ff"> <img width="461" alt="Screenshot 2024-06-18 at 11 17 55 PM" src="https://github.com/google/flax/assets/90777911/93d2c348-3837-4fa4-b74d-30778c7e16f6"> <img width="441" alt="Screenshot 2024-06-18 at 11 19 21 PM" src="https://github.com/google/flax/assets/90777911/b2daa7c9-45ef-41ca-aa2d-db594484dd35"> I think this might lead to loose control over the softmax operator and result in some stability issues under `bf16` or `fp16` precision, so I wonder if there's an alternate? Thanks!
google/flax
diff --git a/tests/linen/linen_attention_test.py b/tests/linen/linen_attention_test.py index 7dd07878..e7d69a43 100644 --- a/tests/linen/linen_attention_test.py +++ b/tests/linen/linen_attention_test.py @@ -14,7 +14,6 @@ """Tests for flax.linen.attention.""" -import functools from absl.testing import absltest, parameterized from flax import errors, jax_utils from flax import linen as nn @@ -565,9 +564,7 @@ class AttentionTest(parameterized.TestCase): qkv_features=4, kernel_init=initializers.lecun_normal(), bias_init=initializers.uniform(), - attention_fn=functools.partial( - nn.dot_product_attention, force_fp32_for_softmax=force_fp32 - ), + force_fp32_for_softmax=force_fp32, deterministic=False, dtype=jnp.bfloat16, )
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
absl-py==2.2.1 accessible-pygments==0.0.5 alabaster==0.7.16 array_record==0.5.1 asttokens==3.0.0 astunparse==1.6.3 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 certifi==2025.1.31 charset-normalizer==3.4.1 chex==0.1.89 click==8.1.8 comm==0.2.2 commonmark==0.9.1 contextlib2==21.6.0 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 dm-haiku==0.0.13 dm-tree==0.1.8 docutils==0.16 einops==0.8.1 etils==1.5.2 exceptiongroup==1.2.2 execnet==2.1.1 executing==2.2.0 fastjsonschema==2.21.1 flatbuffers==25.2.10 -e git+https://github.com/google/flax.git@3b21870822bd2a6d880194799b749bb69534769f#egg=flax fonttools==4.56.0 fsspec==2025.3.1 gast==0.6.0 google-pasta==0.2.0 greenlet==3.1.1 grpcio==1.71.0 h5py==3.13.0 humanize==4.12.2 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipython==8.18.1 ipython-genutils==0.2.0 jax==0.4.30 jaxlib==0.4.30 jedi==0.19.2 Jinja2==3.1.6 jmp==0.0.4 joblib==1.4.2 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-cache==1.0.1 jupyter_client==8.6.3 jupyter_core==5.7.2 jupytext==1.13.8 keras==3.9.1 kiwisolver==1.4.7 libclang==18.1.1 Markdown==3.7 markdown-it-py==2.2.0 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mdit-py-plugins==0.3.5 mdurl==0.1.2 ml_collections==0.1.1 ml_dtypes==0.5.1 msgpack==1.1.0 myst-nb==1.2.0 myst-parser==1.0.0 namex==0.0.8 nbclient==0.10.2 nbformat==5.10.4 nest-asyncio==1.6.0 numpy==2.0.2 opt_einsum==3.4.0 optax==0.2.4 optree==0.14.1 orbax-checkpoint==0.6.4 packaging==24.2 parso==0.8.4 pexpect==4.9.0 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 promise==2.3 prompt_toolkit==3.0.50 protobuf==3.20.3 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pydata-sphinx-theme==0.15.4 Pygments==2.19.1 pyparsing==3.2.3 pytest==8.3.5 pytest-cov==6.0.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 PyYAML==6.0.2 pyzmq==26.3.0 recommonmark==0.7.1 referencing==0.36.2 requests==2.32.3 rich==14.0.0 rpds-py==0.24.0 scikit-learn==1.6.1 scipy==1.13.1 six==1.17.0 snowballstemmer==2.2.0 soupsieve==2.6 Sphinx==5.3.0 sphinx-book-theme==1.1.3 sphinx_design==0.6.0 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 SQLAlchemy==2.0.40 stack-data==0.6.3 swebench_matterhorn @ file:///swebench_matterhorn tabulate==0.9.0 tensorboard==2.18.0 tensorboard-data-server==0.7.2 tensorflow==2.18.1 tensorflow-datasets==4.9.3 tensorflow-io-gcs-filesystem==0.37.1 tensorflow-metadata==1.16.1 tensorflow-text==2.18.1 tensorstore==0.1.69 termcolor==3.0.0 threadpoolctl==3.6.0 toml==0.10.2 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 typing_extensions==4.13.0 urllib3==2.3.0 wcwidth==0.2.13 Werkzeug==3.1.3 wrapt==1.17.2 zipp==3.21.0
name: flax channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - absl-py==2.2.1 - accessible-pygments==0.0.5 - alabaster==0.7.16 - array-record==0.5.1 - asttokens==3.0.0 - astunparse==1.6.3 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - certifi==2025.1.31 - charset-normalizer==3.4.1 - chex==0.1.89 - click==8.1.8 - comm==0.2.2 - commonmark==0.9.1 - contextlib2==21.6.0 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - dm-haiku==0.0.13 - dm-tree==0.1.8 - docutils==0.16 - einops==0.8.1 - etils==1.5.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - executing==2.2.0 - fastjsonschema==2.21.1 - flatbuffers==25.2.10 - flax==0.8.5 - fonttools==4.56.0 - fsspec==2025.3.1 - gast==0.6.0 - google-pasta==0.2.0 - greenlet==3.1.1 - grpcio==1.71.0 - h5py==3.13.0 - humanize==4.12.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipython==8.18.1 - ipython-genutils==0.2.0 - jax==0.4.30 - jaxlib==0.4.30 - jedi==0.19.2 - jinja2==3.1.6 - jmp==0.0.4 - joblib==1.4.2 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-cache==1.0.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupytext==1.13.8 - keras==3.9.1 - kiwisolver==1.4.7 - libclang==18.1.1 - markdown==3.7 - markdown-it-py==2.2.0 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mdit-py-plugins==0.3.5 - mdurl==0.1.2 - ml-collections==0.1.1 - ml-dtypes==0.5.1 - msgpack==1.1.0 - myst-nb==1.2.0 - myst-parser==1.0.0 - namex==0.0.8 - nbclient==0.10.2 - nbformat==5.10.4 - nest-asyncio==1.6.0 - numpy==2.0.2 - opt-einsum==3.4.0 - optax==0.2.4 - optree==0.14.1 - orbax-checkpoint==0.6.4 - packaging==24.2 - parso==0.8.4 - pexpect==4.9.0 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - promise==2.3 - prompt-toolkit==3.0.50 - protobuf==3.20.3 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pydata-sphinx-theme==0.15.4 - pygments==2.19.1 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - pyzmq==26.3.0 - recommonmark==0.7.1 - referencing==0.36.2 - requests==2.32.3 - rich==14.0.0 - rpds-py==0.24.0 - scikit-learn==1.6.1 - scipy==1.13.1 - six==1.17.0 - snowballstemmer==2.2.0 - soupsieve==2.6 - sphinx==5.3.0 - sphinx-book-theme==1.1.3 - sphinx-design==0.6.0 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - sqlalchemy==2.0.40 - stack-data==0.6.3 - swebench-matterhorn==0.0.0 - tabulate==0.9.0 - tensorboard==2.18.0 - tensorboard-data-server==0.7.2 - tensorflow==2.18.1 - tensorflow-datasets==4.9.3 - tensorflow-io-gcs-filesystem==0.37.1 - tensorflow-metadata==1.16.1 - tensorflow-text==2.18.1 - tensorstore==0.1.69 - termcolor==3.0.0 - threadpoolctl==3.6.0 - toml==0.10.2 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - typing-extensions==4.13.0 - urllib3==2.3.0 - wcwidth==0.2.13 - werkzeug==3.1.3 - wrapt==1.17.2 - zipp==3.21.0 prefix: /opt/conda/envs/flax
[ "tests/linen/linen_attention_test.py::AttentionTest::test_mixed_precision_multihead_attention0" ]
[]
[ "tests/linen/linen_attention_test.py::AttentionTest::test_attention_alias_equivalence", "tests/linen/linen_attention_test.py::AttentionTest::test_attention_alias_submodule", "tests/linen/linen_attention_test.py::AttentionTest::test_autoregresive_receptive_field_1d", "tests/linen/linen_attention_test.py::AttentionTest::test_autoregressive_decode_with_x64", "tests/linen/linen_attention_test.py::AttentionTest::test_causal_mask_1d", "tests/linen/linen_attention_test.py::AttentionTest::test_decoding0", "tests/linen/linen_attention_test.py::AttentionTest::test_decoding1", "tests/linen/linen_attention_test.py::AttentionTest::test_dtype_infer", "tests/linen/linen_attention_test.py::AttentionTest::test_mha_out_initializers", "tests/linen/linen_attention_test.py::AttentionTest::test_mixed_precision_multihead_attention1", "tests/linen/linen_attention_test.py::AttentionTest::test_multihead_encoder_decoder_attention", "tests/linen/linen_attention_test.py::AttentionTest::test_multihead_kv_args", "tests/linen/linen_attention_test.py::AttentionTest::test_multihead_mask_warning", "tests/linen/linen_attention_test.py::AttentionTest::test_multihead_self_attention", "tests/linen/linen_attention_test.py::AttentionTest::test_multihead_self_attention_explicit_dropout", "tests/linen/linen_attention_test.py::AttentionTest::test_multihead_self_attention_w_dropout", "tests/linen/linen_attention_test.py::AttentionTest::test_multihead_self_attention_w_dropout_disabled", "tests/linen/linen_attention_test.py::AttentionTest::test_multihead_sow_attention_weights" ]
[]
Apache License 2.0
18,801
538
[ "flax/linen/attention.py" ]
yukinarit__pyserde-565
d87205b851a792583cd05f060ba9a0f10a66e109
2024-06-26 13:54:15
0587025a1b205e649bff0ceb22a91f64c9dafdbf
diff --git a/serde/compat.py b/serde/compat.py index 2b3ccb9..77b15bf 100644 --- a/serde/compat.py +++ b/serde/compat.py @@ -214,7 +214,7 @@ def typename(typ: Any, with_typing_module: bool = False) -> str: args = type_args(typ) if not args: raise TypeError("Literal type requires at least one literal argument") - return f'Literal[{", ".join(str(e) for e in args)}]' + return f'Literal[{", ".join(stringify_literal(e) for e in args)}]' elif typ is Any: return f"{mod}Any" elif is_ellipsis(typ): @@ -236,6 +236,13 @@ def typename(typ: Any, with_typing_module: bool = False) -> str: raise SerdeError(f"Could not get a type name from: {typ}") +def stringify_literal(v: Any) -> str: + if isinstance(v, str): + return f"'{v}'" + else: + return str(v) + + def type_args(typ: Any) -> tuple[type[Any], ...]: """ Wrapper to suppress type error for accessing private members. diff --git a/serde/de.py b/serde/de.py index e51458c..6356bfd 100644 --- a/serde/de.py +++ b/serde/de.py @@ -13,6 +13,7 @@ import typing import jinja2 from collections.abc import Callable, Sequence, Iterable from beartype import beartype, BeartypeConf +from beartype.door import is_bearable from beartype.roar import BeartypeCallHintParamViolation from dataclasses import dataclass, is_dataclass from typing import overload, TypeVar, Generic, Any, Optional, Union, Literal @@ -263,6 +264,7 @@ def deserialize( g["_get_by_aliases"] = _get_by_aliases g["class_deserializers"] = class_deserializers g["BeartypeCallHintParamViolation"] = BeartypeCallHintParamViolation + g["is_bearable"] = is_bearable if deserializer: g["serde_legacy_custom_class_deserializer"] = functools.partial( serde_legacy_custom_class_deserializer, custom=deserializer @@ -1158,9 +1160,11 @@ def {{func}}(cls=cls, maybe_generic=None, maybe_generic_type_vars=None, data=Non if not isinstance(fake_dict["fake_key"], {{typename(t)}}): raise Exception("Not a type of {{typename(t)}}") {% endif %} - return {{rvalue(arg(t))}} + res = {{rvalue(arg(t))}} + ensure(is_bearable(res, {{typename(t)}}), "object is not of type '{{typename(t)}}'") + return res except Exception as e: - errors.append(f' Failed to deserialize into {{typename(t)}}: {e}') + errors.append(f" Failed to deserialize into {{typename(t)}}: {e}") {% endfor %} raise SerdeError("Can not deserialize " + repr(data) + " of type " + \ typename(type(data)) + " into {{union_name}}.\\nReasons:\\n" + "\\n".join(errors))
Incorrect deserialization when deserializing a Union[list, object] Code to reproduce: ```python import serde from dataclasses import dataclass @serde.serde @dataclass class A: a: int @serde.serde(tagging=serde.InternalTagging('type')) @dataclass class B: x: list[int] | A o = B(x=A(a=1)) serde.json.from_json(B, serde.json.to_json(o)) ``` Expect: `B(x=A(a=1))` Output: `B(x=['a', 'type'])`
yukinarit/pyserde
diff --git a/tests/test_compat.py b/tests/test_compat.py index a1fd888..265f197 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -83,7 +83,7 @@ def test_typename() -> None: assert typename(dict[str, Foo]) == "dict[str, Foo]" # type: ignore assert typename(set) == "set" assert typename(set[int]) == "set[int]" - assert typename(Literal[1, True, "Hey"]) == "Literal[1, True, Hey]" + assert typename(Literal[1, True, "Hey"]) == "Literal[1, True, 'Hey']" def test_iter_types() -> None: diff --git a/tests/test_union.py b/tests/test_union.py index 75fa80d..04edf35 100644 --- a/tests/test_union.py +++ b/tests/test_union.py @@ -822,3 +822,19 @@ def test_union_with_different_ordering() -> None: s = '{"a":"1","b":{"Expr":{"expr":"2"}},"c":"3"}' assert s == to_json(f) assert f == from_json(Foo, s) + + +def test_union_internal_tagging_for_non_dataclass() -> None: + @serde + class Bar: + a: int + + @serde(tagging=InternalTagging("type")) + class Foo: + x: Union[list[int], Bar] + + f = Foo(Bar(1)) + assert f == from_json(Foo, to_json(f)) + + f = Foo([10]) + assert f == from_json(Foo, to_json(f))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
0.19
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
beartype==0.20.2 casefy==1.1.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work greenlet==3.1.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 msgpack==1.1.0 mypy-extensions==1.0.0 numpy==1.26.4 orjson==3.10.16 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work plum-dispatch==2.2.2 -e git+https://github.com/yukinarit/pyserde.git@d87205b851a792583cd05f060ba9a0f10a66e109#egg=pyserde pytest @ file:///croot/pytest_1738938843180/work PyYAML==6.0.2 SQLAlchemy==2.0.40 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tomli_w==1.2.0 typing-inspect==0.9.0 typing_extensions==4.13.0
name: pyserde channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - beartype==0.20.2 - casefy==1.1.0 - greenlet==3.1.1 - jinja2==3.1.6 - markupsafe==3.0.2 - msgpack==1.1.0 - mypy-extensions==1.0.0 - numpy==1.26.4 - orjson==3.10.16 - plum-dispatch==2.2.2 - pyserde==0.19.1.post6.dev0+d87205b - pyyaml==6.0.2 - sqlalchemy==2.0.40 - tomli-w==1.2.0 - typing-extensions==4.13.0 - typing-inspect==0.9.0 prefix: /opt/conda/envs/pyserde
[ "tests/test_compat.py::test_typename", "tests/test_union.py::test_union_internal_tagging_for_non_dataclass" ]
[]
[ "tests/test_compat.py::test_types", "tests/test_compat.py::test_iter_types", "tests/test_compat.py::test_iter_unions", "tests/test_compat.py::test_type_args", "tests/test_compat.py::test_union_args", "tests/test_compat.py::test_is_instance", "tests/test_compat.py::test_is_generic", "tests/test_compat.py::test_get_generic_arg", "tests/test_union.py::test_union", "tests/test_union.py::test_union_optional", "tests/test_union.py::test_union_containers", "tests/test_union.py::test_union_with_literal", "tests/test_union.py::test_union_with_complex_types", "tests/test_union.py::test_union_with_complex_types_and_reuse_instances", "tests/test_union.py::test_optional_union_with_complex_types", "tests/test_union.py::test_optional_complex_type_with_default", "tests/test_union.py::test_union_with_complex_types_in_containers", "tests/test_union.py::test_union_exception_if_nothing_matches", "tests/test_union.py::test_union_in_union", "tests/test_union.py::test_union_in_other_type", "tests/test_union.py::test_union_rename_all", "tests/test_union.py::test_union_with_list_of_other_class", "tests/test_union.py::test_union_with_union_in_nested_types", "tests/test_union.py::test_union_with_union_in_nested_tuple", "tests/test_union.py::test_generic_union", "tests/test_union.py::test_external_tagging", "tests/test_union.py::test_internal_tagging", "tests/test_union.py::test_adjacent_tagging", "tests/test_union.py::test_untagged", "tests/test_union.py::test_newtype_and_untagged_union", "tests/test_union.py::test_union_directly", "tests/test_union.py::test_union_frozenset_with_prim", "tests/test_union.py::test_union_with_any", "tests/test_union.py::test_union_with_different_ordering" ]
[]
MIT License
18,805
768
[ "serde/compat.py", "serde/de.py" ]
Quantum-Accelerators__raspa_ase-24
9c1bf8756ff05093d87835a889c76dc59ad3e5bf
2024-06-26 22:00:37
9c1bf8756ff05093d87835a889c76dc59ad3e5bf
diff --git a/src/raspa_ase/calculator.py b/src/raspa_ase/calculator.py index f1ca04a..1cffc30 100644 --- a/src/raspa_ase/calculator.py +++ b/src/raspa_ase/calculator.py @@ -32,27 +32,26 @@ class RaspaProfile(BaseProfile): RASPA profile, which defines the command that will be executed and where. """ - def __init__(self, binary: Path | str | None = None, **kwargs) -> None: + def __init__(self, command: Path | str | None = None, **kwargs) -> None: """ Initialize the RASPA profile. $RASPA_DIR must be set in the environment. Parameters ---------- - binary - The binary to run RASPA. This defaults to doing `${RASPA_DIR}/bin/simulate` + command + The command to run RASPA. This defaults to doing `${RASPA_DIR}/bin/simulate` and typically does not need to be changed. Returns ------- None """ - super().__init__(**kwargs) - if not binary: + if not command: raspa_dir = os.environ.get("RASPA_DIR") if not raspa_dir: raise OSError("RASPA_DIR environment variable not set") - binary = f"{raspa_dir}/bin/simulate" - self.binary = binary + command = f"{raspa_dir}/bin/simulate" + super().__init__(command, **kwargs) def get_calculator_command(self, inputfile: str = SIMULATION_INPUT) -> list[str]: """ @@ -68,7 +67,7 @@ class RaspaProfile(BaseProfile): list[str] The command to run the calculator. """ - return [self.binary, f"{inputfile}"] + return [self.command, f"{inputfile}"] def version(self) -> str: """
Calculator not working with ASE 3.23 Calculator broke with the refactoring in ASE 3.23 :( needs a patch as shown in the tests
Quantum-Accelerators/raspa_ase
diff --git a/tests/test_calculator.py b/tests/test_calculator.py index 6b2703b..17a5db5 100644 --- a/tests/test_calculator.py +++ b/tests/test_calculator.py @@ -19,7 +19,7 @@ def test_profile_bad(monkeypatch): def test_profile(): profile = RaspaProfile() - assert profile.binary == f"{os.getenv('RASPA_DIR')}/bin/simulate" + assert profile.command == f"{os.getenv('RASPA_DIR')}/bin/simulate" assert profile.get_calculator_command() == [ f"{os.getenv('RASPA_DIR')}/bin/simulate", @@ -31,8 +31,8 @@ def test_profile(): def test_profil2e(): - profile = RaspaProfile(binary="my/path") - assert profile.binary == "my/path" + profile = RaspaProfile(command="my/path") + assert profile.command == "my/path" assert profile.get_calculator_command() == [ "my/path",
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 1 }
0.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc", "conda install -c conda-forge raspa2 -y" ], "python": "3.9", "reqs_path": [ "tests/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
ase==3.23.0 black==25.1.0 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 docformatter==1.7.5 exceptiongroup==1.2.2 execnet==2.1.1 fonttools==4.56.0 idna==3.10 importlib_resources==6.5.2 iniconfig==2.1.0 isort==6.0.1 joblib==1.4.2 kiwisolver==1.4.7 latexcodec==3.0.0 matplotlib==3.9.4 monty==2025.3.3 mpmath==1.3.0 mypy-extensions==1.0.0 narwhals==1.32.0 networkx==3.2.1 numpy==1.26.4 packaging==24.2 palettable==3.3.3 pandas==2.2.3 pathspec==0.12.1 pillow==11.1.0 platformdirs==4.3.7 plotly==6.0.1 pluggy==1.5.0 pybtex==0.24.0 pymatgen==2024.4.13 pyparsing==3.2.3 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 -e git+https://github.com/Quantum-Accelerators/raspa_ase.git@9c1bf8756ff05093d87835a889c76dc59ad3e5bf#egg=raspa_ase requests==2.32.3 ruamel.yaml==0.18.10 ruamel.yaml.clib==0.2.12 ruff==0.11.2 scipy==1.13.1 six==1.17.0 spglib==2.6.0 sympy==1.13.3 tabulate==0.9.0 tomli==2.2.1 tqdm==4.67.1 typing_extensions==4.13.0 tzdata==2025.2 uncertainties==3.2.2 untokenize==0.1.1 urllib3==2.3.0 zipp==3.21.0
name: raspa_ase channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - fftw=3.3.10=nompi_h77c792f_102 - ld_impl_linux-64=2.40=h12ee557_0 - libblas=3.9.0=16_linux64_openblas - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=13.2.0=h69a702a_0 - libgfortran5=13.2.0=ha4646dd_0 - libgomp=11.2.0=h1234567_1 - liblapack=3.9.0=16_linux64_openblas - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - raspa2=2.0.47=h6712644_0 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - ase==3.23.0 - black==25.1.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - docformatter==1.7.5 - exceptiongroup==1.2.2 - execnet==2.1.1 - fonttools==4.56.0 - idna==3.10 - importlib-resources==6.5.2 - iniconfig==2.1.0 - isort==6.0.1 - joblib==1.4.2 - kiwisolver==1.4.7 - latexcodec==3.0.0 - matplotlib==3.9.4 - monty==2025.3.3 - mpmath==1.3.0 - mypy-extensions==1.0.0 - narwhals==1.32.0 - networkx==3.2.1 - numpy==1.26.4 - packaging==24.2 - palettable==3.3.3 - pandas==2.2.3 - pathspec==0.12.1 - pillow==11.1.0 - platformdirs==4.3.7 - plotly==6.0.1 - pluggy==1.5.0 - pybtex==0.24.0 - pymatgen==2024.4.13 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - raspa-ase==0.0.2 - requests==2.32.3 - ruamel-yaml==0.18.10 - ruamel-yaml-clib==0.2.12 - ruff==0.11.2 - scipy==1.13.1 - six==1.17.0 - spglib==2.6.0 - sympy==1.13.3 - tabulate==0.9.0 - tomli==2.2.1 - tqdm==4.67.1 - typing-extensions==4.13.0 - tzdata==2025.2 - uncertainties==3.2.2 - untokenize==0.1.1 - urllib3==2.3.0 - zipp==3.21.0 prefix: /opt/conda/envs/raspa_ase
[ "tests/test_calculator.py::test_profil2e" ]
[ "tests/test_calculator.py::test_profile_bad", "tests/test_calculator.py::test_profile", "tests/test_calculator.py::test_template_execute", "tests/test_calculator.py::test_template_write_input", "tests/test_calculator.py::test_raspa_blank", "tests/test_calculator.py::test_raspa_parameters", "tests/test_calculator.py::test_raspa_boxes", "tests/test_calculator.py::test_raspa_components", "tests/test_calculator.py::test_raspa_functional1", "tests/test_calculator.py::test_raspa_functional2", "tests/test_calculator.py::test_multi_frameworks" ]
[ "tests/test_calculator.py::test_template", "tests/test_calculator.py::test_notimplemented", "tests/test_calculator.py::test_template_read_results" ]
[]
BSD 3-Clause "New" or "Revised" License
18,808
462
[ "src/raspa_ase/calculator.py" ]
narwhals-dev__narwhals-341
f77cd214441ccd1cd4cce45a4782823794a2c93b
2024-06-27 13:44:36
63d081dc0bdb5c448969f0ef91461aea986785b5
diff --git a/narwhals/__init__.py b/narwhals/__init__.py index a40f8018..e81f4236 100644 --- a/narwhals/__init__.py +++ b/narwhals/__init__.py @@ -3,6 +3,7 @@ from narwhals.dataframe import DataFrame from narwhals.dataframe import LazyFrame from narwhals.dtypes import Boolean from narwhals.dtypes import Categorical +from narwhals.dtypes import Date from narwhals.dtypes import Datetime from narwhals.dtypes import Float32 from narwhals.dtypes import Float64 @@ -75,6 +76,7 @@ __all__ = [ "Categorical", "String", "Datetime", + "Date", "narwhalify", "narwhalify_method", "show_versions", diff --git a/narwhals/_pandas_like/namespace.py b/narwhals/_pandas_like/namespace.py index 529b535f..95768d70 100644 --- a/narwhals/_pandas_like/namespace.py +++ b/narwhals/_pandas_like/namespace.py @@ -35,6 +35,7 @@ class PandasNamespace: Categorical = dtypes.Categorical String = dtypes.String Datetime = dtypes.Datetime + Date = dtypes.Date @property def selectors(self) -> PandasSelectorNamespace: diff --git a/narwhals/_pandas_like/utils.py b/narwhals/_pandas_like/utils.py index 1d4a0b24..0678b799 100644 --- a/narwhals/_pandas_like/utils.py +++ b/narwhals/_pandas_like/utils.py @@ -409,6 +409,8 @@ def translate_dtype(dtype: Any) -> DType: # pyarrow-backed datetime # todo: different time units and time zones return dtypes.Datetime() + if str(dtype) == "date32[day][pyarrow]": + return dtypes.Date() if dtype == "object": return dtypes.String() msg = f"Unknown dtype: {dtype}" # pragma: no cover @@ -532,6 +534,11 @@ def reverse_translate_dtype( # noqa: PLR0915 if dtype_backend == "pyarrow-nullable": return "timestamp[ns][pyarrow]" return "datetime64[ns]" + if isinstance_or_issubclass(dtype, dtypes.Date): + if dtype_backend == "pyarrow-nullable": + return "date32[pyarrow]" + msg = "Date dtype only supported for pyarrow-backed data types in pandas" + raise NotImplementedError(msg) msg = f"Unknown dtype: {dtype}" # pragma: no cover raise AssertionError(msg) diff --git a/narwhals/dtypes.py b/narwhals/dtypes.py index 49bc2239..93f3d99c 100644 --- a/narwhals/dtypes.py +++ b/narwhals/dtypes.py @@ -110,6 +110,8 @@ def translate_dtype(plx: Any, dtype: DType) -> Any: return plx.Categorical if dtype == Datetime: return plx.Datetime + if dtype == Date: + return plx.Date msg = f"Unknown dtype: {dtype}" # pragma: no cover raise AssertionError(msg) @@ -147,5 +149,7 @@ def to_narwhals_dtype(dtype: Any, *, is_polars: bool) -> DType: return Categorical() if dtype == pl.Datetime: return Datetime() + if dtype == pl.Date: + return Date() msg = f"Unexpected dtype, got: {type(dtype)}" # pragma: no cover raise AssertionError(msg)
feat: support nw.Date we need to support the Date dtype
narwhals-dev/narwhals
diff --git a/tests/series/cast_test.py b/tests/series/cast_test.py index 23bdf8e4..cb2d176b 100644 --- a/tests/series/cast_test.py +++ b/tests/series/cast_test.py @@ -1,7 +1,13 @@ +from datetime import date +from datetime import datetime + import pandas as pd import polars as pl +import pytest +from polars.testing import assert_frame_equal import narwhals as nw +from narwhals.utils import parse_version def test_cast_253() -> None: @@ -16,3 +22,65 @@ def test_cast_253() -> None: nw.col("a").cast(nw.String) + "hi" )["a"][0] assert result == "1hi" + + +def test_cast_date_datetime_polars() -> None: + # polars: date to datetime + dfpl = pl.DataFrame({"a": [date(2020, 1, 1), date(2020, 1, 2)]}) + df = nw.from_native(dfpl) + df = df.select(nw.col("a").cast(nw.Datetime)) + result = nw.to_native(df) + expected = pl.DataFrame({"a": [datetime(2020, 1, 1), datetime(2020, 1, 2)]}) + assert_frame_equal(result, expected) + + # polars: datetime to date + dfpl = pl.DataFrame({"a": [datetime(2020, 1, 1), datetime(2020, 1, 2)]}) + df = nw.from_native(dfpl) + df = df.select(nw.col("a").cast(nw.Date)) + result = nw.to_native(df) + expected = pl.DataFrame({"a": [date(2020, 1, 1), date(2020, 1, 2)]}) + assert_frame_equal(result, expected) + assert df.schema == {"a": nw.Date} + + [email protected]( + parse_version(pd.__version__) < parse_version("2.0.0"), + reason="pyarrow dtype not available", +) +def test_cast_date_datetime_pandas() -> None: + # pandas: pyarrow date to datetime + dfpd = pd.DataFrame({"a": [date(2020, 1, 1), date(2020, 1, 2)]}).astype( + {"a": "date32[pyarrow]"} + ) + df = nw.from_native(dfpd) + df = df.select(nw.col("a").cast(nw.Datetime)) + result = nw.to_native(df) + expected = pd.DataFrame({"a": [datetime(2020, 1, 1), datetime(2020, 1, 2)]}).astype( + {"a": "timestamp[ns][pyarrow]"} + ) + pd.testing.assert_frame_equal(result, expected) + + # pandas: pyarrow datetime to date + dfpd = pd.DataFrame({"a": [datetime(2020, 1, 1), datetime(2020, 1, 2)]}).astype( + {"a": "timestamp[ns][pyarrow]"} + ) + df = nw.from_native(dfpd) + df = df.select(nw.col("a").cast(nw.Date)) + result = nw.to_native(df) + expected = pd.DataFrame({"a": [date(2020, 1, 1), date(2020, 1, 2)]}).astype( + {"a": "date32[pyarrow]"} + ) + pd.testing.assert_frame_equal(result, expected) + assert df.schema == {"a": nw.Date} + + [email protected]( + parse_version(pd.__version__) < parse_version("2.0.0"), + reason="pyarrow dtype not available", +) +def test_cast_date_datetime_invalid() -> None: + # pandas: pyarrow datetime to date + dfpd = pd.DataFrame({"a": [datetime(2020, 1, 1), datetime(2020, 1, 2)]}) + df = nw.from_native(dfpd) + with pytest.raises(NotImplementedError, match="pyarrow"): + df.select(nw.col("a").cast(nw.Date))
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 4 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 cfgv==3.4.0 covdefaults==2.3.0 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 filelock==3.18.0 hypothesis==6.130.5 identify==2.6.9 iniconfig==2.1.0 joblib==1.4.2 -e git+https://github.com/narwhals-dev/narwhals.git@f77cd214441ccd1cd4cce45a4782823794a2c93b#egg=narwhals nodeenv==1.9.1 numpy==2.0.2 packaging==24.2 pandas==2.2.3 platformdirs==4.3.7 pluggy==1.5.0 polars==1.26.0 pre_commit==4.2.0 pyarrow==19.0.1 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 scikit-learn==1.6.1 scipy==1.13.1 six==1.17.0 sortedcontainers==2.4.0 threadpoolctl==3.6.0 tomli==2.2.1 tzdata==2025.2 virtualenv==20.29.3
name: narwhals channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - cfgv==3.4.0 - covdefaults==2.3.0 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - filelock==3.18.0 - hypothesis==6.130.5 - identify==2.6.9 - iniconfig==2.1.0 - joblib==1.4.2 - narwhals==0.9.16 - nodeenv==1.9.1 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - platformdirs==4.3.7 - pluggy==1.5.0 - polars==1.26.0 - pre-commit==4.2.0 - pyarrow==19.0.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - scikit-learn==1.6.1 - scipy==1.13.1 - six==1.17.0 - sortedcontainers==2.4.0 - threadpoolctl==3.6.0 - tomli==2.2.1 - tzdata==2025.2 - virtualenv==20.29.3 prefix: /opt/conda/envs/narwhals
[ "tests/series/cast_test.py::test_cast_date_datetime_polars", "tests/series/cast_test.py::test_cast_date_datetime_pandas", "tests/series/cast_test.py::test_cast_date_datetime_invalid" ]
[]
[ "tests/series/cast_test.py::test_cast_253" ]
[]
MIT License
18,811
944
[ "narwhals/__init__.py", "narwhals/_pandas_like/namespace.py", "narwhals/_pandas_like/utils.py", "narwhals/dtypes.py" ]
dag-hammarskjold-library__dlx-dl-123
f59613566132915e35ca8fe19ef7e41eb552a322
2024-06-27 18:05:37
980c47a79ac12933f44275497b287156db8d49b1
diff --git a/dlx_dl/scripts/export/__init__.py b/dlx_dl/scripts/export/__init__.py index e5fdcdc..bd80fbe 100644 --- a/dlx_dl/scripts/export/__init__.py +++ b/dlx_dl/scripts/export/__init__.py @@ -392,6 +392,7 @@ def _561(bib): latest = sorted(files, key=lambda x: x.timestamp, reverse=True)[0] _fft = Datafield('FFT', record_type='bib') _fft.set('a', 'https://' + latest.uri) + _fft.set('d', ', '.join([ISO_STR.get(x, '') for x in latest.languages])) old_fn = latest.filename if latest.filename else uri.split('/')[-1] new_fn = clean_fn(old_fn) diff --git a/dlx_dl/scripts/sync/__init__.py b/dlx_dl/scripts/sync/__init__.py index 3cb614c..9eefbb1 100644 --- a/dlx_dl/scripts/sync/__init__.py +++ b/dlx_dl/scripts/sync/__init__.py @@ -79,6 +79,8 @@ def get_args(**kwargs): # if run as function convert args to sys.argv so they can be parsed by ArgumentParser if kwargs: + sys.argv = [sys.argv[0]] # clear any existing command line args + for key, val in kwargs.items(): if val == True: # boolean args @@ -90,10 +92,10 @@ def get_args(**kwargs): sys.argv.append(f'--{key}={val}') return parser.parse_args() - + def run(**kwargs): args = get_args(**kwargs) - + if isinstance(kwargs.get('connect'), MockClient): # required for testing DB.client = kwargs['connect']
Set a language for fft created using field 561 add the language to the fft filed when importing a files using a uri as an identifier. Just like here: https://github.com/dag-hammarskjold-library/dlx-dl/blob/6a6aa2cb377b676761cae6607ef59e2f0264b478/dlx_dl/scripts/export/__init__.py#L537C18-L537C46
dag-hammarskjold-library/dlx-dl
diff --git a/tests/test_dlx_dl.py b/tests/test_dlx_dl.py index 490064a..588f2e5 100644 --- a/tests/test_dlx_dl.py +++ b/tests/test_dlx_dl.py @@ -1,4 +1,4 @@ -import os, pytest, responses +import sys, os, pytest, responses from moto import mock_aws from datetime import datetime from dlx_dl.scripts import export, sync @@ -38,8 +38,8 @@ def db(): handle.seek(0) File.import_from_handle( handle, - filename='', - identifiers=[Identifier('symbol', 'TEST/1')], + filename='test 1', + identifiers=[Identifier('symbol', 'TEST/1'), Identifier('uri', 'test uri identifier')], languages=['EN'], mimetype='text/plain', source='test' @@ -210,7 +210,20 @@ def test_delete(db, capsys, mock_post): #assert len(data) == 3 #assert json.loads(data[2])['record_id'] == 3 +def test_561(db, tmp_path): + from io import BytesIO + from xmldiff.main import diff_texts + from dlx.marc import Bib + + bib = Bib().set('561', 'u', 'test uri identifier') + bib.commit() + control = '<collection><record><datafield tag="035" ind1=" " ind2=" "><subfield code="a">(DHL)3</subfield></datafield><datafield tag="561" ind1=" " ind2=" "><subfield code="u">test uri identifier</subfield></datafield><datafield tag="980" ind1=" " ind2=" "><subfield code="a">BIB</subfield></datafield><datafield tag="FFT" ind1=" " ind2=" "><subfield code="a">https://mock_bucket.s3.amazonaws.com/1e50210a0202497fb79bc38b6ade6c34</subfield><subfield code="d">English</subfield><subfield code="n">.test_1</subfield></datafield></record></collection>' + out = tmp_path / 'out.xml' + export.run(connect=db, source='test', type='bib', id=bib.id, xml=out) + assert diff_texts(out.read_text(), control) == [] + def test_sync(db, capsys, mock_get_post): + # todo: expand this test from http.server import HTTPServer from dlx.marc import Bib
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
1.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==23.2.0 boto3==1.34.100 botocore==1.34.100 certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 click==8.1.7 cryptography==42.0.7 dlx @ git+https://github.com/dag-hammarskjold-library/dlx@02ec992c5391f38813bd6f5e6f393b3e6d67c562 -e git+https://github.com/dag-hammarskjold-library/dlx-dl.git@f59613566132915e35ca8fe19ef7e41eb552a322#egg=dlx_dl dnspython==2.6.1 exceptiongroup==1.2.1 idna==3.7 iniconfig==2.0.0 Jinja2==3.1.4 jmespath==1.0.1 joblib==1.4.2 jsonschema==4.0.0 lxml==5.2.1 MarkupSafe==2.1.5 mongomock==4.1.2 moto==5.0.8 nltk==3.8.1 packaging==24.0 pluggy==1.5.0 pycparser==2.22 pymongo==4.6.3 pyrsistent==0.20.0 pytest==8.2.0 python-dateutil==2.9.0.post0 pytz==2024.1 PyYAML==6.0.1 regex==2024.4.28 requests==2.32.2 responses==0.25.0 s3transfer==0.10.1 sentinels==1.0.0 six==1.16.0 toml==0.10.2 tomli==2.0.1 tqdm==4.66.4 types-toml==0.10.8 urllib3==1.26.18 Werkzeug==3.0.3 xlrd==1.2.0 xmldiff==2.4 xmltodict==0.13.0
name: dlx-dl channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==23.2.0 - boto3==1.34.100 - botocore==1.34.100 - certifi==2024.2.2 - cffi==1.16.0 - charset-normalizer==3.3.2 - click==8.1.7 - cryptography==42.0.7 - dlx==1.4.2 - dnspython==2.6.1 - exceptiongroup==1.2.1 - idna==3.7 - iniconfig==2.0.0 - jinja2==3.1.4 - jmespath==1.0.1 - joblib==1.4.2 - jsonschema==4.0.0 - lxml==5.2.1 - markupsafe==2.1.5 - mongomock==4.1.2 - moto==5.0.8 - nltk==3.8.1 - packaging==24.0 - pluggy==1.5.0 - pycparser==2.22 - pymongo==4.6.3 - pyrsistent==0.20.0 - pytest==8.2.0 - python-dateutil==2.9.0.post0 - pytz==2024.1 - pyyaml==6.0.1 - regex==2024.4.28 - requests==2.32.2 - responses==0.25.0 - s3transfer==0.10.1 - sentinels==1.0.0 - six==1.16.0 - toml==0.10.2 - tomli==2.0.1 - tqdm==4.66.4 - types-toml==0.10.8 - urllib3==1.26.18 - werkzeug==3.0.3 - xlrd==1.2.0 - xmldiff==2.4 - xmltodict==0.13.0 prefix: /opt/conda/envs/dlx-dl
[ "tests/test_dlx_dl.py::test_561", "tests/test_dlx_dl.py::test_sync" ]
[]
[ "tests/test_dlx_dl.py::test_by_id", "tests/test_dlx_dl.py::test_to_file", "tests/test_dlx_dl.py::test_by_list", "tests/test_dlx_dl.py::test_by_date", "tests/test_dlx_dl.py::test_post_and_log", "tests/test_dlx_dl.py::test_modified_since_log", "tests/test_dlx_dl.py::test_blacklist", "tests/test_dlx_dl.py::test_queue", "tests/test_dlx_dl.py::test_delete" ]
[]
null
18,813
424
[ "dlx_dl/scripts/export/__init__.py", "dlx_dl/scripts/sync/__init__.py" ]
lark-parser__lark-1433
33136b32963d131580217b479cad3a09f3657dae
2024-06-28 01:50:23
501689455b00ff643b7901994dcb6d2a92d4412e
diff --git a/lark/parsers/earley.py b/lark/parsers/earley.py index 2153a0c..8deaa2f 100644 --- a/lark/parsers/earley.py +++ b/lark/parsers/earley.py @@ -300,7 +300,10 @@ class Parser: if self.Tree is not None: # Perform our SPPF -> AST conversion - transformer = ForestToParseTree(self.Tree, self.callbacks, self.forest_sum_visitor and self.forest_sum_visitor(), self.resolve_ambiguity) + # Disable the ForestToParseTree cache when ambiguity='resolve' + # to prevent a tree construction bug. See issue #1283 + use_cache = not self.resolve_ambiguity + transformer = ForestToParseTree(self.Tree, self.callbacks, self.forest_sum_visitor and self.forest_sum_visitor(), self.resolve_ambiguity, use_cache) solutions = [transformer.transform(s) for s in solutions] if len(solutions) > 1: diff --git a/lark/parsers/earley_forest.py b/lark/parsers/earley_forest.py index cdc613a..c60f3a6 100644 --- a/lark/parsers/earley_forest.py +++ b/lark/parsers/earley_forest.py @@ -609,9 +609,10 @@ class ForestToParseTree(ForestTransformer): children.append(data.left) if data.right is not PackedData.NO_DATA: children.append(data.right) - if node.parent.is_intermediate: - return self._cache.setdefault(id(node), children) - return self._cache.setdefault(id(node), self._call_rule_func(node, children)) + transformed = children if node.parent.is_intermediate else self._call_rule_func(node, children) + if self._use_cache: + self._cache[id(node)] = transformed + return transformed def visit_symbol_node_in(self, node): super(ForestToParseTree, self).visit_symbol_node_in(node)
Earley parser produces wrong parse Tree Over on SO someone asked this question: https://stackoverflow.com/questions/76366280/parsing-formulas-using-lark-ebnf/76381256 As far as I can tell, it shows a bug in the earley parser where it duplicates some Tokens because of enormous amounts of ambiguities. I don't have the expertise with earley to figure out what is happening or the time to create a minimal example right now.
lark-parser/lark
diff --git a/tests/test_parser.py b/tests/test_parser.py index ee5d5a0..13124a0 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -954,6 +954,26 @@ def _make_full_earley_test(LEXER): self.assertEqual(node.start, 0) self.assertEqual(node.end, 3) + def test_resolve_ambiguity_with_shared_node(self): + grammar = """ + start: (a+)* + !a.1: "A" | + """ + + l = Lark(grammar, ambiguity='resolve', lexer=LEXER) + tree = l.parse("A") + self.assertEqual(tree, Tree('start', [Tree('a', []), Tree('a', []), Tree('a', ['A'])])) + + def test_resolve_ambiguity_with_shared_node2(self): + grammar = """ + start: _s x _s + x: "X"? + _s: " "? + """ + + l = Lark(grammar, ambiguity='resolve', lexer=LEXER) + tree = l.parse("") + self.assertEqual(tree, Tree('start', [Tree('x', [])])) _NAME = "TestFullEarley" + LEXER.capitalize() _TestFullEarley.__name__ = _NAME
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mypy", "pre-commit" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cfgv==3.4.0 distlib==0.3.9 exceptiongroup==1.2.2 filelock==3.18.0 identify==2.6.9 iniconfig==2.1.0 -e git+https://github.com/lark-parser/lark.git@33136b32963d131580217b479cad3a09f3657dae#egg=lark mypy==1.15.0 mypy-extensions==1.0.0 nodeenv==1.9.1 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 pytest==8.3.5 PyYAML==6.0.2 tomli==2.2.1 typing_extensions==4.13.0 virtualenv==20.29.3
name: lark channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cfgv==3.4.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - filelock==3.18.0 - identify==2.6.9 - iniconfig==2.1.0 - lark==1.2.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - nodeenv==1.9.1 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pytest==8.3.5 - pyyaml==6.0.2 - tomli==2.2.1 - typing-extensions==4.13.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/lark
[ "tests/test_parser.py::TestFullEarleyBasic::test_resolve_ambiguity_with_shared_node", "tests/test_parser.py::TestFullEarleyBasic::test_resolve_ambiguity_with_shared_node2", "tests/test_parser.py::TestFullEarleyDynamic::test_resolve_ambiguity_with_shared_node", "tests/test_parser.py::TestFullEarleyDynamic::test_resolve_ambiguity_with_shared_node2", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_resolve_ambiguity_with_shared_node", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_resolve_ambiguity_with_shared_node2" ]
[]
[ "tests/test_parser.py::TestParsers::test_alias", "tests/test_parser.py::TestParsers::test_backwards_custom_lexer", "tests/test_parser.py::TestParsers::test_big_list", "tests/test_parser.py::TestParsers::test_comment_in_rule_definition", "tests/test_parser.py::TestParsers::test_embedded_transformer", "tests/test_parser.py::TestParsers::test_embedded_transformer_inplace", "tests/test_parser.py::TestParsers::test_expand1", "tests/test_parser.py::TestParsers::test_infinite_recurse", "tests/test_parser.py::TestParsers::test_lexer_token_limit", "tests/test_parser.py::TestParsers::test_propagate_positions", "tests/test_parser.py::TestParsers::test_propagate_positions2", "tests/test_parser.py::TestParsers::test_same_ast", "tests/test_parser.py::TestParsers::test_vargs_meta", "tests/test_parser.py::TestParsers::test_vargs_tree", "tests/test_parser.py::TestParsers::test_visit_tokens", "tests/test_parser.py::TestParsers::test_visit_tokens2", "tests/test_parser.py::TestEarleyBasic::test_alias", "tests/test_parser.py::TestEarleyBasic::test_backslash", "tests/test_parser.py::TestEarleyBasic::test_backslash2", "tests/test_parser.py::TestEarleyBasic::test_basic1", "tests/test_parser.py::TestEarleyBasic::test_basic2", "tests/test_parser.py::TestEarleyBasic::test_bytes_utf8", "tests/test_parser.py::TestEarleyBasic::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestEarleyBasic::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestEarleyBasic::test_empty", "tests/test_parser.py::TestEarleyBasic::test_empty_end", "tests/test_parser.py::TestEarleyBasic::test_empty_expand1_list", "tests/test_parser.py::TestEarleyBasic::test_empty_expand1_list_2", "tests/test_parser.py::TestEarleyBasic::test_empty_flatten_list", "tests/test_parser.py::TestEarleyBasic::test_escaped_string", "tests/test_parser.py::TestEarleyBasic::test_expand1_lists_with_one_item", "tests/test_parser.py::TestEarleyBasic::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestEarleyBasic::test_float_without_lexer", "tests/test_parser.py::TestEarleyBasic::test_g_regex_flags", "tests/test_parser.py::TestEarleyBasic::test_hex_escape", "tests/test_parser.py::TestEarleyBasic::test_hex_literal_range_escape", "tests/test_parser.py::TestEarleyBasic::test_ignore", "tests/test_parser.py::TestEarleyBasic::test_import", "tests/test_parser.py::TestEarleyBasic::test_import_errors", "tests/test_parser.py::TestEarleyBasic::test_import_rename", "tests/test_parser.py::TestEarleyBasic::test_join_regex_flags", "tests/test_parser.py::TestEarleyBasic::test_keep_all_tokens", "tests/test_parser.py::TestEarleyBasic::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestEarleyBasic::test_lexer_prioritization", "tests/test_parser.py::TestEarleyBasic::test_line_and_column", "tests/test_parser.py::TestEarleyBasic::test_line_counting", "tests/test_parser.py::TestEarleyBasic::test_match_examples", "tests/test_parser.py::TestEarleyBasic::test_maybe", "tests/test_parser.py::TestEarleyBasic::test_maybe_placeholders", "tests/test_parser.py::TestEarleyBasic::test_meddling_unused", "tests/test_parser.py::TestEarleyBasic::test_multi_import", "tests/test_parser.py::TestEarleyBasic::test_multi_start", "tests/test_parser.py::TestEarleyBasic::test_postlex_declare", "tests/test_parser.py::TestEarleyBasic::test_postlex_indenter", "tests/test_parser.py::TestEarleyBasic::test_prioritization", "tests/test_parser.py::TestEarleyBasic::test_priority_vs_embedded", "tests/test_parser.py::TestEarleyBasic::test_ranged_repeat_rules", "tests/test_parser.py::TestEarleyBasic::test_reduce_cycle", "tests/test_parser.py::TestEarleyBasic::test_regex_escaping", "tests/test_parser.py::TestEarleyBasic::test_regex_quote", "tests/test_parser.py::TestEarleyBasic::test_relative_import", "tests/test_parser.py::TestEarleyBasic::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestEarleyBasic::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestEarleyBasic::test_relative_import_rename", "tests/test_parser.py::TestEarleyBasic::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestEarleyBasic::test_relative_import_unicode", "tests/test_parser.py::TestEarleyBasic::test_relative_multi_import", "tests/test_parser.py::TestEarleyBasic::test_relative_rule_import", "tests/test_parser.py::TestEarleyBasic::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestEarleyBasic::test_relative_rule_import_rename", "tests/test_parser.py::TestEarleyBasic::test_relative_rule_import_subrule", "tests/test_parser.py::TestEarleyBasic::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestEarleyBasic::test_rule_collision", "tests/test_parser.py::TestEarleyBasic::test_rule_collision2", "tests/test_parser.py::TestEarleyBasic::test_special_chars", "tests/test_parser.py::TestEarleyBasic::test_stack_for_ebnf", "tests/test_parser.py::TestEarleyBasic::test_start", "tests/test_parser.py::TestEarleyBasic::test_stringio_unicode", "tests/test_parser.py::TestEarleyBasic::test_templates", "tests/test_parser.py::TestEarleyBasic::test_templates_alias", "tests/test_parser.py::TestEarleyBasic::test_templates_import", "tests/test_parser.py::TestEarleyBasic::test_templates_modifiers", "tests/test_parser.py::TestEarleyBasic::test_templates_recursion", "tests/test_parser.py::TestEarleyBasic::test_templates_templates", "tests/test_parser.py::TestEarleyBasic::test_token_collision", "tests/test_parser.py::TestEarleyBasic::test_token_collision2", "tests/test_parser.py::TestEarleyBasic::test_token_collision_WS", "tests/test_parser.py::TestEarleyBasic::test_token_ebnf", "tests/test_parser.py::TestEarleyBasic::test_token_flags", "tests/test_parser.py::TestEarleyBasic::test_token_flags2", "tests/test_parser.py::TestEarleyBasic::test_token_flags3", "tests/test_parser.py::TestEarleyBasic::test_token_flags_verbose", "tests/test_parser.py::TestEarleyBasic::test_token_flags_verbose_multiline", "tests/test_parser.py::TestEarleyBasic::test_token_not_anon", "tests/test_parser.py::TestEarleyBasic::test_twice_empty", "tests/test_parser.py::TestEarleyBasic::test_unicode", "tests/test_parser.py::TestEarleyBasic::test_unicode2", "tests/test_parser.py::TestEarleyBasic::test_unicode3", "tests/test_parser.py::TestEarleyBasic::test_unicode4", "tests/test_parser.py::TestEarleyBasic::test_unicode_literal_range_escape", "tests/test_parser.py::TestEarleyBasic::test_unicode_literal_range_escape2", "tests/test_parser.py::TestEarleyBasic::test_utf8", "tests/test_parser.py::TestCykBasic::test_alias", "tests/test_parser.py::TestCykBasic::test_backslash", "tests/test_parser.py::TestCykBasic::test_backslash2", "tests/test_parser.py::TestCykBasic::test_basic1", "tests/test_parser.py::TestCykBasic::test_basic2", "tests/test_parser.py::TestCykBasic::test_bytes_utf8", "tests/test_parser.py::TestCykBasic::test_default_in_treeless_mode", "tests/test_parser.py::TestCykBasic::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestCykBasic::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestCykBasic::test_escaped_string", "tests/test_parser.py::TestCykBasic::test_expand1_lists_with_one_item", "tests/test_parser.py::TestCykBasic::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestCykBasic::test_float_without_lexer", "tests/test_parser.py::TestCykBasic::test_g_regex_flags", "tests/test_parser.py::TestCykBasic::test_hex_escape", "tests/test_parser.py::TestCykBasic::test_hex_literal_range_escape", "tests/test_parser.py::TestCykBasic::test_import", "tests/test_parser.py::TestCykBasic::test_import_errors", "tests/test_parser.py::TestCykBasic::test_import_rename", "tests/test_parser.py::TestCykBasic::test_join_regex_flags", "tests/test_parser.py::TestCykBasic::test_keep_all_tokens", "tests/test_parser.py::TestCykBasic::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestCykBasic::test_lexer_prioritization", "tests/test_parser.py::TestCykBasic::test_line_and_column", "tests/test_parser.py::TestCykBasic::test_line_counting", "tests/test_parser.py::TestCykBasic::test_meddling_unused", "tests/test_parser.py::TestCykBasic::test_multi_import", "tests/test_parser.py::TestCykBasic::test_multi_start", "tests/test_parser.py::TestCykBasic::test_postlex_declare", "tests/test_parser.py::TestCykBasic::test_postlex_indenter", "tests/test_parser.py::TestCykBasic::test_priority_vs_embedded", "tests/test_parser.py::TestCykBasic::test_ranged_repeat_rules", "tests/test_parser.py::TestCykBasic::test_reduce_cycle", "tests/test_parser.py::TestCykBasic::test_regex_escaping", "tests/test_parser.py::TestCykBasic::test_regex_quote", "tests/test_parser.py::TestCykBasic::test_relative_import", "tests/test_parser.py::TestCykBasic::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestCykBasic::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestCykBasic::test_relative_import_rename", "tests/test_parser.py::TestCykBasic::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestCykBasic::test_relative_import_unicode", "tests/test_parser.py::TestCykBasic::test_relative_multi_import", "tests/test_parser.py::TestCykBasic::test_relative_rule_import", "tests/test_parser.py::TestCykBasic::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestCykBasic::test_relative_rule_import_rename", "tests/test_parser.py::TestCykBasic::test_relative_rule_import_subrule", "tests/test_parser.py::TestCykBasic::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestCykBasic::test_rule_collision", "tests/test_parser.py::TestCykBasic::test_rule_collision2", "tests/test_parser.py::TestCykBasic::test_special_chars", "tests/test_parser.py::TestCykBasic::test_start", "tests/test_parser.py::TestCykBasic::test_stringio_unicode", "tests/test_parser.py::TestCykBasic::test_templates", "tests/test_parser.py::TestCykBasic::test_templates_alias", "tests/test_parser.py::TestCykBasic::test_templates_import", "tests/test_parser.py::TestCykBasic::test_templates_modifiers", "tests/test_parser.py::TestCykBasic::test_templates_recursion", "tests/test_parser.py::TestCykBasic::test_templates_templates", "tests/test_parser.py::TestCykBasic::test_token_collision", "tests/test_parser.py::TestCykBasic::test_token_collision2", "tests/test_parser.py::TestCykBasic::test_token_collision_WS", "tests/test_parser.py::TestCykBasic::test_token_ebnf", "tests/test_parser.py::TestCykBasic::test_token_flags", "tests/test_parser.py::TestCykBasic::test_token_flags2", "tests/test_parser.py::TestCykBasic::test_token_flags3", "tests/test_parser.py::TestCykBasic::test_token_flags_verbose", "tests/test_parser.py::TestCykBasic::test_token_flags_verbose_multiline", "tests/test_parser.py::TestCykBasic::test_token_not_anon", "tests/test_parser.py::TestCykBasic::test_unicode", "tests/test_parser.py::TestCykBasic::test_unicode2", "tests/test_parser.py::TestCykBasic::test_unicode3", "tests/test_parser.py::TestCykBasic::test_unicode4", "tests/test_parser.py::TestCykBasic::test_unicode_literal_range_escape", "tests/test_parser.py::TestCykBasic::test_unicode_literal_range_escape2", "tests/test_parser.py::TestCykBasic::test_utf8", "tests/test_parser.py::TestLalrBasic::test_alias", "tests/test_parser.py::TestLalrBasic::test_backslash", "tests/test_parser.py::TestLalrBasic::test_backslash2", "tests/test_parser.py::TestLalrBasic::test_basic1", "tests/test_parser.py::TestLalrBasic::test_basic2", "tests/test_parser.py::TestLalrBasic::test_bytes_utf8", "tests/test_parser.py::TestLalrBasic::test_default_in_treeless_mode", "tests/test_parser.py::TestLalrBasic::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestLalrBasic::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestLalrBasic::test_empty", "tests/test_parser.py::TestLalrBasic::test_empty_end", "tests/test_parser.py::TestLalrBasic::test_empty_expand1_list", "tests/test_parser.py::TestLalrBasic::test_empty_expand1_list_2", "tests/test_parser.py::TestLalrBasic::test_empty_flatten_list", "tests/test_parser.py::TestLalrBasic::test_error_with_interactive_parser", "tests/test_parser.py::TestLalrBasic::test_escaped_string", "tests/test_parser.py::TestLalrBasic::test_expand1_lists_with_one_item", "tests/test_parser.py::TestLalrBasic::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestLalrBasic::test_float_without_lexer", "tests/test_parser.py::TestLalrBasic::test_g_regex_flags", "tests/test_parser.py::TestLalrBasic::test_hex_escape", "tests/test_parser.py::TestLalrBasic::test_hex_literal_range_escape", "tests/test_parser.py::TestLalrBasic::test_ignore", "tests/test_parser.py::TestLalrBasic::test_import", "tests/test_parser.py::TestLalrBasic::test_import_errors", "tests/test_parser.py::TestLalrBasic::test_import_rename", "tests/test_parser.py::TestLalrBasic::test_interactive_treeless_transformer", "tests/test_parser.py::TestLalrBasic::test_iter_parse", "tests/test_parser.py::TestLalrBasic::test_join_regex_flags", "tests/test_parser.py::TestLalrBasic::test_keep_all_tokens", "tests/test_parser.py::TestLalrBasic::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestLalrBasic::test_lexer_prioritization", "tests/test_parser.py::TestLalrBasic::test_line_and_column", "tests/test_parser.py::TestLalrBasic::test_line_counting", "tests/test_parser.py::TestLalrBasic::test_match_examples", "tests/test_parser.py::TestLalrBasic::test_maybe", "tests/test_parser.py::TestLalrBasic::test_maybe_placeholders", "tests/test_parser.py::TestLalrBasic::test_meddling_unused", "tests/test_parser.py::TestLalrBasic::test_multi_import", "tests/test_parser.py::TestLalrBasic::test_multi_start", "tests/test_parser.py::TestLalrBasic::test_parser_interactive_parser", "tests/test_parser.py::TestLalrBasic::test_postlex_declare", "tests/test_parser.py::TestLalrBasic::test_postlex_indenter", "tests/test_parser.py::TestLalrBasic::test_prioritization", "tests/test_parser.py::TestLalrBasic::test_priority_vs_embedded", "tests/test_parser.py::TestLalrBasic::test_ranged_repeat_rules", "tests/test_parser.py::TestLalrBasic::test_reduce_cycle", "tests/test_parser.py::TestLalrBasic::test_regex_escaping", "tests/test_parser.py::TestLalrBasic::test_regex_quote", "tests/test_parser.py::TestLalrBasic::test_relative_import", "tests/test_parser.py::TestLalrBasic::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestLalrBasic::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestLalrBasic::test_relative_import_rename", "tests/test_parser.py::TestLalrBasic::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestLalrBasic::test_relative_import_unicode", "tests/test_parser.py::TestLalrBasic::test_relative_multi_import", "tests/test_parser.py::TestLalrBasic::test_relative_rule_import", "tests/test_parser.py::TestLalrBasic::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestLalrBasic::test_relative_rule_import_rename", "tests/test_parser.py::TestLalrBasic::test_relative_rule_import_subrule", "tests/test_parser.py::TestLalrBasic::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestLalrBasic::test_rule_collision", "tests/test_parser.py::TestLalrBasic::test_rule_collision2", "tests/test_parser.py::TestLalrBasic::test_serialize", "tests/test_parser.py::TestLalrBasic::test_special_chars", "tests/test_parser.py::TestLalrBasic::test_stack_for_ebnf", "tests/test_parser.py::TestLalrBasic::test_start", "tests/test_parser.py::TestLalrBasic::test_strict", "tests/test_parser.py::TestLalrBasic::test_stringio_unicode", "tests/test_parser.py::TestLalrBasic::test_templates", "tests/test_parser.py::TestLalrBasic::test_templates_alias", "tests/test_parser.py::TestLalrBasic::test_templates_import", "tests/test_parser.py::TestLalrBasic::test_templates_modifiers", "tests/test_parser.py::TestLalrBasic::test_templates_recursion", "tests/test_parser.py::TestLalrBasic::test_templates_templates", "tests/test_parser.py::TestLalrBasic::test_token_collision", "tests/test_parser.py::TestLalrBasic::test_token_collision2", "tests/test_parser.py::TestLalrBasic::test_token_collision_WS", "tests/test_parser.py::TestLalrBasic::test_token_ebnf", "tests/test_parser.py::TestLalrBasic::test_token_flags", "tests/test_parser.py::TestLalrBasic::test_token_flags2", "tests/test_parser.py::TestLalrBasic::test_token_flags3", "tests/test_parser.py::TestLalrBasic::test_token_flags_verbose", "tests/test_parser.py::TestLalrBasic::test_token_flags_verbose_multiline", "tests/test_parser.py::TestLalrBasic::test_token_not_anon", "tests/test_parser.py::TestLalrBasic::test_twice_empty", "tests/test_parser.py::TestLalrBasic::test_unicode", "tests/test_parser.py::TestLalrBasic::test_unicode2", "tests/test_parser.py::TestLalrBasic::test_unicode3", "tests/test_parser.py::TestLalrBasic::test_unicode4", "tests/test_parser.py::TestLalrBasic::test_unicode_literal_range_escape", "tests/test_parser.py::TestLalrBasic::test_unicode_literal_range_escape2", "tests/test_parser.py::TestLalrBasic::test_utf8", "tests/test_parser.py::TestEarleyDynamic::test_alias", "tests/test_parser.py::TestEarleyDynamic::test_backslash", "tests/test_parser.py::TestEarleyDynamic::test_backslash2", "tests/test_parser.py::TestEarleyDynamic::test_basic1", "tests/test_parser.py::TestEarleyDynamic::test_basic2", "tests/test_parser.py::TestEarleyDynamic::test_bytes_utf8", "tests/test_parser.py::TestEarleyDynamic::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestEarleyDynamic::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestEarleyDynamic::test_dynamic_lexer_prioritization", "tests/test_parser.py::TestEarleyDynamic::test_empty", "tests/test_parser.py::TestEarleyDynamic::test_empty_end", "tests/test_parser.py::TestEarleyDynamic::test_empty_expand1_list", "tests/test_parser.py::TestEarleyDynamic::test_empty_expand1_list_2", "tests/test_parser.py::TestEarleyDynamic::test_empty_flatten_list", "tests/test_parser.py::TestEarleyDynamic::test_escaped_string", "tests/test_parser.py::TestEarleyDynamic::test_expand1_lists_with_one_item", "tests/test_parser.py::TestEarleyDynamic::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestEarleyDynamic::test_float_without_lexer", "tests/test_parser.py::TestEarleyDynamic::test_g_regex_flags", "tests/test_parser.py::TestEarleyDynamic::test_hex_escape", "tests/test_parser.py::TestEarleyDynamic::test_hex_literal_range_escape", "tests/test_parser.py::TestEarleyDynamic::test_ignore", "tests/test_parser.py::TestEarleyDynamic::test_import", "tests/test_parser.py::TestEarleyDynamic::test_import_errors", "tests/test_parser.py::TestEarleyDynamic::test_import_rename", "tests/test_parser.py::TestEarleyDynamic::test_join_regex_flags", "tests/test_parser.py::TestEarleyDynamic::test_keep_all_tokens", "tests/test_parser.py::TestEarleyDynamic::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestEarleyDynamic::test_line_and_column", "tests/test_parser.py::TestEarleyDynamic::test_line_counting", "tests/test_parser.py::TestEarleyDynamic::test_match_examples", "tests/test_parser.py::TestEarleyDynamic::test_maybe", "tests/test_parser.py::TestEarleyDynamic::test_maybe_placeholders", "tests/test_parser.py::TestEarleyDynamic::test_meddling_unused", "tests/test_parser.py::TestEarleyDynamic::test_multi_import", "tests/test_parser.py::TestEarleyDynamic::test_multi_start", "tests/test_parser.py::TestEarleyDynamic::test_prioritization", "tests/test_parser.py::TestEarleyDynamic::test_prioritization_sum", "tests/test_parser.py::TestEarleyDynamic::test_priority_vs_embedded", "tests/test_parser.py::TestEarleyDynamic::test_ranged_repeat_rules", "tests/test_parser.py::TestEarleyDynamic::test_reduce_cycle", "tests/test_parser.py::TestEarleyDynamic::test_regex_escaping", "tests/test_parser.py::TestEarleyDynamic::test_regex_quote", "tests/test_parser.py::TestEarleyDynamic::test_relative_import", "tests/test_parser.py::TestEarleyDynamic::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestEarleyDynamic::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestEarleyDynamic::test_relative_import_rename", "tests/test_parser.py::TestEarleyDynamic::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestEarleyDynamic::test_relative_import_unicode", "tests/test_parser.py::TestEarleyDynamic::test_relative_multi_import", "tests/test_parser.py::TestEarleyDynamic::test_relative_rule_import", "tests/test_parser.py::TestEarleyDynamic::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestEarleyDynamic::test_relative_rule_import_rename", "tests/test_parser.py::TestEarleyDynamic::test_relative_rule_import_subrule", "tests/test_parser.py::TestEarleyDynamic::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestEarleyDynamic::test_rule_collision", "tests/test_parser.py::TestEarleyDynamic::test_rule_collision2", "tests/test_parser.py::TestEarleyDynamic::test_special_chars", "tests/test_parser.py::TestEarleyDynamic::test_stack_for_ebnf", "tests/test_parser.py::TestEarleyDynamic::test_start", "tests/test_parser.py::TestEarleyDynamic::test_stringio_unicode", "tests/test_parser.py::TestEarleyDynamic::test_templates", "tests/test_parser.py::TestEarleyDynamic::test_templates_alias", "tests/test_parser.py::TestEarleyDynamic::test_templates_import", "tests/test_parser.py::TestEarleyDynamic::test_templates_modifiers", "tests/test_parser.py::TestEarleyDynamic::test_templates_recursion", "tests/test_parser.py::TestEarleyDynamic::test_templates_templates", "tests/test_parser.py::TestEarleyDynamic::test_token_collision", "tests/test_parser.py::TestEarleyDynamic::test_token_collision2", "tests/test_parser.py::TestEarleyDynamic::test_token_collision_WS", "tests/test_parser.py::TestEarleyDynamic::test_token_ebnf", "tests/test_parser.py::TestEarleyDynamic::test_token_flags", "tests/test_parser.py::TestEarleyDynamic::test_token_flags2", "tests/test_parser.py::TestEarleyDynamic::test_token_flags3", "tests/test_parser.py::TestEarleyDynamic::test_token_flags_collision", "tests/test_parser.py::TestEarleyDynamic::test_token_flags_verbose", "tests/test_parser.py::TestEarleyDynamic::test_token_flags_verbose_multiline", "tests/test_parser.py::TestEarleyDynamic::test_token_not_anon", "tests/test_parser.py::TestEarleyDynamic::test_twice_empty", "tests/test_parser.py::TestEarleyDynamic::test_unicode", "tests/test_parser.py::TestEarleyDynamic::test_unicode2", "tests/test_parser.py::TestEarleyDynamic::test_unicode3", "tests/test_parser.py::TestEarleyDynamic::test_unicode4", "tests/test_parser.py::TestEarleyDynamic::test_unicode_literal_range_escape", "tests/test_parser.py::TestEarleyDynamic::test_unicode_literal_range_escape2", "tests/test_parser.py::TestEarleyDynamic::test_utf8", "tests/test_parser.py::TestEarleyDynamic_complete::test_alias", "tests/test_parser.py::TestEarleyDynamic_complete::test_backslash", "tests/test_parser.py::TestEarleyDynamic_complete::test_backslash2", "tests/test_parser.py::TestEarleyDynamic_complete::test_basic1", "tests/test_parser.py::TestEarleyDynamic_complete::test_basic2", "tests/test_parser.py::TestEarleyDynamic_complete::test_bytes_utf8", "tests/test_parser.py::TestEarleyDynamic_complete::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestEarleyDynamic_complete::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestEarleyDynamic_complete::test_dynamic_lexer_prioritization", "tests/test_parser.py::TestEarleyDynamic_complete::test_empty", "tests/test_parser.py::TestEarleyDynamic_complete::test_empty_end", "tests/test_parser.py::TestEarleyDynamic_complete::test_empty_expand1_list", "tests/test_parser.py::TestEarleyDynamic_complete::test_empty_expand1_list_2", "tests/test_parser.py::TestEarleyDynamic_complete::test_empty_flatten_list", "tests/test_parser.py::TestEarleyDynamic_complete::test_escaped_string", "tests/test_parser.py::TestEarleyDynamic_complete::test_expand1_lists_with_one_item", "tests/test_parser.py::TestEarleyDynamic_complete::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestEarleyDynamic_complete::test_float_without_lexer", "tests/test_parser.py::TestEarleyDynamic_complete::test_g_regex_flags", "tests/test_parser.py::TestEarleyDynamic_complete::test_hex_escape", "tests/test_parser.py::TestEarleyDynamic_complete::test_hex_literal_range_escape", "tests/test_parser.py::TestEarleyDynamic_complete::test_ignore", "tests/test_parser.py::TestEarleyDynamic_complete::test_import", "tests/test_parser.py::TestEarleyDynamic_complete::test_import_errors", "tests/test_parser.py::TestEarleyDynamic_complete::test_import_rename", "tests/test_parser.py::TestEarleyDynamic_complete::test_join_regex_flags", "tests/test_parser.py::TestEarleyDynamic_complete::test_keep_all_tokens", "tests/test_parser.py::TestEarleyDynamic_complete::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestEarleyDynamic_complete::test_line_and_column", "tests/test_parser.py::TestEarleyDynamic_complete::test_line_counting", "tests/test_parser.py::TestEarleyDynamic_complete::test_match_examples", "tests/test_parser.py::TestEarleyDynamic_complete::test_maybe", "tests/test_parser.py::TestEarleyDynamic_complete::test_maybe_placeholders", "tests/test_parser.py::TestEarleyDynamic_complete::test_meddling_unused", "tests/test_parser.py::TestEarleyDynamic_complete::test_multi_import", "tests/test_parser.py::TestEarleyDynamic_complete::test_multi_start", "tests/test_parser.py::TestEarleyDynamic_complete::test_prioritization", "tests/test_parser.py::TestEarleyDynamic_complete::test_prioritization_sum", "tests/test_parser.py::TestEarleyDynamic_complete::test_priority_vs_embedded", "tests/test_parser.py::TestEarleyDynamic_complete::test_ranged_repeat_rules", "tests/test_parser.py::TestEarleyDynamic_complete::test_reduce_cycle", "tests/test_parser.py::TestEarleyDynamic_complete::test_regex_escaping", "tests/test_parser.py::TestEarleyDynamic_complete::test_regex_quote", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_import", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_import_rename", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_import_unicode", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_multi_import", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_rule_import", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_rule_import_rename", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_rule_import_subrule", "tests/test_parser.py::TestEarleyDynamic_complete::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestEarleyDynamic_complete::test_rule_collision", "tests/test_parser.py::TestEarleyDynamic_complete::test_rule_collision2", "tests/test_parser.py::TestEarleyDynamic_complete::test_special_chars", "tests/test_parser.py::TestEarleyDynamic_complete::test_stack_for_ebnf", "tests/test_parser.py::TestEarleyDynamic_complete::test_start", "tests/test_parser.py::TestEarleyDynamic_complete::test_stringio_unicode", "tests/test_parser.py::TestEarleyDynamic_complete::test_templates", "tests/test_parser.py::TestEarleyDynamic_complete::test_templates_alias", "tests/test_parser.py::TestEarleyDynamic_complete::test_templates_import", "tests/test_parser.py::TestEarleyDynamic_complete::test_templates_modifiers", "tests/test_parser.py::TestEarleyDynamic_complete::test_templates_recursion", "tests/test_parser.py::TestEarleyDynamic_complete::test_templates_templates", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_collision", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_collision2", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_collision_WS", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_ebnf", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_flags", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_flags2", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_flags3", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_flags_collision", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_flags_verbose", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_flags_verbose_multiline", "tests/test_parser.py::TestEarleyDynamic_complete::test_token_not_anon", "tests/test_parser.py::TestEarleyDynamic_complete::test_twice_empty", "tests/test_parser.py::TestEarleyDynamic_complete::test_unicode", "tests/test_parser.py::TestEarleyDynamic_complete::test_unicode2", "tests/test_parser.py::TestEarleyDynamic_complete::test_unicode3", "tests/test_parser.py::TestEarleyDynamic_complete::test_unicode4", "tests/test_parser.py::TestEarleyDynamic_complete::test_unicode_literal_range_escape", "tests/test_parser.py::TestEarleyDynamic_complete::test_unicode_literal_range_escape2", "tests/test_parser.py::TestEarleyDynamic_complete::test_utf8", "tests/test_parser.py::TestLalrContextual::test_alias", "tests/test_parser.py::TestLalrContextual::test_backslash", "tests/test_parser.py::TestLalrContextual::test_backslash2", "tests/test_parser.py::TestLalrContextual::test_basic1", "tests/test_parser.py::TestLalrContextual::test_basic2", "tests/test_parser.py::TestLalrContextual::test_bytes_utf8", "tests/test_parser.py::TestLalrContextual::test_default_in_treeless_mode", "tests/test_parser.py::TestLalrContextual::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestLalrContextual::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestLalrContextual::test_empty", "tests/test_parser.py::TestLalrContextual::test_empty_end", "tests/test_parser.py::TestLalrContextual::test_empty_expand1_list", "tests/test_parser.py::TestLalrContextual::test_empty_expand1_list_2", "tests/test_parser.py::TestLalrContextual::test_empty_flatten_list", "tests/test_parser.py::TestLalrContextual::test_error_with_interactive_parser", "tests/test_parser.py::TestLalrContextual::test_escaped_string", "tests/test_parser.py::TestLalrContextual::test_expand1_lists_with_one_item", "tests/test_parser.py::TestLalrContextual::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestLalrContextual::test_float_without_lexer", "tests/test_parser.py::TestLalrContextual::test_g_regex_flags", "tests/test_parser.py::TestLalrContextual::test_hex_escape", "tests/test_parser.py::TestLalrContextual::test_hex_literal_range_escape", "tests/test_parser.py::TestLalrContextual::test_ignore", "tests/test_parser.py::TestLalrContextual::test_import", "tests/test_parser.py::TestLalrContextual::test_import_errors", "tests/test_parser.py::TestLalrContextual::test_import_rename", "tests/test_parser.py::TestLalrContextual::test_interactive_treeless_transformer", "tests/test_parser.py::TestLalrContextual::test_iter_parse", "tests/test_parser.py::TestLalrContextual::test_join_regex_flags", "tests/test_parser.py::TestLalrContextual::test_keep_all_tokens", "tests/test_parser.py::TestLalrContextual::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestLalrContextual::test_lexer_prioritization", "tests/test_parser.py::TestLalrContextual::test_line_and_column", "tests/test_parser.py::TestLalrContextual::test_line_counting", "tests/test_parser.py::TestLalrContextual::test_match_examples", "tests/test_parser.py::TestLalrContextual::test_maybe", "tests/test_parser.py::TestLalrContextual::test_maybe_placeholders", "tests/test_parser.py::TestLalrContextual::test_meddling_unused", "tests/test_parser.py::TestLalrContextual::test_multi_import", "tests/test_parser.py::TestLalrContextual::test_multi_start", "tests/test_parser.py::TestLalrContextual::test_parser_interactive_parser", "tests/test_parser.py::TestLalrContextual::test_postlex_declare", "tests/test_parser.py::TestLalrContextual::test_postlex_indenter", "tests/test_parser.py::TestLalrContextual::test_prioritization", "tests/test_parser.py::TestLalrContextual::test_priority_vs_embedded", "tests/test_parser.py::TestLalrContextual::test_ranged_repeat_rules", "tests/test_parser.py::TestLalrContextual::test_reduce_cycle", "tests/test_parser.py::TestLalrContextual::test_regex_escaping", "tests/test_parser.py::TestLalrContextual::test_regex_quote", "tests/test_parser.py::TestLalrContextual::test_relative_import", "tests/test_parser.py::TestLalrContextual::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestLalrContextual::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestLalrContextual::test_relative_import_rename", "tests/test_parser.py::TestLalrContextual::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestLalrContextual::test_relative_import_unicode", "tests/test_parser.py::TestLalrContextual::test_relative_multi_import", "tests/test_parser.py::TestLalrContextual::test_relative_rule_import", "tests/test_parser.py::TestLalrContextual::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestLalrContextual::test_relative_rule_import_rename", "tests/test_parser.py::TestLalrContextual::test_relative_rule_import_subrule", "tests/test_parser.py::TestLalrContextual::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestLalrContextual::test_rule_collision", "tests/test_parser.py::TestLalrContextual::test_rule_collision2", "tests/test_parser.py::TestLalrContextual::test_serialize", "tests/test_parser.py::TestLalrContextual::test_special_chars", "tests/test_parser.py::TestLalrContextual::test_stack_for_ebnf", "tests/test_parser.py::TestLalrContextual::test_start", "tests/test_parser.py::TestLalrContextual::test_strict", "tests/test_parser.py::TestLalrContextual::test_stringio_unicode", "tests/test_parser.py::TestLalrContextual::test_templates", "tests/test_parser.py::TestLalrContextual::test_templates_alias", "tests/test_parser.py::TestLalrContextual::test_templates_import", "tests/test_parser.py::TestLalrContextual::test_templates_modifiers", "tests/test_parser.py::TestLalrContextual::test_templates_recursion", "tests/test_parser.py::TestLalrContextual::test_templates_templates", "tests/test_parser.py::TestLalrContextual::test_token_collision", "tests/test_parser.py::TestLalrContextual::test_token_collision2", "tests/test_parser.py::TestLalrContextual::test_token_collision_WS", "tests/test_parser.py::TestLalrContextual::test_token_ebnf", "tests/test_parser.py::TestLalrContextual::test_token_flags", "tests/test_parser.py::TestLalrContextual::test_token_flags2", "tests/test_parser.py::TestLalrContextual::test_token_flags3", "tests/test_parser.py::TestLalrContextual::test_token_flags_collision", "tests/test_parser.py::TestLalrContextual::test_token_flags_verbose", "tests/test_parser.py::TestLalrContextual::test_token_flags_verbose_multiline", "tests/test_parser.py::TestLalrContextual::test_token_not_anon", "tests/test_parser.py::TestLalrContextual::test_twice_empty", "tests/test_parser.py::TestLalrContextual::test_unicode", "tests/test_parser.py::TestLalrContextual::test_unicode2", "tests/test_parser.py::TestLalrContextual::test_unicode3", "tests/test_parser.py::TestLalrContextual::test_unicode4", "tests/test_parser.py::TestLalrContextual::test_unicode_literal_range_escape", "tests/test_parser.py::TestLalrContextual::test_unicode_literal_range_escape2", "tests/test_parser.py::TestLalrContextual::test_utf8", "tests/test_parser.py::TestLalrCustom_new::test_alias", "tests/test_parser.py::TestLalrCustom_new::test_backslash", "tests/test_parser.py::TestLalrCustom_new::test_backslash2", "tests/test_parser.py::TestLalrCustom_new::test_basic1", "tests/test_parser.py::TestLalrCustom_new::test_basic2", "tests/test_parser.py::TestLalrCustom_new::test_bytes_utf8", "tests/test_parser.py::TestLalrCustom_new::test_default_in_treeless_mode", "tests/test_parser.py::TestLalrCustom_new::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestLalrCustom_new::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestLalrCustom_new::test_empty", "tests/test_parser.py::TestLalrCustom_new::test_empty_end", "tests/test_parser.py::TestLalrCustom_new::test_empty_expand1_list", "tests/test_parser.py::TestLalrCustom_new::test_empty_expand1_list_2", "tests/test_parser.py::TestLalrCustom_new::test_empty_flatten_list", "tests/test_parser.py::TestLalrCustom_new::test_error_with_interactive_parser", "tests/test_parser.py::TestLalrCustom_new::test_escaped_string", "tests/test_parser.py::TestLalrCustom_new::test_expand1_lists_with_one_item", "tests/test_parser.py::TestLalrCustom_new::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestLalrCustom_new::test_float_without_lexer", "tests/test_parser.py::TestLalrCustom_new::test_g_regex_flags", "tests/test_parser.py::TestLalrCustom_new::test_hex_escape", "tests/test_parser.py::TestLalrCustom_new::test_hex_literal_range_escape", "tests/test_parser.py::TestLalrCustom_new::test_ignore", "tests/test_parser.py::TestLalrCustom_new::test_import", "tests/test_parser.py::TestLalrCustom_new::test_import_errors", "tests/test_parser.py::TestLalrCustom_new::test_import_rename", "tests/test_parser.py::TestLalrCustom_new::test_interactive_treeless_transformer", "tests/test_parser.py::TestLalrCustom_new::test_iter_parse", "tests/test_parser.py::TestLalrCustom_new::test_join_regex_flags", "tests/test_parser.py::TestLalrCustom_new::test_keep_all_tokens", "tests/test_parser.py::TestLalrCustom_new::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestLalrCustom_new::test_lexer_prioritization", "tests/test_parser.py::TestLalrCustom_new::test_line_and_column", "tests/test_parser.py::TestLalrCustom_new::test_line_counting", "tests/test_parser.py::TestLalrCustom_new::test_match_examples", "tests/test_parser.py::TestLalrCustom_new::test_maybe", "tests/test_parser.py::TestLalrCustom_new::test_maybe_placeholders", "tests/test_parser.py::TestLalrCustom_new::test_meddling_unused", "tests/test_parser.py::TestLalrCustom_new::test_multi_import", "tests/test_parser.py::TestLalrCustom_new::test_multi_start", "tests/test_parser.py::TestLalrCustom_new::test_parser_interactive_parser", "tests/test_parser.py::TestLalrCustom_new::test_postlex_declare", "tests/test_parser.py::TestLalrCustom_new::test_postlex_indenter", "tests/test_parser.py::TestLalrCustom_new::test_prioritization", "tests/test_parser.py::TestLalrCustom_new::test_priority_vs_embedded", "tests/test_parser.py::TestLalrCustom_new::test_ranged_repeat_rules", "tests/test_parser.py::TestLalrCustom_new::test_reduce_cycle", "tests/test_parser.py::TestLalrCustom_new::test_regex_escaping", "tests/test_parser.py::TestLalrCustom_new::test_regex_quote", "tests/test_parser.py::TestLalrCustom_new::test_relative_import", "tests/test_parser.py::TestLalrCustom_new::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestLalrCustom_new::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestLalrCustom_new::test_relative_import_rename", "tests/test_parser.py::TestLalrCustom_new::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestLalrCustom_new::test_relative_import_unicode", "tests/test_parser.py::TestLalrCustom_new::test_relative_multi_import", "tests/test_parser.py::TestLalrCustom_new::test_relative_rule_import", "tests/test_parser.py::TestLalrCustom_new::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestLalrCustom_new::test_relative_rule_import_rename", "tests/test_parser.py::TestLalrCustom_new::test_relative_rule_import_subrule", "tests/test_parser.py::TestLalrCustom_new::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestLalrCustom_new::test_rule_collision", "tests/test_parser.py::TestLalrCustom_new::test_rule_collision2", "tests/test_parser.py::TestLalrCustom_new::test_serialize", "tests/test_parser.py::TestLalrCustom_new::test_special_chars", "tests/test_parser.py::TestLalrCustom_new::test_stack_for_ebnf", "tests/test_parser.py::TestLalrCustom_new::test_start", "tests/test_parser.py::TestLalrCustom_new::test_strict", "tests/test_parser.py::TestLalrCustom_new::test_stringio_unicode", "tests/test_parser.py::TestLalrCustom_new::test_templates", "tests/test_parser.py::TestLalrCustom_new::test_templates_alias", "tests/test_parser.py::TestLalrCustom_new::test_templates_import", "tests/test_parser.py::TestLalrCustom_new::test_templates_modifiers", "tests/test_parser.py::TestLalrCustom_new::test_templates_recursion", "tests/test_parser.py::TestLalrCustom_new::test_templates_templates", "tests/test_parser.py::TestLalrCustom_new::test_token_collision", "tests/test_parser.py::TestLalrCustom_new::test_token_collision2", "tests/test_parser.py::TestLalrCustom_new::test_token_collision_WS", "tests/test_parser.py::TestLalrCustom_new::test_token_ebnf", "tests/test_parser.py::TestLalrCustom_new::test_token_flags", "tests/test_parser.py::TestLalrCustom_new::test_token_flags2", "tests/test_parser.py::TestLalrCustom_new::test_token_flags3", "tests/test_parser.py::TestLalrCustom_new::test_token_flags_verbose", "tests/test_parser.py::TestLalrCustom_new::test_token_flags_verbose_multiline", "tests/test_parser.py::TestLalrCustom_new::test_token_not_anon", "tests/test_parser.py::TestLalrCustom_new::test_twice_empty", "tests/test_parser.py::TestLalrCustom_new::test_unicode", "tests/test_parser.py::TestLalrCustom_new::test_unicode2", "tests/test_parser.py::TestLalrCustom_new::test_unicode3", "tests/test_parser.py::TestLalrCustom_new::test_unicode4", "tests/test_parser.py::TestLalrCustom_new::test_unicode_literal_range_escape", "tests/test_parser.py::TestLalrCustom_new::test_unicode_literal_range_escape2", "tests/test_parser.py::TestLalrCustom_new::test_utf8", "tests/test_parser.py::TestCykCustom_new::test_alias", "tests/test_parser.py::TestCykCustom_new::test_backslash", "tests/test_parser.py::TestCykCustom_new::test_backslash2", "tests/test_parser.py::TestCykCustom_new::test_basic1", "tests/test_parser.py::TestCykCustom_new::test_basic2", "tests/test_parser.py::TestCykCustom_new::test_bytes_utf8", "tests/test_parser.py::TestCykCustom_new::test_default_in_treeless_mode", "tests/test_parser.py::TestCykCustom_new::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestCykCustom_new::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestCykCustom_new::test_escaped_string", "tests/test_parser.py::TestCykCustom_new::test_expand1_lists_with_one_item", "tests/test_parser.py::TestCykCustom_new::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestCykCustom_new::test_float_without_lexer", "tests/test_parser.py::TestCykCustom_new::test_g_regex_flags", "tests/test_parser.py::TestCykCustom_new::test_hex_escape", "tests/test_parser.py::TestCykCustom_new::test_hex_literal_range_escape", "tests/test_parser.py::TestCykCustom_new::test_import", "tests/test_parser.py::TestCykCustom_new::test_import_errors", "tests/test_parser.py::TestCykCustom_new::test_import_rename", "tests/test_parser.py::TestCykCustom_new::test_join_regex_flags", "tests/test_parser.py::TestCykCustom_new::test_keep_all_tokens", "tests/test_parser.py::TestCykCustom_new::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestCykCustom_new::test_lexer_prioritization", "tests/test_parser.py::TestCykCustom_new::test_line_and_column", "tests/test_parser.py::TestCykCustom_new::test_line_counting", "tests/test_parser.py::TestCykCustom_new::test_meddling_unused", "tests/test_parser.py::TestCykCustom_new::test_multi_import", "tests/test_parser.py::TestCykCustom_new::test_multi_start", "tests/test_parser.py::TestCykCustom_new::test_postlex_declare", "tests/test_parser.py::TestCykCustom_new::test_postlex_indenter", "tests/test_parser.py::TestCykCustom_new::test_priority_vs_embedded", "tests/test_parser.py::TestCykCustom_new::test_ranged_repeat_rules", "tests/test_parser.py::TestCykCustom_new::test_reduce_cycle", "tests/test_parser.py::TestCykCustom_new::test_regex_escaping", "tests/test_parser.py::TestCykCustom_new::test_regex_quote", "tests/test_parser.py::TestCykCustom_new::test_relative_import", "tests/test_parser.py::TestCykCustom_new::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestCykCustom_new::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestCykCustom_new::test_relative_import_rename", "tests/test_parser.py::TestCykCustom_new::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestCykCustom_new::test_relative_import_unicode", "tests/test_parser.py::TestCykCustom_new::test_relative_multi_import", "tests/test_parser.py::TestCykCustom_new::test_relative_rule_import", "tests/test_parser.py::TestCykCustom_new::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestCykCustom_new::test_relative_rule_import_rename", "tests/test_parser.py::TestCykCustom_new::test_relative_rule_import_subrule", "tests/test_parser.py::TestCykCustom_new::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestCykCustom_new::test_rule_collision", "tests/test_parser.py::TestCykCustom_new::test_rule_collision2", "tests/test_parser.py::TestCykCustom_new::test_special_chars", "tests/test_parser.py::TestCykCustom_new::test_start", "tests/test_parser.py::TestCykCustom_new::test_stringio_unicode", "tests/test_parser.py::TestCykCustom_new::test_templates", "tests/test_parser.py::TestCykCustom_new::test_templates_alias", "tests/test_parser.py::TestCykCustom_new::test_templates_import", "tests/test_parser.py::TestCykCustom_new::test_templates_modifiers", "tests/test_parser.py::TestCykCustom_new::test_templates_recursion", "tests/test_parser.py::TestCykCustom_new::test_templates_templates", "tests/test_parser.py::TestCykCustom_new::test_token_collision", "tests/test_parser.py::TestCykCustom_new::test_token_collision2", "tests/test_parser.py::TestCykCustom_new::test_token_collision_WS", "tests/test_parser.py::TestCykCustom_new::test_token_ebnf", "tests/test_parser.py::TestCykCustom_new::test_token_flags", "tests/test_parser.py::TestCykCustom_new::test_token_flags2", "tests/test_parser.py::TestCykCustom_new::test_token_flags3", "tests/test_parser.py::TestCykCustom_new::test_token_flags_verbose", "tests/test_parser.py::TestCykCustom_new::test_token_flags_verbose_multiline", "tests/test_parser.py::TestCykCustom_new::test_token_not_anon", "tests/test_parser.py::TestCykCustom_new::test_unicode", "tests/test_parser.py::TestCykCustom_new::test_unicode2", "tests/test_parser.py::TestCykCustom_new::test_unicode3", "tests/test_parser.py::TestCykCustom_new::test_unicode4", "tests/test_parser.py::TestCykCustom_new::test_unicode_literal_range_escape", "tests/test_parser.py::TestCykCustom_new::test_unicode_literal_range_escape2", "tests/test_parser.py::TestCykCustom_new::test_utf8", "tests/test_parser.py::TestEarleyCustom_old::test_alias", "tests/test_parser.py::TestEarleyCustom_old::test_backslash", "tests/test_parser.py::TestEarleyCustom_old::test_backslash2", "tests/test_parser.py::TestEarleyCustom_old::test_basic1", "tests/test_parser.py::TestEarleyCustom_old::test_basic2", "tests/test_parser.py::TestEarleyCustom_old::test_bytes_utf8", "tests/test_parser.py::TestEarleyCustom_old::test_dont_expand1_lists_with_multiple_items", "tests/test_parser.py::TestEarleyCustom_old::test_dont_expand1_lists_with_multiple_items_2", "tests/test_parser.py::TestEarleyCustom_old::test_empty", "tests/test_parser.py::TestEarleyCustom_old::test_empty_end", "tests/test_parser.py::TestEarleyCustom_old::test_empty_expand1_list", "tests/test_parser.py::TestEarleyCustom_old::test_empty_expand1_list_2", "tests/test_parser.py::TestEarleyCustom_old::test_empty_flatten_list", "tests/test_parser.py::TestEarleyCustom_old::test_escaped_string", "tests/test_parser.py::TestEarleyCustom_old::test_expand1_lists_with_one_item", "tests/test_parser.py::TestEarleyCustom_old::test_expand1_lists_with_one_item_2", "tests/test_parser.py::TestEarleyCustom_old::test_float_without_lexer", "tests/test_parser.py::TestEarleyCustom_old::test_g_regex_flags", "tests/test_parser.py::TestEarleyCustom_old::test_hex_escape", "tests/test_parser.py::TestEarleyCustom_old::test_hex_literal_range_escape", "tests/test_parser.py::TestEarleyCustom_old::test_ignore", "tests/test_parser.py::TestEarleyCustom_old::test_import", "tests/test_parser.py::TestEarleyCustom_old::test_import_errors", "tests/test_parser.py::TestEarleyCustom_old::test_import_rename", "tests/test_parser.py::TestEarleyCustom_old::test_join_regex_flags", "tests/test_parser.py::TestEarleyCustom_old::test_keep_all_tokens", "tests/test_parser.py::TestEarleyCustom_old::test_lexer_detect_newline_tokens", "tests/test_parser.py::TestEarleyCustom_old::test_lexer_prioritization", "tests/test_parser.py::TestEarleyCustom_old::test_line_and_column", "tests/test_parser.py::TestEarleyCustom_old::test_line_counting", "tests/test_parser.py::TestEarleyCustom_old::test_maybe", "tests/test_parser.py::TestEarleyCustom_old::test_maybe_placeholders", "tests/test_parser.py::TestEarleyCustom_old::test_meddling_unused", "tests/test_parser.py::TestEarleyCustom_old::test_multi_import", "tests/test_parser.py::TestEarleyCustom_old::test_multi_start", "tests/test_parser.py::TestEarleyCustom_old::test_postlex_declare", "tests/test_parser.py::TestEarleyCustom_old::test_postlex_indenter", "tests/test_parser.py::TestEarleyCustom_old::test_prioritization", "tests/test_parser.py::TestEarleyCustom_old::test_priority_vs_embedded", "tests/test_parser.py::TestEarleyCustom_old::test_ranged_repeat_rules", "tests/test_parser.py::TestEarleyCustom_old::test_reduce_cycle", "tests/test_parser.py::TestEarleyCustom_old::test_regex_escaping", "tests/test_parser.py::TestEarleyCustom_old::test_regex_quote", "tests/test_parser.py::TestEarleyCustom_old::test_relative_import", "tests/test_parser.py::TestEarleyCustom_old::test_relative_import_of_nested_grammar", "tests/test_parser.py::TestEarleyCustom_old::test_relative_import_preserves_leading_underscore", "tests/test_parser.py::TestEarleyCustom_old::test_relative_import_rename", "tests/test_parser.py::TestEarleyCustom_old::test_relative_import_rules_dependencies_imported_only_once", "tests/test_parser.py::TestEarleyCustom_old::test_relative_import_unicode", "tests/test_parser.py::TestEarleyCustom_old::test_relative_multi_import", "tests/test_parser.py::TestEarleyCustom_old::test_relative_rule_import", "tests/test_parser.py::TestEarleyCustom_old::test_relative_rule_import_drop_ignore", "tests/test_parser.py::TestEarleyCustom_old::test_relative_rule_import_rename", "tests/test_parser.py::TestEarleyCustom_old::test_relative_rule_import_subrule", "tests/test_parser.py::TestEarleyCustom_old::test_relative_rule_import_subrule_no_conflict", "tests/test_parser.py::TestEarleyCustom_old::test_rule_collision", "tests/test_parser.py::TestEarleyCustom_old::test_rule_collision2", "tests/test_parser.py::TestEarleyCustom_old::test_special_chars", "tests/test_parser.py::TestEarleyCustom_old::test_stack_for_ebnf", "tests/test_parser.py::TestEarleyCustom_old::test_start", "tests/test_parser.py::TestEarleyCustom_old::test_stringio_unicode", "tests/test_parser.py::TestEarleyCustom_old::test_templates", "tests/test_parser.py::TestEarleyCustom_old::test_templates_alias", "tests/test_parser.py::TestEarleyCustom_old::test_templates_import", "tests/test_parser.py::TestEarleyCustom_old::test_templates_modifiers", "tests/test_parser.py::TestEarleyCustom_old::test_templates_recursion", "tests/test_parser.py::TestEarleyCustom_old::test_templates_templates", "tests/test_parser.py::TestEarleyCustom_old::test_token_collision", "tests/test_parser.py::TestEarleyCustom_old::test_token_collision2", "tests/test_parser.py::TestEarleyCustom_old::test_token_collision_WS", "tests/test_parser.py::TestEarleyCustom_old::test_token_ebnf", "tests/test_parser.py::TestEarleyCustom_old::test_token_flags", "tests/test_parser.py::TestEarleyCustom_old::test_token_flags2", "tests/test_parser.py::TestEarleyCustom_old::test_token_flags3", "tests/test_parser.py::TestEarleyCustom_old::test_token_flags_verbose", "tests/test_parser.py::TestEarleyCustom_old::test_token_flags_verbose_multiline", "tests/test_parser.py::TestEarleyCustom_old::test_token_not_anon", "tests/test_parser.py::TestEarleyCustom_old::test_twice_empty", "tests/test_parser.py::TestEarleyCustom_old::test_unicode", "tests/test_parser.py::TestEarleyCustom_old::test_unicode2", "tests/test_parser.py::TestEarleyCustom_old::test_unicode3", "tests/test_parser.py::TestEarleyCustom_old::test_unicode4", "tests/test_parser.py::TestEarleyCustom_old::test_unicode_literal_range_escape", "tests/test_parser.py::TestEarleyCustom_old::test_unicode_literal_range_escape2", "tests/test_parser.py::TestEarleyCustom_old::test_utf8", "tests/test_parser.py::TestFullEarleyBasic::test_ambiguous_inlined_rule", "tests/test_parser.py::TestFullEarleyBasic::test_ambiguous_intermediate_node", "tests/test_parser.py::TestFullEarleyBasic::test_ambiguous_intermediate_node_conditionally_inlined_rule", "tests/test_parser.py::TestFullEarleyBasic::test_ambiguous_intermediate_node_inlined_rule", "tests/test_parser.py::TestFullEarleyBasic::test_ambiguous_intermediate_node_unnamed_token", "tests/test_parser.py::TestFullEarleyBasic::test_ambiguous_symbol_and_intermediate_nodes", "tests/test_parser.py::TestFullEarleyBasic::test_anon", "tests/test_parser.py::TestFullEarleyBasic::test_cycle", "tests/test_parser.py::TestFullEarleyBasic::test_cycle2", "tests/test_parser.py::TestFullEarleyBasic::test_cycles", "tests/test_parser.py::TestFullEarleyBasic::test_cycles_with_child_filter", "tests/test_parser.py::TestFullEarleyBasic::test_earley2", "tests/test_parser.py::TestFullEarleyBasic::test_earley4", "tests/test_parser.py::TestFullEarleyBasic::test_earley_repeating_empty", "tests/test_parser.py::TestFullEarleyBasic::test_many_cycles", "tests/test_parser.py::TestFullEarleyBasic::test_multiple_start_solutions", "tests/test_parser.py::TestFullEarleyBasic::test_nested_ambiguous_intermediate_nodes", "tests/test_parser.py::TestFullEarleyBasic::test_nested_ambiguous_intermediate_nodes2", "tests/test_parser.py::TestFullEarleyBasic::test_term_ambig_resolve", "tests/test_parser.py::TestFullEarleyDynamic::test_ambiguity1", "tests/test_parser.py::TestFullEarleyDynamic::test_ambiguity2", "tests/test_parser.py::TestFullEarleyDynamic::test_ambiguous_inlined_rule", "tests/test_parser.py::TestFullEarleyDynamic::test_ambiguous_intermediate_node", "tests/test_parser.py::TestFullEarleyDynamic::test_ambiguous_intermediate_node_conditionally_inlined_rule", "tests/test_parser.py::TestFullEarleyDynamic::test_ambiguous_intermediate_node_inlined_rule", "tests/test_parser.py::TestFullEarleyDynamic::test_ambiguous_intermediate_node_unnamed_token", "tests/test_parser.py::TestFullEarleyDynamic::test_ambiguous_symbol_and_intermediate_nodes", "tests/test_parser.py::TestFullEarleyDynamic::test_anon", "tests/test_parser.py::TestFullEarleyDynamic::test_cycle", "tests/test_parser.py::TestFullEarleyDynamic::test_cycle2", "tests/test_parser.py::TestFullEarleyDynamic::test_cycles", "tests/test_parser.py::TestFullEarleyDynamic::test_cycles_with_child_filter", "tests/test_parser.py::TestFullEarleyDynamic::test_earley", "tests/test_parser.py::TestFullEarleyDynamic::test_earley2", "tests/test_parser.py::TestFullEarleyDynamic::test_earley4", "tests/test_parser.py::TestFullEarleyDynamic::test_earley_explicit_ambiguity", "tests/test_parser.py::TestFullEarleyDynamic::test_earley_repeating_empty", "tests/test_parser.py::TestFullEarleyDynamic::test_fruitflies_ambig", "tests/test_parser.py::TestFullEarleyDynamic::test_many_cycles", "tests/test_parser.py::TestFullEarleyDynamic::test_multiple_start_solutions", "tests/test_parser.py::TestFullEarleyDynamic::test_nested_ambiguous_intermediate_nodes", "tests/test_parser.py::TestFullEarleyDynamic::test_nested_ambiguous_intermediate_nodes2", "tests/test_parser.py::TestFullEarleyDynamic::test_symbol_node_start_end_dynamic_lexer", "tests/test_parser.py::TestFullEarleyDynamic::test_term_ambig_resolve", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_ambiguity1", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_ambiguity2", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_ambiguous_inlined_rule", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_ambiguous_intermediate_node", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_ambiguous_intermediate_node_conditionally_inlined_rule", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_ambiguous_intermediate_node_inlined_rule", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_ambiguous_intermediate_node_unnamed_token", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_ambiguous_symbol_and_intermediate_nodes", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_anon", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_cycle", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_cycle2", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_cycles", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_cycles_with_child_filter", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_earley", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_earley2", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_earley3", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_earley4", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_earley_explicit_ambiguity", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_earley_repeating_empty", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_explicit_ambiguity2", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_fruitflies_ambig", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_many_cycles", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_multiple_start_solutions", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_nested_ambiguous_intermediate_nodes", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_nested_ambiguous_intermediate_nodes2", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_symbol_node_start_end_dynamic_lexer", "tests/test_parser.py::TestFullEarleyDynamic_complete::test_term_ambig_resolve" ]
[]
MIT License
18,817
479
[ "lark/parsers/earley.py", "lark/parsers/earley_forest.py" ]
sanic-org__sanic-2976
24cf099bcaf7b3a1f1221489415359540b5ce692
2024-06-28 07:56:14
24cf099bcaf7b3a1f1221489415359540b5ce692
diff --git a/sanic/cookies/response.py b/sanic/cookies/response.py index a0e18d19..e84a24d8 100644 --- a/sanic/cookies/response.py +++ b/sanic/cookies/response.py @@ -363,6 +363,7 @@ class CookieJar(dict): *, path: str = "/", domain: Optional[str] = None, + secure: bool = True, host_prefix: bool = False, secure_prefix: bool = False, ) -> None: @@ -381,6 +382,8 @@ class CookieJar(dict): :type path: Optional[str], optional :param domain: Domain of the cookie, defaults to None :type domain: Optional[str], optional + :param secure: Whether to delete a secure cookie. Defaults to True. + :param secure: bool :param host_prefix: Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True, defaults to False @@ -389,8 +392,18 @@ class CookieJar(dict): This requires that secure=True, defaults to False :type secure_prefix: bool """ - # remove it from header + if host_prefix and not (secure and path == "/" and domain is None): + raise ServerError( + "Cannot set host_prefix on a cookie without " + "path='/', domain=None, and secure=True" + ) + if secure_prefix and not secure: + raise ServerError( + "Cannot set secure_prefix on a cookie without secure=True" + ) + cookies: List[Cookie] = self.headers.popall(self.HEADER_KEY, []) + existing_cookie = None for cookie in cookies: if ( cookie.key != Cookie.make_key(key, host_prefix, secure_prefix) @@ -398,23 +411,42 @@ class CookieJar(dict): or cookie.domain != domain ): self.headers.add(self.HEADER_KEY, cookie) - + elif existing_cookie is None: + existing_cookie = cookie # This should be removed in v24.3 try: super().__delitem__(key) except KeyError: ... - self.add_cookie( - key=key, - value="", - path=path, - domain=domain, - max_age=0, - samesite=None, - host_prefix=host_prefix, - secure_prefix=secure_prefix, - ) + if existing_cookie is not None: + # Use all the same values as the cookie to be deleted + # except value="" and max_age=0 + self.add_cookie( + key=key, + value="", + path=existing_cookie.path, + domain=existing_cookie.domain, + secure=existing_cookie.secure, + max_age=0, + httponly=existing_cookie.httponly, + partitioned=existing_cookie.partitioned, + samesite=existing_cookie.samesite, + host_prefix=host_prefix, + secure_prefix=secure_prefix, + ) + else: + self.add_cookie( + key=key, + value="", + path=path, + domain=domain, + secure=secure, + max_age=0, + samesite=None, + host_prefix=host_prefix, + secure_prefix=secure_prefix, + ) # In v24.3, we should remove this as being a subclass of dict
Cannot delete cookies due to missing `secure` parameter ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug The `delete_cookie` method in `CookieJar` lacks the `secure` parameter, and this parameter in [its internal call to `self.add_cookie`](https://github.com/sanic-org/sanic/blob/39d4ea49761bb2221cd6cb970a41e9099990273f/sanic/cookies/response.py#L408) default to True. Therefore, attempts to delete a cookie in an insecure (plain HTTP) origin will be always blocked by the browser because it will set the `;Secure` flag: ![image](https://github.com/sanic-org/sanic/assets/6646473/1dade3d9-607f-429b-b31b-c612e6de5145) ### Code snippet ```python from sanic import Sanic from sanic.response import text, redirect app = Sanic("test") app.config.AUTO_EXTEND = False @app.get("/") async def index(request): return text(f'logged in: {"YES" if request.cookies.get("session", None) else "NO"}') @app.get("/login") async def login(request): res = redirect('/') res.cookies.add_cookie('session', 'foobar', secure=False) return res @app.get("/logout") async def logout(request): res = redirect('/') res.cookies.delete_cookie('session') return res if __name__ == '__main__': app.run(host='0.0.0.0', port=4321, debug=True) ``` 1. Visit `http://YOUR_IP:4321/` and the page says `logged in: NO` 2. Visit `http://YOUR_IP:4321/login` and the page says `logged in: YES` 3. Visit `http://YOUR_IP:4321/logout` and the page still says `logged in: YES` Note: it is important to use the real IP address (instead of 127.0.0.1) to reproduce this bug, since 127.0.0.1 is a secure origin. ### Expected Behavior Sanic should add an optional `secure` parameter to `delete_cookie` method, so we can write something like `res.cookies.delete_cookie('session', secure=False)`. Then the page should say `logged in: NO` after visiting `/logout`. ### How do you run Sanic? As a script (`app.run` or `Sanic.serve`) ### Operating System Linux ### Sanic Version v23.12.1 ### Additional context _No response_
sanic-org/sanic
diff --git a/tests/test_cookies.py b/tests/test_cookies.py index 599a24ef..18c01a3a 100644 --- a/tests/test_cookies.py +++ b/tests/test_cookies.py @@ -380,6 +380,67 @@ def test_cookie_jar_delete_cookie_encode(): ] +def test_cookie_jar_delete_nonsecure_cookie(): + headers = Header() + jar = CookieJar(headers) + jar.delete_cookie("foo", domain="example.com", secure=False) + + encoded = [cookie.encode("ascii") for cookie in jar.cookies] + assert encoded == [ + b'foo=""; Path=/; Domain=example.com; Max-Age=0', + ] + + +def test_cookie_jar_delete_existing_cookie(): + headers = Header() + jar = CookieJar(headers) + jar.add_cookie( + "foo", "test", secure=True, domain="example.com", samesite="Strict" + ) + jar.delete_cookie("foo", domain="example.com", secure=True) + + encoded = [cookie.encode("ascii") for cookie in jar.cookies] + # deletion cookie contains samesite=Strict as was in original cookie + assert encoded == [ + b'foo=""; Path=/; Domain=example.com; Max-Age=0; SameSite=Strict; Secure', + ] + + +def test_cookie_jar_delete_existing_nonsecure_cookie(): + headers = Header() + jar = CookieJar(headers) + jar.add_cookie( + "foo", "test", secure=False, domain="example.com", samesite="Strict" + ) + jar.delete_cookie("foo", domain="example.com", secure=False) + + encoded = [cookie.encode("ascii") for cookie in jar.cookies] + # deletion cookie contains samesite=Strict as was in original cookie + assert encoded == [ + b'foo=""; Path=/; Domain=example.com; Max-Age=0; SameSite=Strict', + ] + + +def test_cookie_jar_delete_existing_nonsecure_cookie_bad_prefix(): + headers = Header() + jar = CookieJar(headers) + jar.add_cookie( + "foo", "test", secure=False, domain="example.com", samesite="Strict" + ) + message = ( + "Cannot set host_prefix on a cookie without " + "path='/', domain=None, and secure=True" + ) + with pytest.raises(ServerError, match=message): + jar.delete_cookie( + "foo", + domain="example.com", + secure=False, + secure_prefix=True, + host_prefix=True, + ) + + def test_cookie_jar_old_school_delete_encode(): headers = Header() jar = CookieJar(headers)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
23.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiofiles==24.1.0 anyio==4.9.0 async-generator==1.10 bandit==1.8.3 beautifulsoup4==4.13.3 certifi==2025.1.31 cffi==1.17.1 chardet==3.0.4 click==8.1.8 coverage==7.8.0 cryptography==44.0.2 distlib==0.3.9 docutils==0.21.2 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 h11==0.14.0 html5tagger==1.3.0 httpcore==1.0.7 httptools==0.6.4 httpx==0.28.1 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 markdown-it-py==3.0.0 MarkupSafe==3.0.2 mdurl==0.1.2 multidict==6.2.0 mypy==1.15.0 mypy-extensions==1.0.0 packaging @ file:///croot/packaging_1734472117206/work pbr==6.1.1 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work py==1.11.0 py-cpuinfo==9.0.0 pycparser==2.22 Pygments==2.19.1 pytest @ file:///croot/pytest_1738938843180/work pytest-benchmark==5.1.0 pytest-sanic==1.9.1 PyYAML==6.0.2 rich==14.0.0 ruff==0.11.2 -e git+https://github.com/sanic-org/sanic.git@24cf099bcaf7b3a1f1221489415359540b5ce692#egg=sanic sanic-routing==23.12.0 sanic-testing==24.6.0 six==1.17.0 slotscheck==0.19.1 sniffio==1.3.1 soupsieve==2.6 stevedore==5.4.1 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work towncrier==24.8.0 tox==3.28.0 tracerite==1.1.1 types-ujson==5.10.0.20250326 typing_extensions==4.13.0 ujson==5.10.0 uvicorn==0.34.0 uvloop==0.21.0 virtualenv==20.29.3 websockets==10.4 zipp==3.21.0
name: sanic channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aiofiles==24.1.0 - anyio==4.9.0 - async-generator==1.10 - bandit==1.8.3 - beautifulsoup4==4.13.3 - certifi==2025.1.31 - cffi==1.17.1 - chardet==3.0.4 - click==8.1.8 - coverage==7.8.0 - cryptography==44.0.2 - distlib==0.3.9 - docutils==0.21.2 - filelock==3.18.0 - h11==0.14.0 - html5tagger==1.3.0 - httpcore==1.0.7 - httptools==0.6.4 - httpx==0.28.1 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - jinja2==3.1.6 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - mdurl==0.1.2 - multidict==6.2.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - pbr==6.1.1 - platformdirs==4.3.7 - py==1.11.0 - py-cpuinfo==9.0.0 - pycparser==2.22 - pygments==2.19.1 - pytest-benchmark==5.1.0 - pytest-sanic==1.9.1 - pyyaml==6.0.2 - rich==14.0.0 - ruff==0.11.2 - sanic==24.3.0.dev0 - sanic-routing==23.12.0 - sanic-testing==24.6.0 - six==1.17.0 - slotscheck==0.19.1 - sniffio==1.3.1 - soupsieve==2.6 - stevedore==5.4.1 - towncrier==24.8.0 - tox==3.28.0 - tracerite==1.1.1 - types-ujson==5.10.0.20250326 - typing-extensions==4.13.0 - ujson==5.10.0 - uvicorn==0.34.0 - uvloop==0.21.0 - virtualenv==20.29.3 - websockets==10.4 - zipp==3.21.0 prefix: /opt/conda/envs/sanic
[ "tests/test_cookies.py::test_cookie_jar_delete_nonsecure_cookie", "tests/test_cookies.py::test_cookie_jar_delete_existing_cookie", "tests/test_cookies.py::test_cookie_jar_delete_existing_nonsecure_cookie", "tests/test_cookies.py::test_cookie_jar_delete_existing_nonsecure_cookie_bad_prefix" ]
[]
[ "tests/test_cookies.py::test_request_cookies", "tests/test_cookies.py::test_cookies", "tests/test_cookies.py::test_cookies_asgi", "tests/test_cookies.py::test_false_cookies_encoded[False-False]", "tests/test_cookies.py::test_false_cookies_encoded[True-True]", "tests/test_cookies.py::test_false_cookies[False-False]", "tests/test_cookies.py::test_false_cookies[True-True]", "tests/test_cookies.py::test_http2_cookies", "tests/test_cookies.py::test_cookie_options", "tests/test_cookies.py::test_cookie_deletion", "tests/test_cookies.py::test_cookie_reserved_cookie", "tests/test_cookies.py::test_cookie_illegal_key_format", "tests/test_cookies.py::test_cookie_set_unknown_property", "tests/test_cookies.py::test_cookie_set_same_key", "tests/test_cookies.py::test_cookie_max_age[0]", "tests/test_cookies.py::test_cookie_max_age[30_0]", "tests/test_cookies.py::test_cookie_max_age[30_1]", "tests/test_cookies.py::test_cookie_bad_max_age[30.0]", "tests/test_cookies.py::test_cookie_bad_max_age[30.1]", "tests/test_cookies.py::test_cookie_bad_max_age[test]", "tests/test_cookies.py::test_cookie_expires[expires0]", "tests/test_cookies.py::test_cookie_expires_illegal_instance_type[Fri,", "tests/test_cookies.py::test_request_with_duplicate_cookie_key[foo=one;", "tests/test_cookies.py::test_request_with_duplicate_cookie_key[foo=one;foo=two]", "tests/test_cookies.py::test_cookie_jar_cookies", "tests/test_cookies.py::test_cookie_jar_has_cookie", "tests/test_cookies.py::test_cookie_jar_get_cookie", "tests/test_cookies.py::test_cookie_jar_add_cookie_encode", "tests/test_cookies.py::test_cookie_jar_old_school_cookie_encode", "tests/test_cookies.py::test_cookie_jar_delete_cookie_encode", "tests/test_cookies.py::test_cookie_jar_old_school_delete_encode", "tests/test_cookies.py::test_bad_cookie_prarms", "tests/test_cookies.py::test_cookie_accessors", "tests/test_cookies.py::test_cookie_accessor_hyphens", "tests/test_cookies.py::test_cookie_passthru" ]
[]
MIT License
18,819
803
[ "sanic/cookies/response.py" ]
borgbackup__borg-8257
aada9859ff025d15010ab71352958d4639147fd7
2024-06-29 09:05:32
4eb2a30237cd2656ef5865e6fe6c88dc8a96991b
codecov-commenter: :warning: Please install the !['codecov app svg image'](https://github.com/codecov/engineering-team/assets/152432831/e90313f4-9d3a-4b63-8b54-cfe14e7ec20d) to ensure uploads and comments are reliably processed by Codecov. ## [Codecov](https://app.codecov.io/gh/borgbackup/borg/pull/8257?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=borgbackup) Report Attention: Patch coverage is `88.88889%` with `2 lines` in your changes missing coverage. Please review. > Project coverage is 83.19%. Comparing base [(`00962f9`)](https://app.codecov.io/gh/borgbackup/borg/commit/00962f9d5da83533f0762568f214668be5bae1f6?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=borgbackup) to head [(`0992fad`)](https://app.codecov.io/gh/borgbackup/borg/commit/0992fad802d83718ac359d6a3d08a13c3a351598?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=borgbackup). > Report is 6 commits behind head on master. > :exclamation: **Current head 0992fad differs from pull request most recent head d4d658d** > > Please [upload](https://docs.codecov.com/docs/codecov-uploader) reports for the commit d4d658d to get more accurate results. | [Files](https://app.codecov.io/gh/borgbackup/borg/pull/8257?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=borgbackup) | Patch % | Lines | |---|---|---| | [src/borg/cache.py](https://app.codecov.io/gh/borgbackup/borg/pull/8257?src=pr&el=tree&filepath=src%2Fborg%2Fcache.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=borgbackup#diff-c3JjL2JvcmcvY2FjaGUucHk=) | 88.88% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/borgbackup/borg/pull/8257?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=borgbackup) | :exclamation: Your organization needs to install the [Codecov GitHub app](https://github.com/apps/codecov/installations/select_target) to enable full functionality. <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## master #8257 +/- ## ========================================== - Coverage 83.75% 83.19% -0.56% ========================================== Files 67 67 Lines 12060 12045 -15 Branches 2189 1903 -286 ========================================== - Hits 10101 10021 -80 - Misses 1367 1416 +49 - Partials 592 608 +16 ``` </details> [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/borgbackup/borg/pull/8257?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=borgbackup). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=borgbackup).
diff --git a/src/borg/cache.py b/src/borg/cache.py index b6cd5c0a..c36572c0 100644 --- a/src/borg/cache.py +++ b/src/borg/cache.py @@ -531,7 +531,12 @@ def __init__( self.security_manager.assert_access_unknown(warn_if_unencrypted, manifest, self.key) self.create() - self.open() + try: + self.open() + except (FileNotFoundError, FileIntegrityError): + self.wipe_cache() + self.open() + try: self.security_manager.assert_secure(manifest, self.key, cache_config=self.cache_config) @@ -924,19 +929,31 @@ def check_cache_compatibility(self): return True def wipe_cache(self): - logger.warning("Discarding incompatible cache and forcing a cache rebuild") + logger.warning("Discarding incompatible or corrupted cache and forcing a cache rebuild") archive_path = os.path.join(self.path, "chunks.archive.d") if os.path.isdir(archive_path): shutil.rmtree(os.path.join(self.path, "chunks.archive.d")) os.makedirs(os.path.join(self.path, "chunks.archive.d")) self.chunks = ChunkIndex() - with SaveFile(os.path.join(self.path, files_cache_name()), binary=True): + with IntegrityCheckedFile(path=os.path.join(self.path, "chunks"), write=True) as fd: + self.chunks.write(fd) + self.cache_config.integrity["chunks"] = fd.integrity_data + with IntegrityCheckedFile(path=os.path.join(self.path, files_cache_name()), write=True) as fd: pass # empty file + self.cache_config.integrity[files_cache_name()] = fd.integrity_data self.cache_config.manifest_id = "" self.cache_config._config.set("cache", "manifest", "") + if not self.cache_config._config.has_section("integrity"): + self.cache_config._config.add_section("integrity") + for file, integrity_data in self.cache_config.integrity.items(): + self.cache_config._config.set("integrity", file, integrity_data) + # This is needed to pass the integrity check later on inside CacheConfig.load() + self.cache_config._config.set("integrity", "manifest", "") self.cache_config.ignored_features = set() self.cache_config.mandatory_features = set() + with SaveFile(self.cache_config.config_path) as fd: + self.cache_config._config.write(fd) def update_compatibility(self): operation_to_features_map = self.manifest.get_all_mandatory_features()
no automatic rebuild of a deleted chunks file borg does not tolerate a deleted chunks file (deleted because it was corrupted) due to the integrity checks: ``` u0_a151@localhost ~> ./borgbackup.sh Fri Jun 5 21:11:53 EDT 2020 Starting backup Killed stale lock [email protected]. Removed stale exclusive roster lock for host localhost@75173968615802 pid 3665 thread 0. Removed stale exclusive roster lock for host localhost@75173968615802 pid 9194 thread 0. Removed stale exclusive roster lock for host localhost@75173968615802 pid 3665 thread 0. Removed stale exclusive roster lock for host localhost@75173968615802 pid 9194 thread 0. Creating archive at "[email protected]:/media/borg-monolith::Monolith-2020-06-05T21:11:55" Local Exception Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/archiver.py", line 4529, in main exit_code = archiver.run(args) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/archiver.py", line 4461, in run return set_ec(func(args)) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/archiver.py", line 166, in wrapper return method(self, args, repository=repository, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/archiver.py", line 565, in do_create with Cache(repository, key, manifest, do_files=args.cache_files, progress=args.progress, File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/cache.py", line 380, in __new__ return local() File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/cache.py", line 372, in local return LocalCache(repository=repository, key=key, manifest=manifest, path=path, sync=sync, File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/cache.py", line 457, in __init__ self.open() File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/cache.py", line 505, in open self.rollback() File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/cache.py", line 610, in rollback self._do_open() File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/cache.py", line 493, in _do_open with IntegrityCheckedFile(path=os.path.join(self.path, 'chunks'), write=False, File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/borgbackup-1.1.11-py3.8-linux-x86_64.egg/borg/crypto/file_integrity.py", line 129, in __init__ self.file_fd = override_fd or open(path, mode) FileNotFoundError: [Errno 2] No such file or directory: '/data/data/com.termux/files/home/.cache/borg/6d24295b115c5b4eb74bace9521ab7b09de7f82f096b8b39f8fcd1411fe4b34e/chunks' Platform: Linux localhost 4.9.197-arter97-r12-g29a968fb09d85 #1 SMP PREEMPT Mon Oct 28 19:22:17 KST 2019 aarch64 Linux: Unknown Linux Borg: 1.1.11 Python: CPython 3.8.3 msgpack: 0.5.6 PID: 11175 CWD: /data/data/com.termux/files/home sys.argv: ['/data/data/com.termux/files/usr/bin/borg', 'create', '--verbose', '--filter', 'AME', '--list', '--stats', '--show-rc', '--compression', 'lz4', '--exclude-caches', '--pattern=+/storage/emulated/0/Android/data/org.tasks', '--pattern=+/storage/emulated/0/Android/data/net.sourceforge.opencamera', '--pattern=-/storage/emulated/0/Android', '--pattern=-/storage/emulated/0/DCIM', '--exclude', '*/.sync', '::Monolith-{now}', 'borgbackup.sh', '/storage/emulated/0/'] SSH_ORIGINAL_COMMAND: None terminating with error status, rc 2 ```
borgbackup/borg
diff --git a/src/borg/testsuite/archiver/corruption.py b/src/borg/testsuite/archiver/corruption.py index a604a478..cb8b5541 100644 --- a/src/borg/testsuite/archiver/corruption.py +++ b/src/borg/testsuite/archiver/corruption.py @@ -2,13 +2,15 @@ import json import os from configparser import ConfigParser +from unittest.mock import patch import pytest from ...constants import * # NOQA -from ...crypto.file_integrity import FileIntegrityError from ...helpers import bin_to_hex, Error from . import cmd, create_src_archive, create_test_files, RK_ENCRYPTION +from ...hashindex import ChunkIndex +from ...cache import LocalCache def test_check_corrupted_repository(archiver): @@ -43,15 +45,31 @@ def corrupt(file, amount=1): fd.write(corrupted) [email protected]_cache_wipe def test_cache_chunks(archiver): corrupt_archiver(archiver) - corrupt(os.path.join(archiver.cache_path, "chunks")) - if archiver.FORK_DEFAULT: - out = cmd(archiver, "rinfo", exit_code=2) - assert "failed integrity check" in out - else: - with pytest.raises(FileIntegrityError): - cmd(archiver, "rinfo") + create_src_archive(archiver, "test") + chunks_path = os.path.join(archiver.cache_path, "chunks") + chunks_before_corruption = set(ChunkIndex(path=chunks_path).iteritems()) + corrupt(chunks_path) + + assert not archiver.FORK_DEFAULT # test does not support forking + + chunks_in_memory = None + sync_chunks = LocalCache.sync + + def sync_wrapper(cache): + nonlocal chunks_in_memory + sync_chunks(cache) + chunks_in_memory = set(cache.chunks.iteritems()) + + with patch.object(LocalCache, "sync", sync_wrapper): + out = cmd(archiver, "rinfo") + + assert chunks_in_memory == chunks_before_corruption + assert "forcing a cache rebuild" in out + chunks_after_repair = set(ChunkIndex(path=chunks_path).iteritems()) + assert chunks_after_repair == chunks_before_corruption def test_cache_files(archiver):
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_issue_reference" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-xdist", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y python3-dev libssl-dev libacl1-dev liblz4-dev libzstd-dev libxxhash-dev build-essential pkg-config python3-pkgconfig" ], "python": "3.9", "reqs_path": [ "requirements.d/development.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 -e git+https://github.com/borgbackup/borg.git@aada9859ff025d15010ab71352958d4639147fd7#egg=borgbackup build==1.2.2.post1 cachetools==5.5.2 cffi==1.17.1 cfgv==3.4.0 chardet==5.2.0 colorama==0.4.6 coverage==7.8.0 Cython==3.0.12 distlib==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 identify==2.6.9 importlib_metadata==8.6.1 iniconfig==2.1.0 msgpack==1.1.0 nodeenv==1.9.1 packaging==24.2 pkgconfig==1.5.5 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 py-cpuinfo==9.0.0 pycparser==2.22 pyproject-api==1.9.0 pyproject_hooks==1.2.0 pytest==8.3.5 pytest-benchmark==5.1.0 pytest-cov==6.0.0 pytest-xdist==3.6.1 PyYAML==6.0.2 setuptools-scm==8.2.0 tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 virtualenv==20.29.3 zipp==3.21.0
name: borg channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - borgbackup==2.0.0b9.dev65+gaada9859 - build==1.2.2.post1 - cachetools==5.5.2 - cffi==1.17.1 - cfgv==3.4.0 - chardet==5.2.0 - colorama==0.4.6 - coverage==7.8.0 - cython==3.0.12 - distlib==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - identify==2.6.9 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - msgpack==1.1.0 - nodeenv==1.9.1 - packaging==24.2 - pkgconfig==1.5.5 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - py-cpuinfo==9.0.0 - pycparser==2.22 - pyproject-api==1.9.0 - pyproject-hooks==1.2.0 - pytest==8.3.5 - pytest-benchmark==5.1.0 - pytest-cov==6.0.0 - pytest-xdist==3.6.1 - pyyaml==6.0.2 - setuptools-scm==8.2.0 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - virtualenv==20.29.3 - zipp==3.21.0 prefix: /opt/conda/envs/borg
[ "src/borg/testsuite/archiver/corruption.py::test_cache_chunks" ]
[]
[ "src/borg/testsuite/archiver/corruption.py::test_check_corrupted_repository", "src/borg/testsuite/archiver/corruption.py::test_cache_files", "src/borg/testsuite/archiver/corruption.py::test_chunks_archive", "src/borg/testsuite/archiver/corruption.py::test_old_version_interfered" ]
[]
BSD License
18,831
582
[ "src/borg/cache.py" ]
zarr-developers__zarr-python-2006
f1bd70311f93991dac7aa5dd85de2f6b89aa31d6
2024-07-02 04:52:23
e602aa1d19f26bb06669994231e524c55bcecbeb
diff --git a/src/zarr/abc/store.py b/src/zarr/abc/store.py index 70ac9adc..95d55a2c 100644 --- a/src/zarr/abc/store.py +++ b/src/zarr/abc/store.py @@ -83,6 +83,11 @@ class Store(ABC): if self.mode.readonly: raise ValueError("store mode does not support writing") + @abstractmethod + def __eq__(self, value: object) -> bool: + """Equality comparison.""" + ... + @abstractmethod async def get( self, diff --git a/src/zarr/core/buffer/core.py b/src/zarr/core/buffer/core.py index ff26478c..0c6d966d 100644 --- a/src/zarr/core/buffer/core.py +++ b/src/zarr/core/buffer/core.py @@ -281,6 +281,12 @@ class Buffer(ABC): """Concatenate two buffers""" ... + def __eq__(self, other: object) -> bool: + # Another Buffer class can override this to choose a more efficient path + return isinstance(other, Buffer) and np.array_equal( + self.as_numpy_array(), other.as_numpy_array() + ) + class NDBuffer: """An n-dimensional memory block diff --git a/src/zarr/store/memory.py b/src/zarr/store/memory.py index 89e7ced3..13e289f3 100644 --- a/src/zarr/store/memory.py +++ b/src/zarr/store/memory.py @@ -1,6 +1,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from collections.abc import AsyncGenerator, MutableMapping +from typing import TYPE_CHECKING, Any from zarr.abc.store import Store from zarr.core.buffer import Buffer, gpu @@ -47,6 +48,19 @@ class MemoryStore(Store): def __repr__(self) -> str: return f"MemoryStore({str(self)!r})" + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, type(self)) + and self._store_dict == other._store_dict + and self.mode == other.mode + ) + + def __setstate__(self, state: Any) -> None: + raise NotImplementedError(f"{type(self)} cannot be pickled") + + def __getstate__(self) -> None: + raise NotImplementedError(f"{type(self)} cannot be pickled") + async def get( self, key: str, diff --git a/src/zarr/store/remote.py b/src/zarr/store/remote.py index 3907ac3c..e3e2ba34 100644 --- a/src/zarr/store/remote.py +++ b/src/zarr/store/remote.py @@ -51,6 +51,7 @@ class RemoteStore(Store): this must not be used. """ super().__init__(mode=mode) + self._storage_options = storage_options if isinstance(url, str): self._url = url.rstrip("/") self._fs, _path = fsspec.url_to_fs(url, **storage_options) @@ -91,6 +92,15 @@ class RemoteStore(Store): def __repr__(self) -> str: return f"<RemoteStore({type(self._fs).__name__}, {self.path})>" + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, type(self)) + and self.path == other.path + and self.mode == other.mode + and self._url == other._url + # and self._storage_options == other._storage_options # FIXME: this isn't working for some reason + ) + async def get( self, key: str, diff --git a/src/zarr/store/zip.py b/src/zarr/store/zip.py index 15473aa6..ea31ad93 100644 --- a/src/zarr/store/zip.py +++ b/src/zarr/store/zip.py @@ -5,7 +5,7 @@ import threading import time import zipfile from pathlib import Path -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING, Any, Literal from zarr.abc.store import Store from zarr.core.buffer import Buffer, BufferPrototype @@ -68,7 +68,7 @@ class ZipStore(Store): self.compression = compression self.allowZip64 = allowZip64 - async def _open(self) -> None: + def _sync_open(self) -> None: if self._is_open: raise ValueError("store is already open") @@ -83,6 +83,17 @@ class ZipStore(Store): self._is_open = True + async def _open(self) -> None: + self._sync_open() + + def __getstate__(self) -> tuple[Path, ZipStoreAccessModeLiteral, int, bool]: + return self.path, self._zmode, self.compression, self.allowZip64 + + def __setstate__(self, state: Any) -> None: + self.path, self._zmode, self.compression, self.allowZip64 = state + self._is_open = False + self._sync_open() + def close(self) -> None: super().close() with self._lock:
[v3] Test serialization of arrays and groups Arrays and Groups should be able to be round tripped with Python's pickle protocol. We need a test to make sure this works to be sure downstream applications can work with our new APIs.
zarr-developers/zarr-python
diff --git a/src/zarr/testing/store.py b/src/zarr/testing/store.py index 65d7751a..a08b6960 100644 --- a/src/zarr/testing/store.py +++ b/src/zarr/testing/store.py @@ -1,3 +1,4 @@ +import pickle from typing import Any, Generic, TypeVar import pytest @@ -48,6 +49,19 @@ class StoreTests(Generic[S, B]): assert isinstance(store, Store) assert isinstance(store, self.store_cls) + def test_store_eq(self, store: S, store_kwargs: dict[str, Any]) -> None: + # check self equality + assert store == store + + # check store equality with same inputs + # asserting this is important for being able to compare (de)serialized stores + store2 = self.store_cls(**store_kwargs) + assert store == store2 + + def test_serizalizable_store(self, store: S) -> None: + foo = pickle.dumps(store) + assert pickle.loads(foo) == store + def test_store_mode(self, store: S, store_kwargs: dict[str, Any]) -> None: assert store.mode == AccessMode.from_literal("r+") assert not store.mode.readonly diff --git a/tests/v3/test_array.py b/tests/v3/test_array.py index cd20ab6e..11be5168 100644 --- a/tests/v3/test_array.py +++ b/tests/v3/test_array.py @@ -1,9 +1,10 @@ +import pickle from typing import Literal import numpy as np import pytest -from zarr import Array, Group +from zarr import Array, AsyncArray, Group from zarr.core.common import ZarrFormat from zarr.errors import ContainsArrayError, ContainsGroupError from zarr.store import LocalStore, MemoryStore @@ -135,3 +136,36 @@ def test_array_v3_fill_value(store: MemoryStore, fill_value: int, dtype_str: str assert arr.fill_value == np.dtype(dtype_str).type(fill_value) assert arr.fill_value.dtype == arr.dtype + + [email protected]("store", ("local",), indirect=["store"]) [email protected]("zarr_format", (2, 3)) +async def test_serializable_async_array( + store: LocalStore | MemoryStore, zarr_format: ZarrFormat +) -> None: + expected = await AsyncArray.create( + store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype="i4" + ) + # await expected.setitems(list(range(100))) + + p = pickle.dumps(expected) + actual = pickle.loads(p) + + assert actual == expected + # np.testing.assert_array_equal(await actual.getitem(slice(None)), await expected.getitem(slice(None))) + # TODO: uncomment the parts of this test that will be impacted by the config/prototype changes in flight + + [email protected]("store", ("local",), indirect=["store"]) [email protected]("zarr_format", (2, 3)) +def test_serializable_sync_array(store: LocalStore, zarr_format: ZarrFormat) -> None: + expected = Array.create( + store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype="i4" + ) + expected[:] = list(range(100)) + + p = pickle.dumps(expected) + actual = pickle.loads(p) + + assert actual == expected + np.testing.assert_array_equal(actual[:], expected[:]) diff --git a/tests/v3/test_group.py b/tests/v3/test_group.py index a62f3673..94b839a1 100644 --- a/tests/v3/test_group.py +++ b/tests/v3/test_group.py @@ -1,20 +1,19 @@ from __future__ import annotations +import pickle from typing import TYPE_CHECKING, Any, Literal, cast import numpy as np import pytest -import zarr.api.asynchronous from zarr import Array, AsyncArray, AsyncGroup, Group from zarr.abc.store import Store -from zarr.api.synchronous import open_group from zarr.core.buffer import default_buffer_prototype from zarr.core.common import JSON, ZarrFormat from zarr.core.group import GroupMetadata from zarr.core.sync import sync from zarr.errors import ContainsArrayError, ContainsGroupError -from zarr.store import LocalStore, MemoryStore, StorePath +from zarr.store import LocalStore, StorePath from zarr.store.common import make_store_path from .conftest import parse_store @@ -681,152 +680,22 @@ async def test_asyncgroup_update_attributes(store: Store, zarr_format: ZarrForma assert agroup_new_attributes.attrs == attributes_new -async def test_group_members_async(store: LocalStore | MemoryStore) -> None: - group = AsyncGroup( - GroupMetadata(), - store_path=StorePath(store=store, path="root"), - ) - a0 = await group.create_array("a0", shape=(1,)) - g0 = await group.create_group("g0") - a1 = await g0.create_array("a1", shape=(1,)) - g1 = await g0.create_group("g1") - a2 = await g1.create_array("a2", shape=(1,)) - g2 = await g1.create_group("g2") - - # immediate children - children = sorted([x async for x in group.members()], key=lambda x: x[0]) - assert children == [ - ("a0", a0), - ("g0", g0), - ] - - nmembers = await group.nmembers() - assert nmembers == 2 - - # partial - children = sorted([x async for x in group.members(max_depth=1)], key=lambda x: x[0]) - expected = [ - ("a0", a0), - ("g0", g0), - ("g0/a1", a1), - ("g0/g1", g1), - ] - assert children == expected - nmembers = await group.nmembers(max_depth=1) - assert nmembers == 4 - - # all children - all_children = sorted([x async for x in group.members(max_depth=None)], key=lambda x: x[0]) - expected = [ - ("a0", a0), - ("g0", g0), - ("g0/a1", a1), - ("g0/g1", g1), - ("g0/g1/a2", a2), - ("g0/g1/g2", g2), - ] - assert all_children == expected - - nmembers = await group.nmembers(max_depth=None) - assert nmembers == 6 - - with pytest.raises(ValueError, match="max_depth"): - [x async for x in group.members(max_depth=-1)] - - -async def test_require_group(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - root = await AsyncGroup.create(store=store, zarr_format=zarr_format) - - # create foo group - _ = await root.create_group("foo", attributes={"foo": 100}) - - # test that we can get the group using require_group - foo_group = await root.require_group("foo") - assert foo_group.attrs == {"foo": 100} - - # test that we can get the group using require_group and overwrite=True - foo_group = await root.require_group("foo", overwrite=True) - - _ = await foo_group.create_array( - "bar", shape=(10,), dtype="uint8", chunk_shape=(2,), attributes={"foo": 100} [email protected]("store", ("local",), indirect=["store"]) [email protected]("zarr_format", (2, 3)) +async def test_serializable_async_group(store: LocalStore, zarr_format: ZarrFormat) -> None: + expected = await AsyncGroup.create( + store=store, attributes={"foo": 999}, zarr_format=zarr_format ) + p = pickle.dumps(expected) + actual = pickle.loads(p) + assert actual == expected - # test that overwriting a group w/ children fails - # TODO: figure out why ensure_no_existing_node is not catching the foo.bar array - # - # with pytest.raises(ContainsArrayError): - # await root.require_group("foo", overwrite=True) - - # test that requiring a group where an array is fails - with pytest.raises(TypeError): - await foo_group.require_group("bar") - - -async def test_require_groups(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - root = await AsyncGroup.create(store=store, zarr_format=zarr_format) - # create foo group - _ = await root.create_group("foo", attributes={"foo": 100}) - # create bar group - _ = await root.create_group("bar", attributes={"bar": 200}) - - foo_group, bar_group = await root.require_groups("foo", "bar") - assert foo_group.attrs == {"foo": 100} - assert bar_group.attrs == {"bar": 200} - - # get a mix of existing and new groups - foo_group, spam_group = await root.require_groups("foo", "spam") - assert foo_group.attrs == {"foo": 100} - assert spam_group.attrs == {} - - # no names - no_group = await root.require_groups() - assert no_group == () - - -async def test_create_dataset(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - root = await AsyncGroup.create(store=store, zarr_format=zarr_format) - with pytest.warns(DeprecationWarning): - foo = await root.create_dataset("foo", shape=(10,), dtype="uint8") - assert foo.shape == (10,) - - with pytest.raises(ContainsArrayError), pytest.warns(DeprecationWarning): - await root.create_dataset("foo", shape=(100,), dtype="int8") - - _ = await root.create_group("bar") - with pytest.raises(ContainsGroupError), pytest.warns(DeprecationWarning): - await root.create_dataset("bar", shape=(100,), dtype="int8") - - -async def test_require_array(store: LocalStore | MemoryStore, zarr_format: ZarrFormat) -> None: - root = await AsyncGroup.create(store=store, zarr_format=zarr_format) - foo1 = await root.require_array("foo", shape=(10,), dtype="i8", attributes={"foo": 101}) - assert foo1.attrs == {"foo": 101} - foo2 = await root.require_array("foo", shape=(10,), dtype="i8") - assert foo2.attrs == {"foo": 101} - - # exact = False - _ = await root.require_array("foo", shape=10, dtype="f8") - - # errors w/ exact True - with pytest.raises(TypeError, match="Incompatible dtype"): - await root.require_array("foo", shape=(10,), dtype="f8", exact=True) - - with pytest.raises(TypeError, match="Incompatible shape"): - await root.require_array("foo", shape=(100, 100), dtype="i8") - - with pytest.raises(TypeError, match="Incompatible dtype"): - await root.require_array("foo", shape=(10,), dtype="f4") - - _ = await root.create_group("bar") - with pytest.raises(TypeError, match="Incompatible object"): - await root.require_array("bar", shape=(10,), dtype="int8") - - -async def test_open_mutable_mapping(): - group = await zarr.api.asynchronous.open_group(store={}, mode="w") - assert isinstance(group.store_path.store, MemoryStore) [email protected]("store", ("local",), indirect=["store"]) [email protected]("zarr_format", (2, 3)) +def test_serializable_sync_group(store: LocalStore, zarr_format: ZarrFormat) -> None: + expected = Group.create(store=store, attributes={"foo": 999}, zarr_format=zarr_format) + p = pickle.dumps(expected) + actual = pickle.loads(p) -def test_open_mutable_mapping_sync(): - group = open_group(store={}, mode="w") - assert isinstance(group.store_path.store, MemoryStore) + assert actual == expected diff --git a/tests/v3/test_store/test_memory.py b/tests/v3/test_store/test_memory.py index 13aaa20b..04d17eb2 100644 --- a/tests/v3/test_store/test_memory.py +++ b/tests/v3/test_store/test_memory.py @@ -1,11 +1,12 @@ from __future__ import annotations +import pickle + import pytest -from zarr.core.buffer import Buffer, cpu, gpu -from zarr.store.memory import GpuMemoryStore, MemoryStore +from zarr.core.buffer import Buffer, cpu +from zarr.store.memory import MemoryStore from zarr.testing.store import StoreTests -from zarr.testing.utils import gpu_test class TestMemoryStore(StoreTests[MemoryStore, cpu.Buffer]): @@ -46,43 +47,12 @@ class TestMemoryStore(StoreTests[MemoryStore, cpu.Buffer]): def test_list_prefix(self, store: MemoryStore) -> None: assert True + def test_serizalizable_store(self, store: MemoryStore) -> None: + with pytest.raises(NotImplementedError): + store.__getstate__() -@gpu_test -class TestGpuMemoryStore(StoreTests[GpuMemoryStore, gpu.Buffer]): - store_cls = GpuMemoryStore - buffer_cls = gpu.Buffer - - def set(self, store: GpuMemoryStore, key: str, value: Buffer) -> None: - store._store_dict[key] = value - - def get(self, store: MemoryStore, key: str) -> Buffer: - return store._store_dict[key] - - @pytest.fixture(scope="function", params=[None, {}]) - def store_kwargs(self, request) -> dict[str, str | None | dict[str, Buffer]]: - return {"store_dict": request.param, "mode": "r+"} - - @pytest.fixture(scope="function") - def store(self, store_kwargs: str | None | dict[str, gpu.Buffer]) -> GpuMemoryStore: - return self.store_cls(**store_kwargs) - - def test_store_repr(self, store: GpuMemoryStore) -> None: - assert str(store) == f"gpumemory://{id(store._store_dict)}" - - def test_store_supports_writes(self, store: GpuMemoryStore) -> None: - assert store.supports_writes - - def test_store_supports_listing(self, store: GpuMemoryStore) -> None: - assert store.supports_listing - - def test_store_supports_partial_writes(self, store: GpuMemoryStore) -> None: - assert store.supports_partial_writes - - def test_list_prefix(self, store: GpuMemoryStore) -> None: - assert True - + with pytest.raises(NotImplementedError): + store.__setstate__({}) -def test_uses_dict() -> None: - store_dict = {} - store = MemoryStore(store_dict) - assert store._store_dict is store_dict + with pytest.raises(NotImplementedError): + pickle.dumps(store) diff --git a/tests/v3/test_store/test_remote.py b/tests/v3/test_store/test_remote.py index e400857c..afa99120 100644 --- a/tests/v3/test_store/test_remote.py +++ b/tests/v3/test_store/test_remote.py @@ -109,7 +109,7 @@ class TestRemoteStoreS3(StoreTests[RemoteStore, cpu.Buffer]): anon = False mode = "r+" if request.param == "use_upath": - return {"mode": mode, "url": UPath(url, endpoint_url=endpoint_url, anon=anon)} + return {"url": UPath(url, endpoint_url=endpoint_url, anon=anon), "mode": mode} elif request.param == "use_str": return {"url": url, "mode": mode, "anon": anon, "endpoint_url": endpoint_url}
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 5 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "msgpack", "lmdb", "s3fs", "pytest-asyncio", "moto[s3]", "flask-cors", "flask", "requests", "mypy", "hypothesis", "universal-pathlib" ], "pre_install": null, "python": "3.11", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore==2.21.1 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aioitertools==0.12.0 aiosignal==1.3.2 asciitree==0.3.3 attrs==25.3.0 blinker==1.9.0 boto3==1.37.1 botocore==1.37.1 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 click==8.1.8 coverage==7.8.0 crc32c==2.7.1 cryptography==44.0.2 Deprecated==1.2.18 donfig==0.8.1.post1 fasteners==0.19 Flask==3.1.0 flask-cors==5.0.1 frozenlist==1.5.0 fsspec==2025.3.1 hypothesis==6.130.5 idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work itsdangerous==2.2.0 Jinja2==3.1.6 jmespath==1.0.1 lmdb==1.6.2 MarkupSafe==3.0.2 moto==5.1.2 msgpack==1.1.0 multidict==6.2.0 mypy==1.15.0 mypy-extensions==1.0.0 numcodecs==0.15.1 numpy==2.2.4 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work propcache==0.3.1 py-partiql-parser==0.6.1 pycparser==2.22 pytest @ file:///croot/pytest_1738938843180/work pytest-asyncio==0.26.0 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 responses==0.25.7 s3fs==2025.3.1 s3transfer==0.11.3 six==1.17.0 sortedcontainers==2.4.0 typing_extensions==4.13.0 universal_pathlib==0.2.6 urllib3==2.3.0 Werkzeug==3.1.3 wrapt==1.17.2 xmltodict==0.14.2 yarl==1.18.3 -e git+https://github.com/zarr-developers/zarr-python.git@f1bd70311f93991dac7aa5dd85de2f6b89aa31d6#egg=zarr
name: zarr-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libuuid=1.41.5=h5eee18b_0 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py311h06a4308_0 - pip=25.0=py311h06a4308_0 - pluggy=1.5.0=py311h06a4308_0 - pytest=8.3.4=py311h06a4308_0 - python=3.11.11=he870216_0 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py311h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py311h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aiobotocore==2.21.1 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aioitertools==0.12.0 - aiosignal==1.3.2 - asciitree==0.3.3 - attrs==25.3.0 - blinker==1.9.0 - boto3==1.37.1 - botocore==1.37.1 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - click==8.1.8 - coverage==7.8.0 - crc32c==2.7.1 - cryptography==44.0.2 - deprecated==1.2.18 - donfig==0.8.1.post1 - fasteners==0.19 - flask==3.1.0 - flask-cors==5.0.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - hypothesis==6.130.5 - idna==3.10 - itsdangerous==2.2.0 - jinja2==3.1.6 - jmespath==1.0.1 - lmdb==1.6.2 - markupsafe==3.0.2 - moto==5.1.2 - msgpack==1.1.0 - multidict==6.2.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - numcodecs==0.15.1 - numpy==2.2.4 - propcache==0.3.1 - py-partiql-parser==0.6.1 - pycparser==2.22 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - responses==0.25.7 - s3fs==2025.3.1 - s3transfer==0.11.3 - six==1.17.0 - sortedcontainers==2.4.0 - typing-extensions==4.13.0 - universal-pathlib==0.2.6 - urllib3==2.3.0 - werkzeug==3.1.3 - wrapt==1.17.2 - xmltodict==0.14.2 - yarl==1.18.3 - zarr==3.0.0a4 prefix: /opt/conda/envs/zarr-python
[ "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_eq[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_eq[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_serizalizable_store[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_serizalizable_store[True]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_eq[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_eq[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_serizalizable_store[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_serizalizable_store[use_str]" ]
[]
[ "tests/v3/test_array.py::test_array_creation_existing_node[array-True-2-local]", "tests/v3/test_array.py::test_array_creation_existing_node[array-True-2-memory]", "tests/v3/test_array.py::test_array_creation_existing_node[array-True-2-zip]", "tests/v3/test_array.py::test_array_creation_existing_node[array-True-3-local]", "tests/v3/test_array.py::test_array_creation_existing_node[array-True-3-memory]", "tests/v3/test_array.py::test_array_creation_existing_node[array-True-3-zip]", "tests/v3/test_array.py::test_array_creation_existing_node[array-False-2-local]", "tests/v3/test_array.py::test_array_creation_existing_node[array-False-2-memory]", "tests/v3/test_array.py::test_array_creation_existing_node[array-False-2-zip]", "tests/v3/test_array.py::test_array_creation_existing_node[array-False-3-local]", "tests/v3/test_array.py::test_array_creation_existing_node[array-False-3-memory]", "tests/v3/test_array.py::test_array_creation_existing_node[array-False-3-zip]", "tests/v3/test_array.py::test_array_creation_existing_node[group-True-2-local]", "tests/v3/test_array.py::test_array_creation_existing_node[group-True-2-memory]", "tests/v3/test_array.py::test_array_creation_existing_node[group-True-2-zip]", "tests/v3/test_array.py::test_array_creation_existing_node[group-True-3-local]", "tests/v3/test_array.py::test_array_creation_existing_node[group-True-3-memory]", "tests/v3/test_array.py::test_array_creation_existing_node[group-True-3-zip]", "tests/v3/test_array.py::test_array_creation_existing_node[group-False-2-local]", "tests/v3/test_array.py::test_array_creation_existing_node[group-False-2-memory]", "tests/v3/test_array.py::test_array_creation_existing_node[group-False-2-zip]", "tests/v3/test_array.py::test_array_creation_existing_node[group-False-3-local]", "tests/v3/test_array.py::test_array_creation_existing_node[group-False-3-memory]", "tests/v3/test_array.py::test_array_creation_existing_node[group-False-3-zip]", "tests/v3/test_array.py::test_array_name_properties_no_group[2-local]", "tests/v3/test_array.py::test_array_name_properties_no_group[2-memory]", "tests/v3/test_array.py::test_array_name_properties_no_group[2-zip]", "tests/v3/test_array.py::test_array_name_properties_no_group[3-local]", "tests/v3/test_array.py::test_array_name_properties_no_group[3-memory]", "tests/v3/test_array.py::test_array_name_properties_no_group[3-zip]", "tests/v3/test_array.py::test_array_name_properties_with_group[2-local]", "tests/v3/test_array.py::test_array_name_properties_with_group[2-memory]", "tests/v3/test_array.py::test_array_name_properties_with_group[2-zip]", "tests/v3/test_array.py::test_array_name_properties_with_group[3-local]", "tests/v3/test_array.py::test_array_name_properties_with_group[3-memory]", "tests/v3/test_array.py::test_array_name_properties_with_group[3-zip]", "tests/v3/test_array.py::test_array_v3_fill_value_default[bool-True-memory]", "tests/v3/test_array.py::test_array_v3_fill_value_default[bool-False-memory]", "tests/v3/test_array.py::test_array_v3_fill_value_default[uint8-True-memory]", "tests/v3/test_array.py::test_array_v3_fill_value_default[uint8-False-memory]", "tests/v3/test_array.py::test_array_v3_fill_value_default[complex64-True-memory]", "tests/v3/test_array.py::test_array_v3_fill_value_default[complex64-False-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[bool-False-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[bool-0.0-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[bool-1-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[bool-2.3-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[uint8-False-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[uint8-0.0-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[uint8-1-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[uint8-2.3-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[float32-False-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[float32-0.0-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[float32-1-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[float32-2.3-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[complex64-False-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[complex64-0.0-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[complex64-1-memory]", "tests/v3/test_array.py::test_array_v3_fill_value[complex64-2.3-memory]", "tests/v3/test_array.py::test_serializable_async_array[2-local]", "tests/v3/test_array.py::test_serializable_async_array[3-local]", "tests/v3/test_array.py::test_serializable_sync_array[2-local]", "tests/v3/test_array.py::test_serializable_sync_array[3-local]", "tests/v3/test_group.py::test_group_init[local-zarr2]", "tests/v3/test_group.py::test_group_init[local-zarr3]", "tests/v3/test_group.py::test_group_init[memory-zarr2]", "tests/v3/test_group.py::test_group_init[memory-zarr3]", "tests/v3/test_group.py::test_group_init[zip-zarr2]", "tests/v3/test_group.py::test_group_init[zip-zarr3]", "tests/v3/test_group.py::test_group_name_properties[local-zarr2]", "tests/v3/test_group.py::test_group_name_properties[local-zarr3]", "tests/v3/test_group.py::test_group_name_properties[memory-zarr2]", "tests/v3/test_group.py::test_group_name_properties[memory-zarr3]", "tests/v3/test_group.py::test_group_name_properties[zip-zarr2]", "tests/v3/test_group.py::test_group_name_properties[zip-zarr3]", "tests/v3/test_group.py::test_group_members[local-zarr2]", "tests/v3/test_group.py::test_group_members[local-zarr3]", "tests/v3/test_group.py::test_group_members[memory-zarr2]", "tests/v3/test_group.py::test_group_members[memory-zarr3]", "tests/v3/test_group.py::test_group_members[zip-zarr2]", "tests/v3/test_group.py::test_group_members[zip-zarr3]", "tests/v3/test_group.py::test_group[local-zarr2]", "tests/v3/test_group.py::test_group[local-zarr3]", "tests/v3/test_group.py::test_group[memory-zarr2]", "tests/v3/test_group.py::test_group[memory-zarr3]", "tests/v3/test_group.py::test_group[zip-zarr2]", "tests/v3/test_group.py::test_group[zip-zarr3]", "tests/v3/test_group.py::test_group_create[local-True-zarr2]", "tests/v3/test_group.py::test_group_create[local-True-zarr3]", "tests/v3/test_group.py::test_group_create[local-False-zarr2]", "tests/v3/test_group.py::test_group_create[local-False-zarr3]", "tests/v3/test_group.py::test_group_create[memory-True-zarr2]", "tests/v3/test_group.py::test_group_create[memory-True-zarr3]", "tests/v3/test_group.py::test_group_create[memory-False-zarr2]", "tests/v3/test_group.py::test_group_create[memory-False-zarr3]", "tests/v3/test_group.py::test_group_create[zip-True-zarr2]", "tests/v3/test_group.py::test_group_create[zip-True-zarr3]", "tests/v3/test_group.py::test_group_create[zip-False-zarr2]", "tests/v3/test_group.py::test_group_create[zip-False-zarr3]", "tests/v3/test_group.py::test_group_open[local-zarr2-True]", "tests/v3/test_group.py::test_group_open[local-zarr2-False]", "tests/v3/test_group.py::test_group_open[local-zarr3-True]", "tests/v3/test_group.py::test_group_open[local-zarr3-False]", "tests/v3/test_group.py::test_group_open[memory-zarr2-True]", "tests/v3/test_group.py::test_group_open[memory-zarr2-False]", "tests/v3/test_group.py::test_group_open[memory-zarr3-True]", "tests/v3/test_group.py::test_group_open[memory-zarr3-False]", "tests/v3/test_group.py::test_group_open[zip-zarr2-True]", "tests/v3/test_group.py::test_group_open[zip-zarr2-False]", "tests/v3/test_group.py::test_group_open[zip-zarr3-True]", "tests/v3/test_group.py::test_group_open[zip-zarr3-False]", "tests/v3/test_group.py::test_group_getitem[local-zarr2]", "tests/v3/test_group.py::test_group_getitem[local-zarr3]", "tests/v3/test_group.py::test_group_getitem[memory-zarr2]", "tests/v3/test_group.py::test_group_getitem[memory-zarr3]", "tests/v3/test_group.py::test_group_getitem[zip-zarr2]", "tests/v3/test_group.py::test_group_getitem[zip-zarr3]", "tests/v3/test_group.py::test_group_delitem[local-zarr2]", "tests/v3/test_group.py::test_group_delitem[local-zarr3]", "tests/v3/test_group.py::test_group_delitem[memory-zarr2]", "tests/v3/test_group.py::test_group_delitem[memory-zarr3]", "tests/v3/test_group.py::test_group_iter[local-zarr2]", "tests/v3/test_group.py::test_group_iter[local-zarr3]", "tests/v3/test_group.py::test_group_iter[memory-zarr2]", "tests/v3/test_group.py::test_group_iter[memory-zarr3]", "tests/v3/test_group.py::test_group_iter[zip-zarr2]", "tests/v3/test_group.py::test_group_iter[zip-zarr3]", "tests/v3/test_group.py::test_group_len[local-zarr2]", "tests/v3/test_group.py::test_group_len[local-zarr3]", "tests/v3/test_group.py::test_group_len[memory-zarr2]", "tests/v3/test_group.py::test_group_len[memory-zarr3]", "tests/v3/test_group.py::test_group_len[zip-zarr2]", "tests/v3/test_group.py::test_group_len[zip-zarr3]", "tests/v3/test_group.py::test_group_setitem[local-zarr2]", "tests/v3/test_group.py::test_group_setitem[local-zarr3]", "tests/v3/test_group.py::test_group_setitem[memory-zarr2]", "tests/v3/test_group.py::test_group_setitem[memory-zarr3]", "tests/v3/test_group.py::test_group_setitem[zip-zarr2]", "tests/v3/test_group.py::test_group_setitem[zip-zarr3]", "tests/v3/test_group.py::test_group_contains[local-zarr2]", "tests/v3/test_group.py::test_group_contains[local-zarr3]", "tests/v3/test_group.py::test_group_contains[memory-zarr2]", "tests/v3/test_group.py::test_group_contains[memory-zarr3]", "tests/v3/test_group.py::test_group_contains[zip-zarr2]", "tests/v3/test_group.py::test_group_contains[zip-zarr3]", "tests/v3/test_group.py::test_group_subgroups[local-zarr2]", "tests/v3/test_group.py::test_group_subgroups[local-zarr3]", "tests/v3/test_group.py::test_group_subgroups[memory-zarr2]", "tests/v3/test_group.py::test_group_subgroups[memory-zarr3]", "tests/v3/test_group.py::test_group_subgroups[zip-zarr2]", "tests/v3/test_group.py::test_group_subgroups[zip-zarr3]", "tests/v3/test_group.py::test_group_subarrays[local-zarr2]", "tests/v3/test_group.py::test_group_subarrays[local-zarr3]", "tests/v3/test_group.py::test_group_subarrays[memory-zarr2]", "tests/v3/test_group.py::test_group_subarrays[memory-zarr3]", "tests/v3/test_group.py::test_group_subarrays[zip-zarr2]", "tests/v3/test_group.py::test_group_subarrays[zip-zarr3]", "tests/v3/test_group.py::test_group_update_attributes[local-zarr2]", "tests/v3/test_group.py::test_group_update_attributes[local-zarr3]", "tests/v3/test_group.py::test_group_update_attributes[memory-zarr2]", "tests/v3/test_group.py::test_group_update_attributes[memory-zarr3]", "tests/v3/test_group.py::test_group_update_attributes[zip-zarr2]", "tests/v3/test_group.py::test_group_update_attributes[zip-zarr3]", "tests/v3/test_group.py::test_group_update_attributes_async[local-zarr2]", "tests/v3/test_group.py::test_group_update_attributes_async[local-zarr3]", "tests/v3/test_group.py::test_group_update_attributes_async[memory-zarr2]", "tests/v3/test_group.py::test_group_update_attributes_async[memory-zarr3]", "tests/v3/test_group.py::test_group_update_attributes_async[zip-zarr2]", "tests/v3/test_group.py::test_group_update_attributes_async[zip-zarr3]", "tests/v3/test_group.py::test_group_create_array[local-zarr2-True-create_array]", "tests/v3/test_group.py::test_group_create_array[local-zarr2-True-array]", "tests/v3/test_group.py::test_group_create_array[local-zarr2-False-create_array]", "tests/v3/test_group.py::test_group_create_array[local-zarr2-False-array]", "tests/v3/test_group.py::test_group_create_array[local-zarr3-True-create_array]", "tests/v3/test_group.py::test_group_create_array[local-zarr3-True-array]", "tests/v3/test_group.py::test_group_create_array[local-zarr3-False-create_array]", "tests/v3/test_group.py::test_group_create_array[local-zarr3-False-array]", "tests/v3/test_group.py::test_group_create_array[memory-zarr2-True-create_array]", "tests/v3/test_group.py::test_group_create_array[memory-zarr2-True-array]", "tests/v3/test_group.py::test_group_create_array[memory-zarr2-False-create_array]", "tests/v3/test_group.py::test_group_create_array[memory-zarr2-False-array]", "tests/v3/test_group.py::test_group_create_array[memory-zarr3-True-create_array]", "tests/v3/test_group.py::test_group_create_array[memory-zarr3-True-array]", "tests/v3/test_group.py::test_group_create_array[memory-zarr3-False-create_array]", "tests/v3/test_group.py::test_group_create_array[memory-zarr3-False-array]", "tests/v3/test_group.py::test_group_create_array[zip-zarr2-True-create_array]", "tests/v3/test_group.py::test_group_create_array[zip-zarr2-True-array]", "tests/v3/test_group.py::test_group_create_array[zip-zarr2-False-create_array]", "tests/v3/test_group.py::test_group_create_array[zip-zarr2-False-array]", "tests/v3/test_group.py::test_group_create_array[zip-zarr3-True-create_array]", "tests/v3/test_group.py::test_group_create_array[zip-zarr3-True-array]", "tests/v3/test_group.py::test_group_create_array[zip-zarr3-False-create_array]", "tests/v3/test_group.py::test_group_create_array[zip-zarr3-False-array]", "tests/v3/test_group.py::test_group_creation_existing_node[array-True-2-local]", "tests/v3/test_group.py::test_group_creation_existing_node[array-True-2-memory]", "tests/v3/test_group.py::test_group_creation_existing_node[array-True-2-zip]", "tests/v3/test_group.py::test_group_creation_existing_node[array-True-3-local]", "tests/v3/test_group.py::test_group_creation_existing_node[array-True-3-memory]", "tests/v3/test_group.py::test_group_creation_existing_node[array-True-3-zip]", "tests/v3/test_group.py::test_group_creation_existing_node[array-False-2-local]", "tests/v3/test_group.py::test_group_creation_existing_node[array-False-2-memory]", "tests/v3/test_group.py::test_group_creation_existing_node[array-False-2-zip]", "tests/v3/test_group.py::test_group_creation_existing_node[array-False-3-local]", "tests/v3/test_group.py::test_group_creation_existing_node[array-False-3-memory]", "tests/v3/test_group.py::test_group_creation_existing_node[array-False-3-zip]", "tests/v3/test_group.py::test_group_creation_existing_node[group-True-2-local]", "tests/v3/test_group.py::test_group_creation_existing_node[group-True-2-memory]", "tests/v3/test_group.py::test_group_creation_existing_node[group-True-2-zip]", "tests/v3/test_group.py::test_group_creation_existing_node[group-True-3-local]", "tests/v3/test_group.py::test_group_creation_existing_node[group-True-3-memory]", "tests/v3/test_group.py::test_group_creation_existing_node[group-True-3-zip]", "tests/v3/test_group.py::test_group_creation_existing_node[group-False-2-local]", "tests/v3/test_group.py::test_group_creation_existing_node[group-False-2-memory]", "tests/v3/test_group.py::test_group_creation_existing_node[group-False-2-zip]", "tests/v3/test_group.py::test_group_creation_existing_node[group-False-3-local]", "tests/v3/test_group.py::test_group_creation_existing_node[group-False-3-memory]", "tests/v3/test_group.py::test_group_creation_existing_node[group-False-3-zip]", "tests/v3/test_group.py::test_asyncgroup_create[local-True-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create[local-True-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create[local-False-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create[local-False-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create[memory-True-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create[memory-True-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create[memory-False-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create[memory-False-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create[zip-True-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create[zip-True-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create[zip-False-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create[zip-False-zarr3]", "tests/v3/test_group.py::test_asyncgroup_attrs[local-zarr2]", "tests/v3/test_group.py::test_asyncgroup_attrs[local-zarr3]", "tests/v3/test_group.py::test_asyncgroup_attrs[memory-zarr2]", "tests/v3/test_group.py::test_asyncgroup_attrs[memory-zarr3]", "tests/v3/test_group.py::test_asyncgroup_attrs[zip-zarr2]", "tests/v3/test_group.py::test_asyncgroup_attrs[zip-zarr3]", "tests/v3/test_group.py::test_asyncgroup_open[local-zarr2]", "tests/v3/test_group.py::test_asyncgroup_open[local-zarr3]", "tests/v3/test_group.py::test_asyncgroup_open[memory-zarr2]", "tests/v3/test_group.py::test_asyncgroup_open[memory-zarr3]", "tests/v3/test_group.py::test_asyncgroup_open[zip-zarr2]", "tests/v3/test_group.py::test_asyncgroup_open[zip-zarr3]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[local-zarr2]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[local-zarr3]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[memory-zarr2]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[memory-zarr3]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[zip-zarr2]", "tests/v3/test_group.py::test_asyncgroup_open_wrong_format[zip-zarr3]", "tests/v3/test_group.py::test_asyncgroup_from_dict[local-data0]", "tests/v3/test_group.py::test_asyncgroup_from_dict[local-data1]", "tests/v3/test_group.py::test_asyncgroup_from_dict[memory-data0]", "tests/v3/test_group.py::test_asyncgroup_from_dict[memory-data1]", "tests/v3/test_group.py::test_asyncgroup_from_dict[zip-data0]", "tests/v3/test_group.py::test_asyncgroup_from_dict[zip-data1]", "tests/v3/test_group.py::test_asyncgroup_getitem[local-zarr2]", "tests/v3/test_group.py::test_asyncgroup_getitem[local-zarr3]", "tests/v3/test_group.py::test_asyncgroup_getitem[memory-zarr2]", "tests/v3/test_group.py::test_asyncgroup_getitem[memory-zarr3]", "tests/v3/test_group.py::test_asyncgroup_getitem[zip-zarr2]", "tests/v3/test_group.py::test_asyncgroup_getitem[zip-zarr3]", "tests/v3/test_group.py::test_asyncgroup_delitem[local-zarr2]", "tests/v3/test_group.py::test_asyncgroup_delitem[local-zarr3]", "tests/v3/test_group.py::test_asyncgroup_delitem[memory-zarr2]", "tests/v3/test_group.py::test_asyncgroup_delitem[memory-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create_group[local-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create_group[local-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create_group[memory-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create_group[memory-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create_group[zip-zarr2]", "tests/v3/test_group.py::test_asyncgroup_create_group[zip-zarr3]", "tests/v3/test_group.py::test_asyncgroup_create_array[local-zarr2-True]", "tests/v3/test_group.py::test_asyncgroup_create_array[local-zarr2-False]", "tests/v3/test_group.py::test_asyncgroup_create_array[local-zarr3-True]", "tests/v3/test_group.py::test_asyncgroup_create_array[local-zarr3-False]", "tests/v3/test_group.py::test_asyncgroup_create_array[memory-zarr2-True]", "tests/v3/test_group.py::test_asyncgroup_create_array[memory-zarr2-False]", "tests/v3/test_group.py::test_asyncgroup_create_array[memory-zarr3-True]", "tests/v3/test_group.py::test_asyncgroup_create_array[memory-zarr3-False]", "tests/v3/test_group.py::test_asyncgroup_create_array[zip-zarr2-True]", "tests/v3/test_group.py::test_asyncgroup_create_array[zip-zarr2-False]", "tests/v3/test_group.py::test_asyncgroup_create_array[zip-zarr3-True]", "tests/v3/test_group.py::test_asyncgroup_create_array[zip-zarr3-False]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[local-zarr2]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[local-zarr3]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[memory-zarr2]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[memory-zarr3]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[zip-zarr2]", "tests/v3/test_group.py::test_asyncgroup_update_attributes[zip-zarr3]", "tests/v3/test_group.py::test_serializable_async_group[2-local]", "tests/v3/test_group.py::test_serializable_async_group[3-local]", "tests/v3/test_group.py::test_serializable_sync_group[2-local]", "tests/v3/test_group.py::test_serializable_sync_group[3-local]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_type[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_type[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_mode[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_mode[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_not_writable_store_raises[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_not_writable_store_raises[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-None-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-None-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-None-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-None--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-None--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-None--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range1-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range1-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range1-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range1--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range1--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range1--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range2-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range2-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range2-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range2--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range2--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range2--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range3-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range3-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range3-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range3--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range3--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range3--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range4-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range4-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range4-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range4--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range4--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[None-byte_range4--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-None-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-None-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-None-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-None--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-None--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-None--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range1-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range1-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range1-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range1--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range1--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range1--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range2-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range2-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range2-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range2--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range2--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range2--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range3-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range3-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range3-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range3--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range3--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range3--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range4-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range4-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range4-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range4--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range4--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get[True-byte_range4--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[None-\\x01\\x02\\x03\\x04-zarr.json]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[None-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[None-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[None-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[None--zarr.json]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[None--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[None--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[None--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[True-\\x01\\x02\\x03\\x04-zarr.json]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[True-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[True-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[True-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[True--zarr.json]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[True--c/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[True--foo/c/0.0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set[True--foo/0/0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get_partial_values[None-key_ranges0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get_partial_values[None-key_ranges1]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get_partial_values[None-key_ranges2]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get_partial_values[None-key_ranges3]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get_partial_values[True-key_ranges0]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get_partial_values[True-key_ranges1]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get_partial_values[True-key_ranges2]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_get_partial_values[True-key_ranges3]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_exists[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_exists[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_delete[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_delete[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_empty[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_empty[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_clear[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_clear[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_list[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_list[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_list_dir[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_list_dir[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set_get[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_set_get[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_repr[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_repr[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_supports_writes[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_supports_writes[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_supports_listing[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_supports_listing[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_supports_partial_writes[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_store_supports_partial_writes[True]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_list_prefix[None]", "tests/v3/test_store/test_memory.py::TestMemoryStore::test_list_prefix[True]", "tests/v3/test_store/test_remote.py::test_basic", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_type[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_type[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_mode[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_mode[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_not_writable_store_raises[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_not_writable_store_raises[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-None-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-None-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-None-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-None--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-None--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-None--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range1-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range1-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range1-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range1--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range1--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range1--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range2-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range2-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range2-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range2--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range2--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range2--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range3-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range3-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range3-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range3--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range3--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range3--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range4-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range4-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range4-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range4--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range4--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_upath-byte_range4--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-None-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-None-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-None-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-None--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-None--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-None--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range1-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range1-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range1-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range1--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range1--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range1--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range2-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range2-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range2-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range2--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range2--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range2--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range3-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range3-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range3-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range3--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range3--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range3--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range4-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range4-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range4-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range4--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range4--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get[use_str-byte_range4--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_upath-\\x01\\x02\\x03\\x04-zarr.json]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_upath-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_upath-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_upath-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_upath--zarr.json]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_upath--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_upath--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_upath--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_str-\\x01\\x02\\x03\\x04-zarr.json]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_str-\\x01\\x02\\x03\\x04-c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_str-\\x01\\x02\\x03\\x04-foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_str-\\x01\\x02\\x03\\x04-foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_str--zarr.json]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_str--c/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_str--foo/c/0.0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set[use_str--foo/0/0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get_partial_values[use_upath-key_ranges0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get_partial_values[use_upath-key_ranges1]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get_partial_values[use_upath-key_ranges2]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get_partial_values[use_upath-key_ranges3]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get_partial_values[use_str-key_ranges0]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get_partial_values[use_str-key_ranges1]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get_partial_values[use_str-key_ranges2]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_get_partial_values[use_str-key_ranges3]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_exists[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_exists[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_delete[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_delete[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_empty[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_empty[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_clear[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_clear[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_list[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_list[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_list_dir[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_list_dir[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set_get[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_set_get[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_repr[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_repr[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_supports_writes[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_supports_writes[use_str]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_supports_listing[use_upath]", "tests/v3/test_store/test_remote.py::TestRemoteStoreS3::test_store_supports_listing[use_str]" ]
[]
MIT License
18,858
1,274
[ "src/zarr/abc/store.py", "src/zarr/core/buffer/core.py", "src/zarr/store/memory.py", "src/zarr/store/remote.py", "src/zarr/store/zip.py" ]
scverse__spatialdata-610
f0c603ddfa6fb3d04a0af80a7d9fa4d0e411412e
2024-07-02 07:18:10
f0c603ddfa6fb3d04a0af80a7d9fa4d0e411412e
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/scverse/spatialdata/pull/610?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=scverse) Report All modified and coverable lines are covered by tests :white_check_mark: > Project coverage is 91.94%. Comparing base [(`0727b08`)](https://app.codecov.io/gh/scverse/spatialdata/commit/0727b0810c5ac09c5b9ee2241b32302e00f5c1ac?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=scverse) to head [(`710ec03`)](https://app.codecov.io/gh/scverse/spatialdata/commit/710ec03f715a7ae1cadb387739f77d589b63ef42?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=scverse). > Report is 4 commits behind head on main. <details><summary>Additional details and impacted files</summary> ```diff @@ Coverage Diff @@ ## main #610 +/- ## ========================================== + Coverage 91.91% 91.94% +0.02% ========================================== Files 44 44 Lines 6641 6651 +10 ========================================== + Hits 6104 6115 +11 + Misses 537 536 -1 ``` | [Files](https://app.codecov.io/gh/scverse/spatialdata/pull/610?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=scverse) | Coverage Δ | | |---|---|---| | [src/spatialdata/\_core/spatialdata.py](https://app.codecov.io/gh/scverse/spatialdata/pull/610?src=pr&el=tree&filepath=src%2Fspatialdata%2F_core%2Fspatialdata.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=scverse#diff-c3JjL3NwYXRpYWxkYXRhL19jb3JlL3NwYXRpYWxkYXRhLnB5) | `91.01% <100.00%> (+0.11%)` | :arrow_up: | | [src/spatialdata/models/\_utils.py](https://app.codecov.io/gh/scverse/spatialdata/pull/610?src=pr&el=tree&filepath=src%2Fspatialdata%2Fmodels%2F_utils.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=scverse#diff-c3JjL3NwYXRpYWxkYXRhL21vZGVscy9fdXRpbHMucHk=) | `91.55% <100.00%> (+0.64%)` | :arrow_up: | | [src/spatialdata/models/models.py](https://app.codecov.io/gh/scverse/spatialdata/pull/610?src=pr&el=tree&filepath=src%2Fspatialdata%2Fmodels%2Fmodels.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=scverse#diff-c3JjL3NwYXRpYWxkYXRhL21vZGVscy9tb2RlbHMucHk=) | `87.61% <100.00%> (-0.09%)` | :arrow_down: | ... and [4 files with indirect coverage changes](https://app.codecov.io/gh/scverse/spatialdata/pull/610/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=scverse) </details>
diff --git a/src/spatialdata/_core/spatialdata.py b/src/spatialdata/_core/spatialdata.py index 4be04f8..456bcba 100644 --- a/src/spatialdata/_core/spatialdata.py +++ b/src/spatialdata/_core/spatialdata.py @@ -37,7 +37,7 @@ from spatialdata.models import ( get_model, get_table_keys, ) -from spatialdata.models._utils import SpatialElement, get_axes_names +from spatialdata.models._utils import SpatialElement, convert_region_column_to_categorical, get_axes_names if TYPE_CHECKING: from spatialdata._core.query.spatial_query import BaseSpatialRequest @@ -471,6 +471,7 @@ class SpatialData: self._set_table_annotation_target(table, region, region_key, instance_key) else: raise TypeError("No current annotation metadata found. Please specify both region_key and instance_key.") + convert_region_column_to_categorical(table) @property def query(self) -> QueryManager: diff --git a/src/spatialdata/models/_utils.py b/src/spatialdata/models/_utils.py index 55b4251..71cf8c9 100644 --- a/src/spatialdata/models/_utils.py +++ b/src/spatialdata/models/_utils.py @@ -1,11 +1,14 @@ from __future__ import annotations +import warnings from functools import singledispatch from typing import TYPE_CHECKING, Any, Union import dask.dataframe as dd import geopandas import numpy as np +import pandas as pd +from anndata import AnnData from dask.dataframe import DataFrame as DaskDataFrame from datatree import DataTree from geopandas import GeoDataFrame @@ -359,3 +362,18 @@ def get_raster_model_from_data_dims(dims: tuple[str, ...]) -> type[RasterSchema] if C in dims: return Image3DModel if Z in dims else Image2DModel return Labels3DModel if Z in dims else Labels2DModel + + +def convert_region_column_to_categorical(table: AnnData) -> AnnData: + from spatialdata.models.models import TableModel + + if TableModel.ATTRS_KEY in table.uns: + region_key = table.uns[TableModel.ATTRS_KEY][TableModel.REGION_KEY_KEY] + if not isinstance(table.obs[region_key].dtype, pd.CategoricalDtype): + warnings.warn( + f"Converting `{TableModel.REGION_KEY_KEY}: {region_key}` to categorical dtype.", + UserWarning, + stacklevel=2, + ) + table.obs[region_key] = pd.Categorical(table.obs[region_key]) + return table diff --git a/src/spatialdata/models/models.py b/src/spatialdata/models/models.py index 943b669..bdf1c9e 100644 --- a/src/spatialdata/models/models.py +++ b/src/spatialdata/models/models.py @@ -43,6 +43,7 @@ from spatialdata.models._utils import ( MappingToCoordinateSystem_t, SpatialElement, _validate_mapping_to_coordinate_system_type, + convert_region_column_to_categorical, ) from spatialdata.transformations._utils import ( _get_transformations, @@ -939,11 +940,7 @@ class TableModel: region_: list[str] = region if isinstance(region, list) else [region] if not adata.obs[region_key].isin(region_).all(): raise ValueError(f"`adata.obs[{region_key}]` values do not match with `{cls.REGION_KEY}` values.") - if not isinstance(adata.obs[region_key].dtype, CategoricalDtype): - warnings.warn( - f"Converting `{cls.REGION_KEY_KEY}: {region_key}` to categorical dtype.", UserWarning, stacklevel=2 - ) - adata.obs[region_key] = pd.Categorical(adata.obs[region_key]) + if instance_key is None: raise ValueError("`instance_key` must be provided.") @@ -959,7 +956,7 @@ class TableModel: attr = {"region": region, "region_key": region_key, "instance_key": instance_key} adata.uns[cls.ATTRS_KEY] = attr cls().validate(adata) - return adata + return convert_region_column_to_categorical(adata) Schema_t = Union[
`set_table_annotates_spatialelement` doesn't return a valid table https://github.com/scverse/spatialdata/blob/9e07583f13a70be0855c94ce54b18f133f5ab5b8/src/spatialdata/_core/spatialdata.py#L432 using this, it returns a table that is not valid. Specifically, it fails at write time due to region not being categorical. I believe because the table is never actually parsed somehow, but important to check where does this check fail cc. @lotte-vandevreken @lopollar
scverse/spatialdata
diff --git a/tests/io/test_multi_table.py b/tests/io/test_multi_table.py index 8f6d818..4140633 100644 --- a/tests/io/test_multi_table.py +++ b/tests/io/test_multi_table.py @@ -95,7 +95,8 @@ class TestMultiTable: ): full_sdata.set_table_annotates_spatialelement("table", "non_existing") - def test_set_table_annotates_spatialelement(self, full_sdata): + def test_set_table_annotates_spatialelement(self, full_sdata, tmp_path): + tmpdir = Path(tmp_path) / "tmp.zarr" del full_sdata["table"].uns[TableModel.ATTRS_KEY] with pytest.raises( TypeError, match="No current annotation metadata found. " "Please specify both region_key and instance_key." @@ -120,6 +121,12 @@ class TestMultiTable: "table", pd.Series(["circles", "poly"]), region_key="region", instance_key="instance_id" ) + full_sdata["table"].obs["region"] = "circles" + full_sdata.set_table_annotates_spatialelement( + "table", "circles", region_key="region", instance_key="instance_id" + ) + full_sdata.write(tmpdir) + def test_old_accessor_deprecation(self, full_sdata, tmp_path): # To test self._backed tmpdir = Path(tmp_path) / "tmp.zarr"
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore==2.5.4 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aioitertools==0.12.0 aiosignal==1.3.2 anndata==0.10.9 array_api_compat==1.11.2 asciitree==0.3.3 async-timeout==5.0.1 attrs==25.3.0 botocore==1.31.17 bump2version==1.0.1 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 cloudpickle==3.1.1 colorcet==3.1.0 dask==2024.8.0 dask-expr==1.1.10 dask-image==2024.5.3 datashader==0.17.0 distributed==2024.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work fasteners==0.19 frozenlist==1.5.0 fsspec==2023.6.0 geopandas==1.0.1 h5py==3.13.0 idna==3.10 imageio==2.37.0 importlib_metadata==8.6.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 jmespath==1.0.1 lazy_loader==0.4 llvmlite==0.43.0 locket==1.0.0 markdown-it-py==3.0.0 MarkupSafe==3.0.2 mdurl==0.1.2 msgpack==1.1.0 multidict==6.2.0 multipledispatch==1.0.0 multiscale_spatial_image==1.0.1 natsort==8.4.0 networkx==3.2.1 numba==0.60.0 numcodecs==0.12.1 numpy==2.0.2 ome-zarr==0.10.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 param==2.2.0 partd==1.4.2 pillow==11.1.0 PIMS==0.7 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pooch==1.8.2 propcache==0.3.1 psutil==7.0.0 pyarrow==19.0.1 pyct==0.5.0 Pygments==2.19.1 pyogrio==0.10.0 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 requests==2.32.3 rich==14.0.0 s3fs==2023.6.0 scikit-image==0.24.0 scipy==1.13.1 shapely==2.0.7 six==1.17.0 slicerator==1.1.0 sortedcontainers==2.4.0 spatial_image==1.1.0 -e git+https://github.com/scverse/spatialdata.git@f0c603ddfa6fb3d04a0af80a7d9fa4d0e411412e#egg=spatialdata tblib==3.0.0 tifffile==2024.8.30 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work toolz==1.0.0 tornado==6.4.2 typing_extensions==4.13.0 tzdata==2025.2 urllib3==1.26.20 wrapt==1.17.2 xarray==2024.7.0 xarray-dataclasses==1.9.1 xarray-datatree==0.0.15 xarray-schema==0.0.3 xarray-spatial==0.4.0 yarl==1.18.3 zarr==2.18.2 zict==3.0.0 zipp==3.21.0
name: spatialdata channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aiobotocore==2.5.4 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aioitertools==0.12.0 - aiosignal==1.3.2 - anndata==0.10.9 - array-api-compat==1.11.2 - asciitree==0.3.3 - async-timeout==5.0.1 - attrs==25.3.0 - botocore==1.31.17 - bump2version==1.0.1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - cloudpickle==3.1.1 - colorcet==3.1.0 - dask==2024.8.0 - dask-expr==1.1.10 - dask-image==2024.5.3 - datashader==0.17.0 - distributed==2024.8.0 - fasteners==0.19 - frozenlist==1.5.0 - fsspec==2023.6.0 - geopandas==1.0.1 - h5py==3.13.0 - idna==3.10 - imageio==2.37.0 - importlib-metadata==8.6.1 - jinja2==3.1.6 - jmespath==1.0.1 - lazy-loader==0.4 - llvmlite==0.43.0 - locket==1.0.0 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - mdurl==0.1.2 - msgpack==1.1.0 - multidict==6.2.0 - multipledispatch==1.0.0 - multiscale-spatial-image==1.0.1 - natsort==8.4.0 - networkx==3.2.1 - numba==0.60.0 - numcodecs==0.12.1 - numpy==2.0.2 - ome-zarr==0.10.2 - pandas==2.2.3 - param==2.2.0 - partd==1.4.2 - pillow==11.1.0 - pims==0.7 - platformdirs==4.3.7 - pooch==1.8.2 - propcache==0.3.1 - psutil==7.0.0 - pyarrow==19.0.1 - pyct==0.5.0 - pygments==2.19.1 - pyogrio==0.10.0 - pyproj==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - requests==2.32.3 - rich==14.0.0 - s3fs==2023.6.0 - scikit-image==0.24.0 - scipy==1.13.1 - shapely==2.0.7 - six==1.17.0 - slicerator==1.1.0 - sortedcontainers==2.4.0 - spatial-image==1.1.0 - spatialdata==0.1.3.dev52+gf0c603d - tblib==3.0.0 - tifffile==2024.8.30 - toolz==1.0.0 - tornado==6.4.2 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==1.26.20 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-dataclasses==1.9.1 - xarray-datatree==0.0.15 - xarray-schema==0.0.3 - xarray-spatial==0.4.0 - yarl==1.18.3 - zarr==2.18.2 - zict==3.0.0 - zipp==3.21.0 prefix: /opt/conda/envs/spatialdata
[ "tests/io/test_multi_table.py::TestMultiTable::test_set_table_annotates_spatialelement" ]
[]
[ "tests/io/test_multi_table.py::TestMultiTable::test_set_get_tables_from_spatialdata", "tests/io/test_multi_table.py::TestMultiTable::test_change_annotation_target[None-None-Specified", "tests/io/test_multi_table.py::TestMultiTable::test_change_annotation_target[region-None-Specified", "tests/io/test_multi_table.py::TestMultiTable::test_change_annotation_target[region-instance_id-Instance", "tests/io/test_multi_table.py::TestMultiTable::test_change_annotation_target[None-instance_id-Instance", "tests/io/test_multi_table.py::TestMultiTable::test_set_table_nonexisting_target", "tests/io/test_multi_table.py::TestMultiTable::test_old_accessor_deprecation", "tests/io/test_multi_table.py::TestMultiTable::test_single_table[test_shapes]", "tests/io/test_multi_table.py::TestMultiTable::test_single_table[non_existing]", "tests/io/test_multi_table.py::TestMultiTable::test_paired_elements_tables", "tests/io/test_multi_table.py::TestMultiTable::test_single_table_multiple_elements", "tests/io/test_multi_table.py::TestMultiTable::test_multiple_table_without_element", "tests/io/test_multi_table.py::TestMultiTable::test_multiple_tables_same_element", "tests/io/test_multi_table.py::test_concatenate_sdata_multitables", "tests/io/test_multi_table.py::test_static_set_annotation_target" ]
[]
BSD 3-Clause "New" or "Revised" License
18,859
1,015
[ "src/spatialdata/_core/spatialdata.py", "src/spatialdata/models/_utils.py", "src/spatialdata/models/models.py" ]