repo
stringclasses
6 values
instance_id
stringlengths
20
34
base_commit
stringlengths
40
40
patch
stringlengths
483
2.26k
test_patch
stringlengths
549
4.52k
problem_statement
stringlengths
460
6.7k
hints_text
stringlengths
0
4.04k
created_at
stringlengths
20
20
version
stringlengths
3
4
FAIL_TO_PASS
stringlengths
47
347
PASS_TO_PASS
stringlengths
2
24.3k
environment_setup_commit
stringlengths
40
40
sqlfluff/sqlfluff
sqlfluff__sqlfluff-1625
14e1a23a3166b9a645a16de96f694c77a5d4abb7
diff --git a/src/sqlfluff/rules/L031.py b/src/sqlfluff/rules/L031.py --- a/src/sqlfluff/rules/L031.py +++ b/src/sqlfluff/rules/L031.py @@ -211,7 +211,7 @@ def _lint_aliases_in_join( violation_buff.append( LintResult( anchor=alias_info.alias_identifier_ref, - description="Avoid using aliases in join condition", + description="Avoid aliases in from clauses and join conditions.", fixes=fixes, ) )
diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py --- a/test/cli/commands_test.py +++ b/test/cli/commands_test.py @@ -49,7 +49,7 @@ def invoke_assert_code( expected_output = """== [test/fixtures/linter/indentation_error_simple.sql] FAIL L: 2 | P: 4 | L003 | Indentation not hanging or a multiple of 4 spaces L: 5 | P: 10 | L010 | Keywords must be consistently upper case. -L: 5 | P: 13 | L031 | Avoid using aliases in join condition +L: 5 | P: 13 | L031 | Avoid aliases in from clauses and join conditions. """
TSQL - L031 incorrectly triggers "Avoid using aliases in join condition" when no join present ## Expected Behaviour Both of these queries should pass, the only difference is the addition of a table alias 'a': 1/ no alias ``` SELECT [hello] FROM mytable ``` 2/ same query with alias ``` SELECT a.[hello] FROM mytable AS a ``` ## Observed Behaviour 1/ passes 2/ fails with: L031: Avoid using aliases in join condition. But there is no join condition :-) ## Steps to Reproduce Lint queries above ## Dialect TSQL ## Version sqlfluff 0.6.9 Python 3.6.9 ## Configuration N/A
Actually, re-reading the docs I think this is the intended behaviour... closing
2021-10-13T11:35:29Z
0.6
["test/cli/commands_test.py::test__cli__command_directed"]
["test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-65-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]"]
67023b85c41d23d6c6d69812a41b207c4f8a9331
sqlfluff/sqlfluff
sqlfluff__sqlfluff-2419
f1dba0e1dd764ae72d67c3d5e1471cf14d3db030
diff --git a/src/sqlfluff/rules/L060.py b/src/sqlfluff/rules/L060.py --- a/src/sqlfluff/rules/L060.py +++ b/src/sqlfluff/rules/L060.py @@ -59,4 +59,8 @@ def _eval(self, context: RuleContext) -> Optional[LintResult]: ], ) - return LintResult(context.segment, [fix]) + return LintResult( + anchor=context.segment, + fixes=[fix], + description=f"Use 'COALESCE' instead of '{context.segment.raw_upper}'.", + )
diff --git a/test/rules/std_L060_test.py b/test/rules/std_L060_test.py new file mode 100644 --- /dev/null +++ b/test/rules/std_L060_test.py @@ -0,0 +1,12 @@ +"""Tests the python routines within L060.""" +import sqlfluff + + +def test__rules__std_L060_raised() -> None: + """L060 is raised for use of ``IFNULL`` or ``NVL``.""" + sql = "SELECT\n\tIFNULL(NULL, 100),\n\tNVL(NULL,100);" + result = sqlfluff.lint(sql, rules=["L060"]) + + assert len(result) == 2 + assert result[0]["description"] == "Use 'COALESCE' instead of 'IFNULL'." + assert result[1]["description"] == "Use 'COALESCE' instead of 'NVL'."
Rule L060 could give a specific error message At the moment rule L060 flags something like this: ``` L: 21 | P: 9 | L060 | Use 'COALESCE' instead of 'IFNULL' or 'NVL'. ``` Since we likely know the wrong word, it might be nice to actually flag that instead of both `IFNULL` and `NVL` - like most of the other rules do. That is it should flag this: ``` L: 21 | P: 9 | L060 | Use 'COALESCE' instead of 'IFNULL'. ``` Or this: ``` L: 21 | P: 9 | L060 | Use 'COALESCE' instead of 'NVL'. ``` As appropriate. What do you think @jpy-git ?
@tunetheweb Yeah definitely, should be a pretty quick change 😊
2022-01-22T12:21:52Z
0.8
["test/rules/std_L060_test.py::test__rules__std_L060_raised"]
[]
a5c4eae4e3e419fe95460c9afd9cf39a35a470c4
sqlfluff/sqlfluff
sqlfluff__sqlfluff-1733
a1579a16b1d8913d9d7c7d12add374a290bcc78c
diff --git a/src/sqlfluff/rules/L039.py b/src/sqlfluff/rules/L039.py --- a/src/sqlfluff/rules/L039.py +++ b/src/sqlfluff/rules/L039.py @@ -44,7 +44,9 @@ def _eval(self, context: RuleContext) -> Optional[List[LintResult]]: # This is to avoid indents if not prev_newline: prev_whitespace = seg - prev_newline = False + # We won't set prev_newline to False, just for whitespace + # in case there's multiple indents, inserted by other rule + # fixes (see #1713) elif seg.is_type("comment"): prev_newline = False prev_whitespace = None
diff --git a/test/rules/std_L003_L036_L039_combo_test.py b/test/rules/std_L003_L036_L039_combo_test.py new file mode 100644 --- /dev/null +++ b/test/rules/std_L003_L036_L039_combo_test.py @@ -0,0 +1,36 @@ +"""Tests issue #1373 doesn't reoccur. + +The combination of L003 (incorrect indentation), L036 (select targets), +and L039 (unnecessary white space) can result in incorrect indentation. +""" + +import sqlfluff + + +def test__rules__std_L003_L036_L039(): + """Verify that double indents don't flag L039.""" + sql = """ + WITH example AS ( + SELECT my_id, + other_thing, + one_more + FROM + my_table + ) + + SELECT * + FROM example\n""" + fixed_sql = """ + WITH example AS ( + SELECT + my_id, + other_thing, + one_more + FROM + my_table + ) + + SELECT * + FROM example\n""" + result = sqlfluff.fix(sql) + assert result == fixed_sql diff --git a/test/rules/std_L016_L36_combo.py b/test/rules/std_L016_L36_combo_test.py similarity index 100% rename from test/rules/std_L016_L36_combo.py rename to test/rules/std_L016_L36_combo_test.py
Extra space when first field moved to new line in a WITH statement Note, the query below uses a `WITH` statement. If I just try to fix the SQL within the CTE, this works fine. Given the following SQL: ```sql WITH example AS ( SELECT my_id, other_thing, one_more FROM my_table ) SELECT * FROM example ``` ## Expected Behaviour after running `sqlfluff fix` I'd expect (`my_id` gets moved down and indented properly): ```sql WITH example AS ( SELECT my_id, other_thing, one_more FROM my_table ) SELECT * FROM example ``` ## Observed Behaviour after running `sqlfluff fix` we get (notice that `my_id` is indented one extra space) ```sql WITH example AS ( SELECT my_id, other_thing, one_more FROM my_table ) SELECT * FROM example ``` ## Steps to Reproduce Noted above. Create a file with the initial SQL and fun `sqfluff fix` on it. ## Dialect Running with default config. ## Version Include the output of `sqlfluff --version` along with your Python version sqlfluff, version 0.7.0 Python 3.7.5 ## Configuration Default config.
Does running `sqlfluff fix` again correct the SQL? @tunetheweb yes, yes it does. Is that something that the user is supposed to do (run it multiple times) or is this indeed a bug? Ideally not, but there are some circumstances where it’s understandable that would happen. This however seems an easy enough example where it should not happen. This appears to be a combination of rules L036, L003, and L039 not playing nicely together. The original error is rule L036 and it produces this: ```sql WITH example AS ( SELECT my_id, other_thing, one_more FROM my_table ) SELECT * FROM example ``` That is, it moves the `my_id` down to the newline but does not even try to fix the indentation. Then we have another run through and L003 spots the lack of indentation and fixes it by adding the first set of whitespace: ```sql WITH example AS ( SELECT my_id, other_thing, one_more FROM my_table ) SELECT * FROM example ``` Then we have another run through and L003 spots that there still isn't enough indentation and fixes it by adding the second set of whitespace: ```sql WITH example AS ( SELECT my_id, other_thing, one_more FROM my_table ) SELECT * FROM example ``` At this point we're all good. However then L039 has a look. It never expects two sets of whitespace following a new line and is specifically coded to only assume one set of spaces (which it normally would be if the other rules hadn't interfered as it would be parsed as one big space), so it think's the second set is too much indentation, so it replaces it with a single space. Then another run and L003 and the whitespace back in so we end up with two indents, and a single space. Luckily the fix is easier than that explanation. PR coming up...
2021-10-22T18:23:33Z
0.6
["test/rules/std_L003_L036_L039_combo_test.py::test__rules__std_L003_L036_L039"]
["test/rules/std_L016_L36_combo_test.py::test__rules__std_L016_L036_long_line_lint", "test/rules/std_L016_L36_combo_test.py::test__rules__std_L016_L036_long_line_fix", "test/rules/std_L016_L36_combo_test.py::test__rules__std_L016_L036_long_line_fix2"]
67023b85c41d23d6c6d69812a41b207c4f8a9331
sqlfluff/sqlfluff
sqlfluff__sqlfluff-1517
304a197829f98e7425a46d872ada73176137e5ae
diff --git a/src/sqlfluff/core/parser/helpers.py b/src/sqlfluff/core/parser/helpers.py --- a/src/sqlfluff/core/parser/helpers.py +++ b/src/sqlfluff/core/parser/helpers.py @@ -2,6 +2,7 @@ from typing import Tuple, List, Any, Iterator, TYPE_CHECKING +from sqlfluff.core.errors import SQLParseError from sqlfluff.core.string_helpers import curtail_string if TYPE_CHECKING: @@ -26,11 +27,11 @@ def check_still_complete( """Check that the segments in are the same as the segments out.""" initial_str = join_segments_raw(segments_in) current_str = join_segments_raw(matched_segments + unmatched_segments) - if initial_str != current_str: # pragma: no cover - raise RuntimeError( - "Dropped elements in sequence matching! {!r} != {!r}".format( - initial_str, current_str - ) + + if initial_str != current_str: + raise SQLParseError( + f"Could not parse: {current_str}", + segment=unmatched_segments[0], ) return True
diff --git a/test/dialects/ansi_test.py b/test/dialects/ansi_test.py --- a/test/dialects/ansi_test.py +++ b/test/dialects/ansi_test.py @@ -3,7 +3,7 @@ import pytest import logging -from sqlfluff.core import FluffConfig, Linter +from sqlfluff.core import FluffConfig, Linter, SQLParseError from sqlfluff.core.parser import Lexer @@ -214,3 +214,29 @@ def test__dialect__ansi_parse_indented_joins(sql_string, indented_joins, meta_lo idx for idx, raw_seg in enumerate(parsed.tree.iter_raw_seg()) if raw_seg.is_meta ) assert res_meta_locs == meta_loc + + [email protected]( + "raw,expected_message", + [ + (";;", "Line 1, Position 1: Found unparsable section: ';;'"), + ("select id from tbl;", ""), + ("select id from tbl;;", "Could not parse: ;"), + ("select id from tbl;;;;;;", "Could not parse: ;;;;;"), + ("select id from tbl;select id2 from tbl2;", ""), + ( + "select id from tbl;;select id2 from tbl2;", + "Could not parse: ;select id2 from tbl2;", + ), + ], +) +def test__dialect__ansi_multiple_semicolons(raw: str, expected_message: str) -> None: + """Multiple semicolons should be properly handled.""" + lnt = Linter() + parsed = lnt.parse_string(raw) + + assert len(parsed.violations) == (1 if expected_message else 0) + if expected_message: + violation = parsed.violations[0] + assert isinstance(violation, SQLParseError) + assert violation.desc() == expected_message
"Dropped elements in sequence matching" when doubled semicolon ## Expected Behaviour Frankly, I'm not sure whether it (doubled `;`) should be just ignored or rather some specific rule should be triggered. ## Observed Behaviour ```console (.venv) ?master ~/prod/_inne/sqlfluff> echo "select id from tbl;;" | sqlfluff lint - Traceback (most recent call last): File "/home/adam/prod/_inne/sqlfluff/.venv/bin/sqlfluff", line 11, in <module> load_entry_point('sqlfluff', 'console_scripts', 'sqlfluff')() File "/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py", line 1137, in __call__ return self.main(*args, **kwargs) File "/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py", line 1062, in main rv = self.invoke(ctx) File "/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py", line 1668, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py", line 763, in invoke return __callback(*args, **kwargs) File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/cli/commands.py", line 347, in lint result = lnt.lint_string_wrapped(sys.stdin.read(), fname="stdin") File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py", line 789, in lint_string_wrapped linted_path.add(self.lint_string(string, fname=fname, fix=fix)) File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py", line 668, in lint_string parsed = self.parse_string(in_str=in_str, fname=fname, config=config) File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py", line 607, in parse_string return self.parse_rendered(rendered, recurse=recurse) File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py", line 313, in parse_rendered parsed, pvs = cls._parse_tokens( File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py", line 190, in _parse_tokens parsed: Optional[BaseSegment] = parser.parse( File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/parser/parser.py", line 32, in parse parsed = root_segment.parse(parse_context=ctx) File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/parser/segments/base.py", line 821, in parse check_still_complete(segments, m.matched_segments, m.unmatched_segments) File "/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/parser/helpers.py", line 30, in check_still_complete raise RuntimeError( RuntimeError: Dropped elements in sequence matching! 'select id from tbl;;' != ';' ``` ## Steps to Reproduce Run ```console echo "select id from tbl;;" | sqlfluff lint - ``` ## Dialect default (ansi) ## Version ``` sqlfluff, version 0.6.6 Python 3.9.5 ``` ## Configuration None
Sounds similar to #1458 where we should handle "empty" statement/files better? Nope, that's the different issue. I doubt that solving one of them would help in other one. I think both issues should stay, just in the case. But what do you think @tunetheweb - should it just ignore these `;;` or raise something like `Found unparsable section:`? Just tested and in BigQuery it's an error. Interestingly Oracle is fine with it. I think it should be raised as `Found unparsable section`.
2021-10-06T07:57:35Z
0.6
["test/dialects/ansi_test.py::test__dialect__ansi_multiple_semicolons[select"]
["test/dialects/ansi_test.py::test__dialect__ansi__file_lex[a", "test/dialects/ansi_test.py::test__dialect__ansi__file_lex[b.c-res1]", "test/dialects/ansi_test.py::test__dialect__ansi__file_lex[abc", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectKeywordSegment-select]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[NakedIdentifierSegment-online_sales]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[BareFunctionSegment-current_timestamp]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[FunctionSegment-current_timestamp()]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[NumericLiteralSegment-1000.0]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-online_sales", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[IntervalExpressionSegment-INTERVAL", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-CASE", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-CAST(ROUND(online_sales", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-name", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-MIN", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-DATE_ADD(CURRENT_DATE('America/New_York'),", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[1]]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[OFFSET(1)]]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[5:8]]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-4", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-bits[OFFSET(0)]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-(count_18_24", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-count_18_24", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectStatementSegment-SELECT", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-t.val/t.id]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-CAST(num", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-a.*]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-a.b.*]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-a.b.c.*]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ObjectReferenceSegment-a..c.*]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment--some_variable]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment--", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-concat(left(uaid,", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-c", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-c", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-NULL::INT]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-NULL::INT", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[TruncateStatementSegment-TRUNCATE", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_not_match[ObjectReferenceSegment-\\n", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_not_parse[SELECT", "test/dialects/ansi_test.py::test__dialect__ansi_is_whitespace", "test/dialects/ansi_test.py::test__dialect__ansi_parse_indented_joins[select", "test/dialects/ansi_test.py::test__dialect__ansi_multiple_semicolons[;;-Line"]
67023b85c41d23d6c6d69812a41b207c4f8a9331
sqlfluff/sqlfluff
sqlfluff__sqlfluff-1763
a10057635e5b2559293a676486f0b730981f037a
diff --git a/src/sqlfluff/core/linter/linted_file.py b/src/sqlfluff/core/linter/linted_file.py --- a/src/sqlfluff/core/linter/linted_file.py +++ b/src/sqlfluff/core/linter/linted_file.py @@ -7,6 +7,8 @@ import os import logging +import shutil +import tempfile from typing import ( Any, Iterable, @@ -493,7 +495,24 @@ def persist_tree(self, suffix: str = "") -> bool: if suffix: root, ext = os.path.splitext(fname) fname = root + suffix + ext - # Actually write the file. - with open(fname, "w", encoding=self.encoding) as f: - f.write(write_buff) + self._safe_create_replace_file(fname, write_buff, self.encoding) return success + + @staticmethod + def _safe_create_replace_file(fname, write_buff, encoding): + # Write to a temporary file first, so in case of encoding or other + # issues, we don't delete or corrupt the user's existing file. + dirname, basename = os.path.split(fname) + with tempfile.NamedTemporaryFile( + mode="w", + encoding=encoding, + prefix=basename, + dir=dirname, + suffix=os.path.splitext(fname)[1], + delete=False, + ) as tmp: + tmp.file.write(write_buff) + tmp.flush() + os.fsync(tmp.fileno()) + # Once the temp file is safely written, replace the existing file. + shutil.move(tmp.name, fname)
diff --git a/test/core/linter_test.py b/test/core/linter_test.py --- a/test/core/linter_test.py +++ b/test/core/linter_test.py @@ -641,3 +641,56 @@ def test__attempt_to_change_templater_warning(caplog): assert "Attempt to set templater to " in caplog.text finally: logger.propagate = original_propagate_value + + [email protected]( + "case", + [ + dict( + name="utf8_create", + fname="test.sql", + encoding="utf-8", + existing=None, + update="def", + expected="def", + ), + dict( + name="utf8_update", + fname="test.sql", + encoding="utf-8", + existing="abc", + update="def", + expected="def", + ), + dict( + name="utf8_special_char", + fname="test.sql", + encoding="utf-8", + existing="abc", + update="→", # Special utf-8 character + expected="→", + ), + dict( + name="incorrect_encoding", + fname="test.sql", + encoding="Windows-1252", + existing="abc", + update="→", # Not valid in Windows-1252 + expected="abc", # File should be unchanged + ), + ], + ids=lambda case: case["name"], +) +def test_safe_create_replace_file(case, tmp_path): + """Test creating or updating .sql files, various content and encoding.""" + p = tmp_path / case["fname"] + if case["existing"]: + p.write_text(case["existing"]) + try: + linter.LintedFile._safe_create_replace_file( + str(p), case["update"], case["encoding"] + ) + except: # noqa: E722 + pass + actual = p.read_text(encoding=case["encoding"]) + assert case["expected"] == actual
dbt postgres fix command errors with UnicodeEncodeError and also wipes the .sql file _If this is a parsing or linting issue, please include a minimal SQL example which reproduces the issue, along with the `sqlfluff parse` output, `sqlfluff lint` output and `sqlfluff fix` output when relevant._ ## Expected Behaviour Violation failure notice at a minimum, without wiping the file. Would like a way to ignore the known error at a minimum as --noqa is not getting past this. Actually would expect --noqa to totally ignore this. ## Observed Behaviour Reported error: `UnicodeEncodeError: 'charmap' codec can't encode character '\u2192' in position 120: character maps to <undefined>` ## Steps to Reproduce SQL file: ```sql SELECT reacted_table_name_right.descendant_id AS category_id, string_agg(redacted_table_name_left.name, ' → ' ORDER BY reacted_table_name_right.generations DESC) AS breadcrumbs -- noqa FROM {{ ref2('redacted_schema_name', 'redacted_table_name_left') }} AS redacted_table_name_left INNER JOIN {{ ref2('redacted_schema_name', 'reacted_table_name_right') }} AS reacted_table_name_right ON redacted_table_name_left.id = order_issue_category_hierarchies.ancestor_id GROUP BY reacted_table_name_right.descendant_id ``` Running `sqlfluff fix --ignore templating,parsing,lexing -vvvv` and accepting proposed fixes for linting violations. ## Dialect `postgres`, with `dbt` templater ## Version `python 3.7.12` `sqlfluff 0.7.0` `sqlfluff-templater-dbt 0.7.0` ## Configuration I've tried a few, here's one: ``` [sqlfluff] verbose = 2 dialect = postgres templater = dbt exclude_rules = None output_line_length = 80 runaway_limit = 10 ignore_templated_areas = True processes = 3 # Comma separated list of file extensions to lint. # NB: This config will only apply in the root folder. sql_file_exts = .sql [sqlfluff:indentation] indented_joins = False indented_using_on = True template_blocks_indent = True [sqlfluff:templater] unwrap_wrapped_queries = True [sqlfluff:templater:jinja] apply_dbt_builtins = True [sqlfluff:templater:jinja:macros] # Macros provided as builtins for dbt projects dbt_ref = {% macro ref(model_ref) %}{{model_ref}}{% endmacro %} dbt_source = {% macro source(source_name, table) %}{{source_name}}_{{table}}{% endmacro %} dbt_config = {% macro config() %}{% for k in kwargs %}{% endfor %}{% endmacro %} dbt_var = {% macro var(variable, default='') %}item{% endmacro %} dbt_is_incremental = {% macro is_incremental() %}True{% endmacro %} # Common config across rules [sqlfluff:rules] tab_space_size = 4 indent_unit = space single_table_references = consistent unquoted_identifiers_policy = all # L001 - Remove trailing whitespace (fix) # L002 - Single section of whitespace should not contain both tabs and spaces (fix) # L003 - Keep consistent indentation (fix) # L004 - We use 4 spaces for indentation just for completeness (fix) # L005 - Remove space before commas (fix) # L006 - Operators (+, -, *, /) will be wrapped by a single space each side (fix) # L007 - Operators should not be at the end of a line [sqlfluff:rules:L007] # Keywords operator_new_lines = after # L008 - Always use a single whitespace after a comma (fix) # L009 - Files will always end with a trailing newline # L010 - All keywords will use full upper case (fix) [sqlfluff:rules:L010] # Keywords capitalisation_policy = upper # L011 - Always explicitly alias tables (fix) [sqlfluff:rules:L011] # Aliasing aliasing = explicit # L012 - Do not have to explicitly alias all columns [sqlfluff:rules:L012] # Aliasing aliasing = explicit # L013 - Always explicitly alias a column with an expression in it (fix) [sqlfluff:rules:L013] # Aliasing allow_scalar = False # L014 - Always user full lower case for 'quoted identifiers' -> column refs. without an alias (fix) [sqlfluff:rules:L014] # Unquoted identifiers extended_capitalisation_policy = lower # L015 - Always remove parenthesis when using DISTINCT to be clear that DISTINCT applies to all columns (fix) # L016 - Lines should be 120 characters of less. Comment lines should not be ignored (fix) [sqlfluff:rules:L016] ignore_comment_lines = False max_line_length = 120 # L017 - There should not be whitespace between function name and brackets (fix) # L018 - Always align closing bracket of WITH to the WITH keyword (fix) # L019 - Always use trailing commas / commas at the end of the line (fix) [sqlfluff:rules:L019] comma_style = trailing # L020 - Table aliases will always be unique per statement # L021 - Remove any use of ambiguous DISTINCT and GROUP BY combinations. Lean on removing the GROUP BY. # L022 - Add blank lines after common table expressions (CTE) / WITH. # L023 - Always add a single whitespace after AS in a WITH clause (fix) [sqlfluff:rules:L026] force_enable = False # L027 - Always add references if more than one referenced table or view is used [sqlfluff:rules:L028] force_enable = False [sqlfluff:rules:L029] # Keyword identifiers unquoted_identifiers_policy = aliases [sqlfluff:rules:L030] # Function names capitalisation_policy = upper # L032 - We prefer use of join keys rather than USING # L034 - We prefer ordering of columns in select statements as (fix): # 1. wildcards # 2. single identifiers # 3. calculations and aggregates # L035 - Omit 'else NULL'; it is redundant (fix) # L036 - Move select targets / identifiers onto new lines each (fix) # L037 - When using ORDER BY, make the direction explicit (fix) # L038 - Never use trailing commas at the end of the SELECT clause [sqlfluff:rules:L038] select_clause_trailing_comma = forbid # L039 - Remove unnecessary whitespace (fix) [sqlfluff:rules:L040] # Null & Boolean Literals capitalisation_policy = upper # L042 - Join clauses should not contain subqueries. Use common tables expressions (CTE) instead. [sqlfluff:rules:L042] # By default, allow subqueries in from clauses, but not join clauses. forbid_subquery_in = join # L043 - Reduce CASE WHEN conditions to COALESCE (fix) # L044 - Prefer a known number of columns along the path to the source data # L045 - Remove unused common tables expressions (CTE) / WITH statements (fix) # L046 - Jinja tags should have a single whitespace on both sides # L047 - Use COUNT(*) instead of COUNT(0) or COUNT(1) alternatives (fix) [sqlfluff:rules:L047] # Consistent syntax to count all rows prefer_count_1 = False prefer_count_0 = False # L048 - Quoted literals should be surrounded by a single whitespace (fix) # L049 - Always use IS or IS NOT for comparisons with NULL (fix) ```
I get a dbt-related error -- can you provide your project file as well? Also, what operating system are you running this on? I tested a simplified (non-dbt) version of your file on my Mac, and it worked okay. ``` dbt.exceptions.DbtProjectError: Runtime Error no dbt_project.yml found at expected path /Users/bhart/dev/sqlfluff/dbt_project.yml ``` Never mind the questions above -- I managed to reproduce the error in a sample dbt project. Taking a look now... @Tumble17: Have you tried setting the `encoding` parameter in `.sqlfluff`? Do you know what encoding you're using? The default is `autodetect`, and SQLFluff "thinks" the file uses "Windows-1252" encoding, which I assume is incorrect -- that's why SQLFluff is unable to write out the updated file. I added this line to the first section of your `.sqlfluff`, and now it seems to work. I'll look into changing the behavior of `sqlfluff fix` so it doesn't erase the file when it fails. ``` encoding = utf-8 ```
2021-10-26T17:28:28Z
0.6
["test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]"]
["test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]"]
67023b85c41d23d6c6d69812a41b207c4f8a9331
marshmallow-code/marshmallow
marshmallow-code__marshmallow-1359
b40a0f4e33823e6d0f341f7e8684e359a99060d1
diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py --- a/src/marshmallow/fields.py +++ b/src/marshmallow/fields.py @@ -1114,7 +1114,7 @@ def _bind_to_schema(self, field_name, schema): super()._bind_to_schema(field_name, schema) self.format = ( self.format - or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME) + or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME) or self.DEFAULT_FORMAT )
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -169,6 +169,20 @@ class OtherSchema(MySchema): assert schema2.fields["foo"].key_field.root == schema2 assert schema2.fields["foo"].value_field.root == schema2 + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1357 + def test_datetime_list_inner_format(self, schema): + class MySchema(Schema): + foo = fields.List(fields.DateTime()) + bar = fields.Tuple((fields.DateTime(),)) + + class Meta: + datetimeformat = "iso8601" + dateformat = "iso8601" + + schema = MySchema() + assert schema.fields["foo"].inner.format == "iso8601" + assert schema.fields["bar"].tuple_fields[0].format == "iso8601" + class TestMetadata: @pytest.mark.parametrize("FieldClass", ALL_FIELDS)
3.0: DateTime fields cannot be used as inner field for List or Tuple fields Between releases 3.0.0rc8 and 3.0.0rc9, `DateTime` fields have started throwing an error when being instantiated as inner fields of container fields like `List` or `Tuple`. The snippet below works in <=3.0.0rc8 and throws the error below in >=3.0.0rc9 (and, worryingly, 3.0.0): ```python from marshmallow import fields, Schema class MySchema(Schema): times = fields.List(fields.DateTime()) s = MySchema() ``` Traceback: ``` Traceback (most recent call last): File "test-mm.py", line 8, in <module> s = MySchema() File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py", line 383, in __init__ self.fields = self._init_fields() File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py", line 913, in _init_fields self._bind_field(field_name, field_obj) File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py", line 969, in _bind_field field_obj._bind_to_schema(field_name, self) File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/fields.py", line 636, in _bind_to_schema self.inner._bind_to_schema(field_name, self) File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/fields.py", line 1117, in _bind_to_schema or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME) AttributeError: 'List' object has no attribute 'opts' ``` It seems like it's treating the parent field as a Schema without checking that it is indeed a schema, so the `schema.opts` statement fails as fields don't have an `opts` attribute.
Thanks for reporting. I don't think I'll have time to look into this until the weekend. Would you like to send a PR? I'm afraid I don't have any time either, and I don't really have enough context on the `_bind_to_schema` process to make sure I'm not breaking stuff. OK, no problem. @lafrech Will you have a chance to look into this? I've found the patch below to fix the minimal example above, but I'm not really sure what it's missing out on or how to test it properly: ```patch diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py index 0b18e7d..700732e 100644 --- a/src/marshmallow/fields.py +++ b/src/marshmallow/fields.py @@ -1114,7 +1114,7 @@ class DateTime(Field): super()._bind_to_schema(field_name, schema) self.format = ( self.format - or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME) + or getattr(getattr(schema, "opts", None), self.SCHEMA_OPTS_VAR_NAME, None) or self.DEFAULT_FORMAT ) ``` git difftool 3.0.0rc8 3.0.0rc9 src/marshmallow/fields.py When reworking container stuff, I changed ```py self.inner.parent = self self.inner.name = field_name ``` into ```py self.inner._bind_to_schema(field_name, self) ``` AFAIR, I did this merely to avoid duplication. On second thought, I think it was the right thing to do, not only for duplication but to actually bind inner fields to the `Schema`. Reverting this avoids the error but the inner field's `_bind_to_schema` method is not called so I'm not sure it is desirable. I think we really mean to call that method, not only in this case but also generally. Changing ```py or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME) ``` into ```py or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME) ``` might be a better fix. Can anyone confirm (@sloria, @deckar01)? The fix in https://github.com/marshmallow-code/marshmallow/issues/1357#issuecomment-523465528 removes the error but also the feature: `DateTime` fields buried into container fields won't respect the format set in the `Schema`. I didn't double-check that but AFAIU, the change I mentioned above (in container stuff rework) was the right thing to do. The feature was already broken (format set in `Schema` not respected if `DateTime` field in container field) and that's just one of the issues that may arise due to the inner field not being bound to the `Schema`. But I may be wrong. On quick glance, your analysis and fix look correct @lafrech Let's do that, then. Not much time either. The first who gets the time can do it. For the non-reg tests : 1/ a test that checks the format set in the schema is respected if the `DateTime` field is in a container field 2/ a set of tests asserting the `_bind_to_schema` method of inner fields `List`, `Dict`, `Tuple` is called from container fields (we can use `DateTime` with the same test case for that) Perhaps 1/ is useless if 2/ is done.
2019-08-21T15:45:13Z
3.0
["tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format"]
["tests/test_fields.py::test_field_aliases[Integer-Integer]", "tests/test_fields.py::test_field_aliases[String-String]", "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", "tests/test_fields.py::test_field_aliases[Url-Url]", "tests/test_fields.py::TestField::test_repr", "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_simple_field_root", "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", "tests/test_fields.py::TestErrorMessages::test_make_error[required-Missing", "tests/test_fields.py::TestErrorMessages::test_make_error[null-Field", "tests/test_fields.py::TestErrorMessages::test_make_error[custom-Custom", "tests/test_fields.py::TestErrorMessages::test_make_error[validator_failed-Invalid", "tests/test_fields.py::TestErrorMessages::test_fail[required-Missing", "tests/test_fields.py::TestErrorMessages::test_fail[null-Field", "tests/test_fields.py::TestErrorMessages::test_fail[custom-Custom", "tests/test_fields.py::TestErrorMessages::test_fail[validator_failed-Invalid", "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestListNested::test_list_nested_only_and_exclude_merged_with_nested[only-expected0]", "tests/test_fields.py::TestListNested::test_list_nested_only_and_exclude_merged_with_nested[exclude-expected1]", "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested"]
8b3a32614fd4a74e93e9a63a042e74c1fea34466
marshmallow-code/marshmallow
marshmallow-code__marshmallow-1343
2be2d83a1a9a6d3d9b85804f3ab545cecc409bb0
diff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py --- a/src/marshmallow/schema.py +++ b/src/marshmallow/schema.py @@ -877,7 +877,7 @@ def _invoke_field_validators(self, unmarshal, data, many): for idx, item in enumerate(data): try: value = item[field_obj.attribute or field_name] - except KeyError: + except (KeyError, TypeError): pass else: validated_value = unmarshal.call_and_store( @@ -892,7 +892,7 @@ def _invoke_field_validators(self, unmarshal, data, many): else: try: value = data[field_obj.attribute or field_name] - except KeyError: + except (KeyError, TypeError): pass else: validated_value = unmarshal.call_and_store(
diff --git a/tests/test_marshalling.py b/tests/test_marshalling.py --- a/tests/test_marshalling.py +++ b/tests/test_marshalling.py @@ -2,7 +2,7 @@ import pytest -from marshmallow import fields, Schema +from marshmallow import fields, Schema, validates from marshmallow.marshalling import Marshaller, Unmarshaller, missing from marshmallow.exceptions import ValidationError @@ -283,3 +283,24 @@ class TestSchema(Schema): assert result is None assert excinfo.value.messages == {'foo': {'_schema': ['Invalid input type.']}} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1342 + def test_deserialize_wrong_nested_type_with_validates_method(self, unmarshal): + class TestSchema(Schema): + value = fields.String() + + @validates('value') + def validate_value(self, value): + pass + + data = { + 'foo': 'not what we need' + } + fields_dict = { + 'foo': fields.Nested(TestSchema, required=True) + } + with pytest.raises(ValidationError) as excinfo: + result = unmarshal.deserialize(data, fields_dict) + + assert result is None + assert excinfo.value.messages == {'foo': {'_schema': ['Invalid input type.']}}
[version 2.20.0] TypeError: 'NoneType' object is not subscriptable After update from version 2.19.5 to 2.20.0 I got error for code like: ```python from marshmallow import Schema, fields, validates class Bar(Schema): value = fields.String() @validates('value') # <- issue here def validate_value(self, value): pass class Foo(Schema): bar = fields.Nested(Bar) sch = Foo() sch.validate({ 'bar': 'invalid', }) ``` ``` Traceback (most recent call last): File "/_/bug_mschema.py", line 19, in <module> 'bar': 'invalid', File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 628, in validate _, errors = self._do_load(data, many, partial=partial, postprocess=False) File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 670, in _do_load index_errors=self.opts.index_errors, File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 292, in deserialize index=(index if index_errors else None) File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 65, in call_and_store value = getter_func(data) File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 285, in <lambda> data File "/_/env/lib/python3.7/site-packages/marshmallow/fields.py", line 265, in deserialize output = self._deserialize(value, attr, data) File "/_/env/lib/python3.7/site-packages/marshmallow/fields.py", line 465, in _deserialize data, errors = self.schema.load(value) File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 588, in load result, errors = self._do_load(data, many, partial=partial, postprocess=True) File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 674, in _do_load self._invoke_field_validators(unmarshal, data=result, many=many) File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 894, in _invoke_field_validators value = data[field_obj.attribute or field_name] TypeError: 'NoneType' object is not subscriptable ```
Thanks for reporting. I was able to reproduce this on 2.20.0. This is likely a regression from https://github.com/marshmallow-code/marshmallow/pull/1323 . I don't have time to look into it now. Would appreciate a PR.
2019-08-13T04:36:01Z
2.20
["tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_nested_type_with_validates_method"]
["tests/test_marshalling.py::test_missing_is_falsy", "tests/test_marshalling.py::TestMarshaller::test_prefix", "tests/test_marshalling.py::TestMarshaller::test_marshalling_generator", "tests/test_marshalling.py::TestMarshaller::test_default_to_missing", "tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_load_only_param", "tests/test_marshalling.py::TestMarshaller::test_missing_data_are_skipped", "tests/test_marshalling.py::TestMarshaller::test_serialize_with_load_only_doesnt_validate", "tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_dump_to_param", "tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_dump_to_and_prefix_params", "tests/test_marshalling.py::TestMarshaller::test_stores_indices_of_errors_when_many_equals_true", "tests/test_marshalling.py::TestMarshaller::test_doesnt_store_errors_when_index_errors_equals_false", "tests/test_marshalling.py::TestUnmarshaller::test_extra_data_is_ignored", "tests/test_marshalling.py::TestUnmarshaller::test_stores_errors", "tests/test_marshalling.py::TestUnmarshaller::test_stores_indices_of_errors_when_many_equals_true", "tests/test_marshalling.py::TestUnmarshaller::test_doesnt_store_errors_when_index_errors_equals_false", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize", "tests/test_marshalling.py::TestUnmarshaller::test_extra_fields", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_many", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_stores_errors", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_attribute_param", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_load_from_param", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_dump_only_param", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_type_root_data", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_type_nested_data"]
7015fc4333a2f32cd58c3465296e834acd4496ff
pvlib/pvlib-python
pvlib__pvlib-python-1707
40e9e978c170bdde4eeee1547729417665dbc34c
diff --git a/pvlib/iam.py b/pvlib/iam.py --- a/pvlib/iam.py +++ b/pvlib/iam.py @@ -175,8 +175,12 @@ def physical(aoi, n=1.526, K=4.0, L=0.002, *, n_ar=None): n2costheta2 = n2 * costheta # reflectance of s-, p-polarized, and normal light by the first interface - rho12_s = ((n1costheta1 - n2costheta2) / (n1costheta1 + n2costheta2)) ** 2 - rho12_p = ((n1costheta2 - n2costheta1) / (n1costheta2 + n2costheta1)) ** 2 + with np.errstate(divide='ignore', invalid='ignore'): + rho12_s = \ + ((n1costheta1 - n2costheta2) / (n1costheta1 + n2costheta2)) ** 2 + rho12_p = \ + ((n1costheta2 - n2costheta1) / (n1costheta2 + n2costheta1)) ** 2 + rho12_0 = ((n1 - n2) / (n1 + n2)) ** 2 # transmittance through the first interface @@ -208,13 +212,22 @@ def physical(aoi, n=1.526, K=4.0, L=0.002, *, n_ar=None): tau_0 *= (1 - rho23_0) / (1 - rho23_0 * rho12_0) # transmittance after absorption in the glass - tau_s *= np.exp(-K * L / costheta) - tau_p *= np.exp(-K * L / costheta) + with np.errstate(divide='ignore', invalid='ignore'): + tau_s *= np.exp(-K * L / costheta) + tau_p *= np.exp(-K * L / costheta) + tau_0 *= np.exp(-K * L) # incidence angle modifier iam = (tau_s + tau_p) / 2 / tau_0 + # for light coming from behind the plane, none can enter the module + # when n2 > 1, this is already the case + if np.isclose(n2, 1).any(): + iam = np.where(aoi >= 90, 0, iam) + if isinstance(aoi, pd.Series): + iam = pd.Series(iam, index=aoi.index) + return iam
diff --git a/pvlib/tests/test_iam.py b/pvlib/tests/test_iam.py --- a/pvlib/tests/test_iam.py +++ b/pvlib/tests/test_iam.py @@ -51,6 +51,18 @@ def test_physical(): assert_series_equal(iam, expected) +def test_physical_n1_L0(): + aoi = np.array([0, 22.5, 45, 67.5, 90, 100, np.nan]) + expected = np.array([1, 1, 1, 1, 0, 0, np.nan]) + iam = _iam.physical(aoi, n=1, L=0) + assert_allclose(iam, expected, equal_nan=True) + + aoi = pd.Series(aoi) + expected = pd.Series(expected) + iam = _iam.physical(aoi, n=1, L=0) + assert_series_equal(iam, expected) + + def test_physical_ar(): aoi = np.array([0, 22.5, 45, 67.5, 90, 100, np.nan]) expected = np.array([1, 0.99944171, 0.9917463, 0.91506158, 0, 0, np.nan])
regression: iam.physical returns nan for aoi > 90° when n = 1 **Describe the bug** For pvlib==0.9.5, when n = 1 (no reflection) and aoi > 90°, we get nan as result. **To Reproduce** ```python import pvlib pvlib.iam.physical(aoi=100, n=1) ``` returns `nan`. **Expected behavior** The result should be `0`, as it was for pvlib <= 0.9.4. **Versions:** - ``pvlib.__version__``: '0.9.5' - ``pandas.__version__``: '1.5.3' - python: 3.10.4
2023-03-24T10:46:42Z
0.9
["pvlib/tests/test_iam.py::test_physical_n1_L0"]
["pvlib/tests/test_iam.py::test_ashrae", "pvlib/tests/test_iam.py::test_ashrae_scalar", "pvlib/tests/test_iam.py::test_physical", "pvlib/tests/test_iam.py::test_physical_ar", "pvlib/tests/test_iam.py::test_physical_noar", "pvlib/tests/test_iam.py::test_physical_scalar", "pvlib/tests/test_iam.py::test_martin_ruiz", "pvlib/tests/test_iam.py::test_martin_ruiz_exception", "pvlib/tests/test_iam.py::test_martin_ruiz_diffuse", "pvlib/tests/test_iam.py::test_iam_interp", "pvlib/tests/test_iam.py::test_sapm[45-0.9975036250000002]", "pvlib/tests/test_iam.py::test_sapm[aoi1-expected1]", "pvlib/tests/test_iam.py::test_sapm[aoi2-expected2]", "pvlib/tests/test_iam.py::test_sapm_limits", "pvlib/tests/test_iam.py::test_marion_diffuse_model", "pvlib/tests/test_iam.py::test_marion_diffuse_kwargs", "pvlib/tests/test_iam.py::test_marion_diffuse_invalid", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[sky-180-0.9596085829811408]", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[horizon-1800-0.8329070417832541]", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[ground-180-0.719823559106309]", "pvlib/tests/test_iam.py::test_marion_integrate_list[sky-180-expected0]", "pvlib/tests/test_iam.py::test_marion_integrate_list[horizon-1800-expected1]", "pvlib/tests/test_iam.py::test_marion_integrate_list[ground-180-expected2]", "pvlib/tests/test_iam.py::test_marion_integrate_series[sky-180-expected0]", "pvlib/tests/test_iam.py::test_marion_integrate_series[horizon-1800-expected1]", "pvlib/tests/test_iam.py::test_marion_integrate_series[ground-180-expected2]", "pvlib/tests/test_iam.py::test_marion_integrate_ground_flat", "pvlib/tests/test_iam.py::test_marion_integrate_invalid", "pvlib/tests/test_iam.py::test_schlick", "pvlib/tests/test_iam.py::test_schlick_diffuse"]
6072e0982c3c0236f532ddfa48fbf461180d834e
pvlib/pvlib-python
pvlib__pvlib-python-1072
04a523fafbd61bc2e49420963b84ed8e2bd1b3cf
diff --git a/pvlib/temperature.py b/pvlib/temperature.py --- a/pvlib/temperature.py +++ b/pvlib/temperature.py @@ -599,8 +599,9 @@ def fuentes(poa_global, temp_air, wind_speed, noct_installed, module_height=5, # n.b. the way Fuentes calculates the first timedelta makes it seem like # the value doesn't matter -- rather than recreate it here, just assume # it's the same as the second timedelta: - timedelta_hours = np.diff(poa_global.index).astype(float) / 1e9 / 60 / 60 - timedelta_hours = np.append([timedelta_hours[0]], timedelta_hours) + timedelta_seconds = poa_global.index.to_series().diff().dt.total_seconds() + timedelta_hours = timedelta_seconds / 3600 + timedelta_hours.iloc[0] = timedelta_hours.iloc[1] tamb_array = temp_air + 273.15 sun_array = poa_global * absorp
diff --git a/pvlib/tests/test_temperature.py b/pvlib/tests/test_temperature.py --- a/pvlib/tests/test_temperature.py +++ b/pvlib/tests/test_temperature.py @@ -190,3 +190,17 @@ def test_fuentes(filename, inoct): night_difference = expected_tcell[is_night] - actual_tcell[is_night] assert night_difference.max() < 6 assert night_difference.min() > 0 + + [email protected]('tz', [None, 'Etc/GMT+5']) +def test_fuentes_timezone(tz): + index = pd.date_range('2019-01-01', freq='h', periods=3, tz=tz) + + df = pd.DataFrame({'poa_global': 1000, 'temp_air': 20, 'wind_speed': 1}, + index) + + out = temperature.fuentes(df['poa_global'], df['temp_air'], + df['wind_speed'], noct_installed=45) + + assert_series_equal(out, pd.Series([47.85, 50.85, 50.85], index=index, + name='tmod'))
temperature.fuentes errors when given tz-aware inputs on pandas>=1.0.0 **Describe the bug** When the weather timeseries inputs to `temperature.fuentes` have tz-aware index, an internal call to `np.diff(index)` returns an array of `Timedelta` objects instead of an array of nanosecond ints, throwing an error immediately after. The error only happens when using pandas>=1.0.0; using 0.25.3 runs successfully, but emits the warning: ``` /home/kevin/anaconda3/envs/pvlib-dev/lib/python3.7/site-packages/numpy/lib/function_base.py:1243: FutureWarning: Converting timezone-aware DatetimeArray to timezone-naive ndarray with 'datetime64[ns]' dtype. In the future, this will return an ndarray with 'object' dtype where each element is a 'pandas.Timestamp' with the correct 'tz'. To accept the future behavior, pass 'dtype=object'. To keep the old behavior, pass 'dtype="datetime64[ns]"'. a = asanyarray(a) ``` **To Reproduce** ```python In [1]: import pvlib ...: import pandas as pd ...: ...: index_naive = pd.date_range('2019-01-01', freq='h', periods=3) ...: ...: kwargs = { ...: 'poa_global': pd.Series(1000, index_naive), ...: 'temp_air': pd.Series(20, index_naive), ...: 'wind_speed': pd.Series(1, index_naive), ...: 'noct_installed': 45 ...: } ...: In [2]: print(pvlib.temperature.fuentes(**kwargs)) 2019-01-01 00:00:00 47.85 2019-01-01 01:00:00 50.85 2019-01-01 02:00:00 50.85 Freq: H, Name: tmod, dtype: float64 In [3]: kwargs['poa_global'].index = index_naive.tz_localize('UTC') ...: print(pvlib.temperature.fuentes(**kwargs)) ...: Traceback (most recent call last): File "<ipython-input-3-ff99badadc91>", line 2, in <module> print(pvlib.temperature.fuentes(**kwargs)) File "/home/kevin/anaconda3/lib/python3.7/site-packages/pvlib/temperature.py", line 602, in fuentes timedelta_hours = np.diff(poa_global.index).astype(float) / 1e9 / 60 / 60 TypeError: float() argument must be a string or a number, not 'Timedelta' ``` **Expected behavior** `temperature.fuentes` should work with both tz-naive and tz-aware inputs. **Versions:** - ``pvlib.__version__``: 0.8.0 - ``pandas.__version__``: 1.0.0+ - python: 3.7.4 (default, Aug 13 2019, 20:35:49) \n[GCC 7.3.0]
2020-10-01T00:53:14Z
0.7
["pvlib/tests/test_temperature.py::test_fuentes_timezone[Etc/GMT+5]"]
["pvlib/tests/test_temperature.py::test_sapm_cell", "pvlib/tests/test_temperature.py::test_sapm_module", "pvlib/tests/test_temperature.py::test_sapm_cell_from_module", "pvlib/tests/test_temperature.py::test_sapm_ndarray", "pvlib/tests/test_temperature.py::test_sapm_series", "pvlib/tests/test_temperature.py::test_pvsyst_cell_default", "pvlib/tests/test_temperature.py::test_pvsyst_cell_kwargs", "pvlib/tests/test_temperature.py::test_pvsyst_cell_ndarray", "pvlib/tests/test_temperature.py::test_pvsyst_cell_series", "pvlib/tests/test_temperature.py::test_faiman_default", "pvlib/tests/test_temperature.py::test_faiman_kwargs", "pvlib/tests/test_temperature.py::test_faiman_list", "pvlib/tests/test_temperature.py::test_faiman_ndarray", "pvlib/tests/test_temperature.py::test_faiman_series", "pvlib/tests/test_temperature.py::test__temperature_model_params", "pvlib/tests/test_temperature.py::test_fuentes[pvwatts_8760_rackmount.csv-45]", "pvlib/tests/test_temperature.py::test_fuentes[pvwatts_8760_roofmount.csv-49]", "pvlib/tests/test_temperature.py::test_fuentes_timezone[None]"]
6e5148f59c5050e8f7a0084b7ae39e93b80f72e6
pvlib/pvlib-python
pvlib__pvlib-python-1606
c78b50f4337ecbe536a961336ca91a1176efc0e8
diff --git a/pvlib/tools.py b/pvlib/tools.py --- a/pvlib/tools.py +++ b/pvlib/tools.py @@ -341,6 +341,8 @@ def _golden_sect_DataFrame(params, lower, upper, func, atol=1e-8): -------- pvlib.singlediode._pwr_optfcn """ + if np.any(upper - lower < 0.): + raise ValueError('upper >= lower is required') phim1 = (np.sqrt(5) - 1) / 2 @@ -349,16 +351,8 @@ def _golden_sect_DataFrame(params, lower, upper, func, atol=1e-8): df['VL'] = lower converged = False - iterations = 0 - # handle all NaN case gracefully - with warnings.catch_warnings(): - warnings.filterwarnings(action='ignore', - message='All-NaN slice encountered') - iterlimit = 1 + np.nanmax( - np.trunc(np.log(atol / (df['VH'] - df['VL'])) / np.log(phim1))) - - while not converged and (iterations <= iterlimit): + while not converged: phi = phim1 * (df['VH'] - df['VL']) df['V1'] = df['VL'] + phi @@ -373,22 +367,16 @@ def _golden_sect_DataFrame(params, lower, upper, func, atol=1e-8): err = abs(df['V2'] - df['V1']) - # works with single value because err is np.float64 - converged = (err[~np.isnan(err)] < atol).all() - # err will be less than atol before iterations hit the limit - # but just to be safe - iterations += 1 - - if iterations > iterlimit: - raise Exception("Iterations exceeded maximum. Check that func", - " is not NaN in (lower, upper)") # pragma: no cover + # handle all NaN case gracefully + with warnings.catch_warnings(): + warnings.filterwarnings(action='ignore', + message='All-NaN slice encountered') + converged = np.all(err[~np.isnan(err)] < atol) - try: - func_result = func(df, 'V1') - x = np.where(np.isnan(func_result), np.nan, df['V1']) - except KeyError: - func_result = np.full_like(upper, np.nan) - x = func_result.copy() + # best estimate of location of maximum + df['max'] = 0.5 * (df['V1'] + df['V2']) + func_result = func(df, 'max') + x = np.where(np.isnan(func_result), np.nan, df['max']) return func_result, x
diff --git a/pvlib/tests/test_tools.py b/pvlib/tests/test_tools.py --- a/pvlib/tests/test_tools.py +++ b/pvlib/tests/test_tools.py @@ -45,6 +45,22 @@ def test__golden_sect_DataFrame_vector(): v, x = tools._golden_sect_DataFrame(params, lower, upper, _obj_test_golden_sect) assert np.allclose(x, expected, atol=1e-8) + # some upper and lower bounds equal + params = {'c': np.array([1., 2., 1.]), 'n': np.array([1., 1., 1.])} + lower = np.array([0., 0.001, 1.]) + upper = np.array([1., 1.2, 1.]) + expected = np.array([0.5, 0.25, 1.0]) # x values for maxima + v, x = tools._golden_sect_DataFrame(params, lower, upper, + _obj_test_golden_sect) + assert np.allclose(x, expected, atol=1e-8) + # all upper and lower bounds equal, arrays of length 1 + params = {'c': np.array([1.]), 'n': np.array([1.])} + lower = np.array([1.]) + upper = np.array([1.]) + expected = np.array([1.]) # x values for maxima + v, x = tools._golden_sect_DataFrame(params, lower, upper, + _obj_test_golden_sect) + assert np.allclose(x, expected, atol=1e-8) def test__golden_sect_DataFrame_nans():
golden-section search fails when upper and lower bounds are equal **Describe the bug** I was using pvlib for sometime now and until now I was always passing a big dataframe containing readings of a long period. Because of some changes in our software architecture, I need to pass the weather readings as a single reading (a dataframe with only one row) and I noticed that for readings that GHI-DHI are zero pvlib fails to calculate the output and returns below error while the same code executes correctly with weather information that has non-zero GHI-DHI: ```python import os import pathlib import time import json from datetime import datetime from time import mktime, gmtime import pandas as pd from pvlib import pvsystem from pvlib import location as pvlocation from pvlib import modelchain from pvlib.temperature import TEMPERATURE_MODEL_PARAMETERS as PARAMS # not used -- to remove from pvlib.bifacial.pvfactors import pvfactors_timeseries from pvlib.temperature import TEMPERATURE_MODEL_PARAMETERS class PV: def pv_transform_time(self, val): # tt = gmtime(val / 1000) tt = gmtime(val) dd = datetime.fromtimestamp(mktime(tt)) timestamp = pd.Timestamp(dd) return timestamp def __init__(self, model: str, inverter: str, latitude: float, longitude: float, **kwargs): # super().__init__(**kwargs) temperature_model_parameters = TEMPERATURE_MODEL_PARAMETERS["sapm"][ "open_rack_glass_glass" ] # Load the database of CEC module model parameters modules = pvsystem.retrieve_sam("cecmod") # Load the database of CEC inverter model parameters inverters = pvsystem.retrieve_sam("cecinverter") # A bare bone PV simulator # Load the database of CEC module model parameters modules = pvsystem.retrieve_sam('cecmod') inverters = pvsystem.retrieve_sam('cecinverter') module_parameters = modules[model] inverter_parameters = inverters[inverter] location = pvlocation.Location(latitude=latitude, longitude=longitude) system = pvsystem.PVSystem(module_parameters=module_parameters, inverter_parameters=inverter_parameters, temperature_model_parameters=temperature_model_parameters) self.modelchain = modelchain.ModelChain(system, location, aoi_model='no_loss', spectral_model="no_loss") def process(self, data): weather = pd.read_json(data) # print(f"raw_weather: {weather}") weather.drop('time.1', axis=1, inplace=True) weather['time'] = pd.to_datetime(weather['time']).map(datetime.timestamp) # --> this works for the new process_weather code and also the old weather file weather["time"] = weather["time"].apply(self.pv_transform_time) weather.index = weather["time"] # print(f"weather: {weather}") # print(weather.dtypes) # print(weather['ghi'][0]) # print(type(weather['ghi'][0])) # simulate self.modelchain.run_model(weather) # print(self.modelchain.results.ac.to_frame().to_json()) print(self.modelchain.results.ac) # good data good_data = "{\"time\":{\"12\":\"2010-01-01 13:30:00+00:00\"},\"ghi\":{\"12\":36},\"dhi\":{\"12\":36},\"dni\":{\"12\":0},\"Tamb\":{\"12\":8.0},\"WindVel\":{\"12\":5.0},\"WindDir\":{\"12\":270},\"time.1\":{\"12\":\"2010-01-01 13:30:00+00:00\"}}" # data that causes error data = "{\"time\":{\"4\":\"2010-01-01 05:30:00+00:00\"},\"ghi\":{\"4\":0},\"dhi\":{\"4\":0},\"dni\":{\"4\":0},\"Tamb\":{\"4\":8.0},\"WindVel\":{\"4\":4.0},\"WindDir\":{\"4\":240},\"time.1\":{\"4\":\"2010-01-01 05:30:00+00:00\"}}" p1 = PV(model="Trina_Solar_TSM_300DEG5C_07_II_", inverter="ABB__MICRO_0_25_I_OUTD_US_208__208V_", latitude=51.204483, longitude=5.265472) p1.process(good_data) print("=====") p1.process(data) ``` Error: ```log $ python3 ./tmp-pv.py time 2010-01-01 13:30:00 7.825527 dtype: float64 ===== /home/user/.local/lib/python3.10/site-packages/pvlib/tools.py:340: RuntimeWarning: divide by zero encountered in divide np.trunc(np.log(atol / (df['VH'] - df['VL'])) / np.log(phim1))) Traceback (most recent call last): File "/home/user/workspace/enorch/simulator/simulator_processor/src/pv/./tmp-pv.py", line 88, in <module> p1.process(data) File "/home/user/workspace/enorch/simulator/simulator_processor/src/pv/./tmp-pv.py", line 75, in process self.modelchain.run_model(weather) File "/home/user/.local/lib/python3.10/site-packages/pvlib/modelchain.py", line 1770, in run_model self._run_from_effective_irrad(weather) File "/home/user/.local/lib/python3.10/site-packages/pvlib/modelchain.py", line 1858, in _run_from_effective_irrad self.dc_model() File "/home/user/.local/lib/python3.10/site-packages/pvlib/modelchain.py", line 790, in cec return self._singlediode(self.system.calcparams_cec) File "/home/user/.local/lib/python3.10/site-packages/pvlib/modelchain.py", line 772, in _singlediode self.results.dc = tuple(itertools.starmap( File "/home/user/.local/lib/python3.10/site-packages/pvlib/pvsystem.py", line 931, in singlediode return singlediode(photocurrent, saturation_current, File "/home/user/.local/lib/python3.10/site-packages/pvlib/pvsystem.py", line 2826, in singlediode out = _singlediode._lambertw( File "/home/user/.local/lib/python3.10/site-packages/pvlib/singlediode.py", line 651, in _lambertw p_mp, v_mp = _golden_sect_DataFrame(params, 0., v_oc * 1.14, File "/home/user/.local/lib/python3.10/site-packages/pvlib/tools.py", line 364, in _golden_sect_DataFrame raise Exception("Iterations exceeded maximum. Check that func", Exception: ('Iterations exceeded maximum. Check that func', ' is not NaN in (lower, upper)') ``` I have to mention that for now the workaround that I am using is to pass the weather data as a dataframe with two rows, the first row is a good weather data that pvlib can process and the second row is the incoming weather reading (I can also post that code if you want). **Expected behavior** PVlib should have consistent behavior and regardless of GHI-DHI readings. **Versions:** ```python >>> import pvlib >>> import pandas >>> pvlib.__version__ '0.9.1' >>> pandas.__version__ '1.4.3' ``` - python: 3.10.6 - OS: Ubuntu 22.04.1 LTS
Confirmed. This appears to be an oversight in `pvlib.tools._golden_section_DataFrame` involving error messaging, likely introduced with #1089 . In this code when processing the content of `data`, photocurrent is 0., hence the shunt resistance is infinite and v_oc is 0. That sets the range for the golden section search to be [0., 0.]. [iterlimit](https://github.com/pvlib/pvlib-python/blob/582b956c63c463e5178fbb7a88fa545fa5b1c257/pvlib/tools.py#L358) is then -infinity, which skips the loop (`iterations <= iterlimit`) but since `iterations > iterlimit` raises the "Iterations exceeded..." exception.
2022-12-07T21:12:08Z
0.8
["pvlib/tests/test_tools.py::test__golden_sect_DataFrame_vector"]
["pvlib/tests/test_tools.py::test_build_kwargs[keys0-input_dict0-expected0]", "pvlib/tests/test_tools.py::test_build_kwargs[keys1-input_dict1-expected1]", "pvlib/tests/test_tools.py::test_build_kwargs[keys2-input_dict2-expected2]", "pvlib/tests/test_tools.py::test_build_kwargs[keys3-input_dict3-expected3]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params0-0.0-1.0-0.5-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params1-0.0-1.0-0.07230200263994839-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params2-0.0-100.0-89.14332727531685-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_atol", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_nans", "pvlib/tests/test_tools.py::test_degrees_to_index_1"]
ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91
pvlib/pvlib-python
pvlib__pvlib-python-1854
27a3a07ebc84b11014d3753e4923902adf9a38c0
diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py --- a/pvlib/pvsystem.py +++ b/pvlib/pvsystem.py @@ -101,10 +101,11 @@ class PVSystem: Parameters ---------- - arrays : iterable of Array, optional - List of arrays that are part of the system. If not specified - a single array is created from the other parameters (e.g. - `surface_tilt`, `surface_azimuth`). Must contain at least one Array, + arrays : Array or iterable of Array, optional + An Array or list of arrays that are part of the system. If not + specified a single array is created from the other parameters (e.g. + `surface_tilt`, `surface_azimuth`). If specified as a list, the list + must contain at least one Array; if length of arrays is 0 a ValueError is raised. If `arrays` is specified the following PVSystem parameters are ignored: @@ -220,6 +221,8 @@ def __init__(self, strings_per_inverter, array_losses_parameters, ),) + elif isinstance(arrays, Array): + self.arrays = (arrays,) elif len(arrays) == 0: raise ValueError("PVSystem must have at least one Array. " "If you want to create a PVSystem instance "
diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py --- a/pvlib/tests/test_pvsystem.py +++ b/pvlib/tests/test_pvsystem.py @@ -1887,8 +1887,6 @@ def test_PVSystem_multiple_array_creation(): assert pv_system.arrays[0].module_parameters == {} assert pv_system.arrays[1].module_parameters == {'pdc0': 1} assert pv_system.arrays == (array_one, array_two) - with pytest.raises(TypeError): - pvsystem.PVSystem(arrays=array_one) def test_PVSystem_get_aoi(): @@ -2362,6 +2360,14 @@ def test_PVSystem_at_least_one_array(): pvsystem.PVSystem(arrays=[]) +def test_PVSystem_single_array(): + # GH 1831 + single_array = pvsystem.Array(pvsystem.FixedMount()) + system = pvsystem.PVSystem(arrays=single_array) + assert isinstance(system.arrays, tuple) + assert system.arrays[0] is single_array + + def test_combine_loss_factors(): test_index = pd.date_range(start='1990/01/01T12:00', periods=365, freq='D') loss_1 = pd.Series(.10, index=test_index)
PVSystem with single Array generates an error **Is your feature request related to a problem? Please describe.** When a PVSystem has a single Array, you can't assign just the Array instance when constructing the PVSystem. ``` mount = pvlib.pvsystem.FixedMount(surface_tilt=35, surface_azimuth=180) array = pvlib.pvsystem.Array(mount=mount) pv = pvlib.pvsystem.PVSystem(arrays=array) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-13-f5424e3db16a> in <module> 3 mount = pvlib.pvsystem.FixedMount(surface_tilt=35, surface_azimuth=180) 4 array = pvlib.pvsystem.Array(mount=mount) ----> 5 pv = pvlib.pvsystem.PVSystem(arrays=array) ~\anaconda3\lib\site-packages\pvlib\pvsystem.py in __init__(self, arrays, surface_tilt, surface_azimuth, albedo, surface_type, module, module_type, module_parameters, temperature_model_parameters, modules_per_string, strings_per_inverter, inverter, inverter_parameters, racking_model, losses_parameters, name) 251 array_losses_parameters, 252 ),) --> 253 elif len(arrays) == 0: 254 raise ValueError("PVSystem must have at least one Array. " 255 "If you want to create a PVSystem instance " TypeError: object of type 'Array' has no len() ``` Not a bug per se, since the PVSystem docstring requests that `arrays` be iterable. Still, a bit inconvenient to have to do this ``` mount = pvlib.pvsystem.FixedMount(surface_tilt=35, surface_azimuth=180) array = pvlib.pvsystem.Array(mount=mount) pv = pvlib.pvsystem.PVSystem(arrays=[array]) ``` **Describe the solution you'd like** Handle `arrays=array` where `array` is an instance of `Array` **Describe alternatives you've considered** Status quo - either make the single Array into a list, or use the PVSystem kwargs.
2023-09-13T17:25:47Z
0.9
["pvlib/tests/test_pvsystem.py::test_PVSystem_single_array"]
["pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss_deprecated", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_recombination", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[lambertw]", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[brentq]", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[newton]", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_Array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]"]
6072e0982c3c0236f532ddfa48fbf461180d834e
pvlib/pvlib-python
pvlib__pvlib-python-1154
0b8f24c265d76320067a5ee908a57d475cd1bb24
diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py --- a/pvlib/irradiance.py +++ b/pvlib/irradiance.py @@ -886,8 +886,9 @@ def reindl(surface_tilt, surface_azimuth, dhi, dni, ghi, dni_extra, # these are the () and [] sub-terms of the second term of eqn 8 term1 = 1 - AI term2 = 0.5 * (1 + tools.cosd(surface_tilt)) - term3 = 1 + np.sqrt(HB / ghi) * (tools.sind(0.5 * surface_tilt) ** 3) - + with np.errstate(invalid='ignore', divide='ignore'): + hb_to_ghi = np.where(ghi == 0, 0, np.divide(HB, ghi)) + term3 = 1 + np.sqrt(hb_to_ghi) * (tools.sind(0.5 * surface_tilt)**3) sky_diffuse = dhi * (AI * Rb + term1 * term2 * term3) sky_diffuse = np.maximum(sky_diffuse, 0)
diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py --- a/pvlib/tests/test_irradiance.py +++ b/pvlib/tests/test_irradiance.py @@ -203,7 +203,7 @@ def test_reindl(irrad_data, ephem_data, dni_et): 40, 180, irrad_data['dhi'], irrad_data['dni'], irrad_data['ghi'], dni_et, ephem_data['apparent_zenith'], ephem_data['azimuth']) # values from matlab 1.4 code - assert_allclose(result, [np.nan, 27.9412, 104.1317, 34.1663], atol=1e-4) + assert_allclose(result, [0., 27.9412, 104.1317, 34.1663], atol=1e-4) def test_king(irrad_data, ephem_data):
pvlib.irradiance.reindl() model generates NaNs when GHI = 0 **Describe the bug** The reindl function should give zero sky diffuse when GHI is zero. Instead it generates NaN or Inf values due to "term3" having a quotient that divides by GHI. **Expected behavior** The reindl function should result in zero sky diffuse when GHI is zero. pvlib.irradiance.reindl() model generates NaNs when GHI = 0 **Describe the bug** The reindl function should give zero sky diffuse when GHI is zero. Instead it generates NaN or Inf values due to "term3" having a quotient that divides by GHI. **Expected behavior** The reindl function should result in zero sky diffuse when GHI is zero.
Verified. Looks like an easy fix. Verified. Looks like an easy fix.
2021-01-29T20:53:24Z
0.8
["pvlib/tests/test_irradiance.py::test_reindl"]
["pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_float", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_invalid", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_gti_dirint", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent"]
ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91
pylint-dev/astroid
pylint-dev__astroid-1978
0c9ab0fe56703fa83c73e514a1020d398d23fa7f
diff --git a/astroid/raw_building.py b/astroid/raw_building.py --- a/astroid/raw_building.py +++ b/astroid/raw_building.py @@ -10,11 +10,14 @@ import builtins import inspect +import io +import logging import os import sys import types import warnings from collections.abc import Iterable +from contextlib import redirect_stderr, redirect_stdout from typing import Any, Union from astroid import bases, nodes @@ -22,6 +25,9 @@ from astroid.manager import AstroidManager from astroid.nodes import node_classes +logger = logging.getLogger(__name__) + + _FunctionTypes = Union[ types.FunctionType, types.MethodType, @@ -471,7 +477,26 @@ def imported_member(self, node, member, name: str) -> bool: # check if it sounds valid and then add an import node, else use a # dummy node try: - getattr(sys.modules[modname], name) + with redirect_stderr(io.StringIO()) as stderr, redirect_stdout( + io.StringIO() + ) as stdout: + getattr(sys.modules[modname], name) + stderr_value = stderr.getvalue() + if stderr_value: + logger.error( + "Captured stderr while getting %s from %s:\n%s", + name, + sys.modules[modname], + stderr_value, + ) + stdout_value = stdout.getvalue() + if stdout_value: + logger.info( + "Captured stdout while getting %s from %s:\n%s", + name, + sys.modules[modname], + stdout_value, + ) except (KeyError, AttributeError): attach_dummy_node(node, name, member) else:
diff --git a/tests/unittest_raw_building.py b/tests/unittest_raw_building.py --- a/tests/unittest_raw_building.py +++ b/tests/unittest_raw_building.py @@ -8,8 +8,15 @@ # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt +from __future__ import annotations + +import logging +import os +import sys import types import unittest +from typing import Any +from unittest import mock import _io import pytest @@ -117,5 +124,45 @@ def test_module_object_with_broken_getattr(self) -> None: AstroidBuilder().inspect_build(fm_getattr, "test") [email protected]( + "posix" not in sys.builtin_module_names, reason="Platform doesn't support posix" +) +def test_build_module_getattr_catch_output( + capsys: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, +) -> None: + """Catch stdout and stderr in module __getattr__ calls when building a module. + + Usually raised by DeprecationWarning or FutureWarning. + """ + caplog.set_level(logging.INFO) + original_sys = sys.modules + original_module = sys.modules["posix"] + expected_out = "INFO (TEST): Welcome to posix!" + expected_err = "WARNING (TEST): Monkey-patched version of posix - module getattr" + + class CustomGetattr: + def __getattr__(self, name: str) -> Any: + print(f"{expected_out}") + print(expected_err, file=sys.stderr) + return getattr(original_module, name) + + def mocked_sys_modules_getitem(name: str) -> types.ModuleType | CustomGetattr: + if name != "posix": + return original_sys[name] + return CustomGetattr() + + with mock.patch("astroid.raw_building.sys.modules") as sys_mock: + sys_mock.__getitem__.side_effect = mocked_sys_modules_getitem + builder = AstroidBuilder() + builder.inspect_build(os) + + out, err = capsys.readouterr() + assert expected_out in caplog.text + assert expected_err in caplog.text + assert not out + assert not err + + if __name__ == "__main__": unittest.main()
Deprecation warnings from numpy ### Steps to reproduce 1. Run pylint over the following test case: ``` """Test case""" import numpy as np value = np.random.seed(1234) ``` ### Current behavior ``` /home/bje/source/nemo/myenv/lib/python3.10/site-packages/astroid/raw_building.py:470: FutureWarning: In the future `np.long` will be defined as the corresponding NumPy scalar. (This may have returned Python scalars in past versions. getattr(sys.modules[modname], name) /home/bje/source/nemo/myenv/lib/python3.10/site-packages/astroid/raw_building.py:470: FutureWarning: In the future `np.long` will be defined as the corresponding NumPy scalar. (This may have returned Python scalars in past versions. getattr(sys.modules[modname], name) ``` ### Expected behavior There should be no future warnings. ### python -c "from astroid import __pkginfo__; print(__pkginfo__.version)" output 2.12.13
This seems very similar to https://github.com/PyCQA/astroid/pull/1514 that was fixed in 2.12.0. I'm running 2.12.13 (> 2.12.0), so the fix isn't working in this case? I don't know why #1514 did not fix this, I think we were capturing both stdout and stderr, so this will need some investigation. My guess would be that there's somewhere else to apply the same method to. Hello, I see the same error with pylint on our tool [demcompare](https://github.com/CNES/demcompare). Pylint version: ``` pylint --version pylint 2.15.9 astroid 2.12.13 Python 3.8.10 (default, Nov 14 2022, 12:59:47) [GCC 9.4.0] ``` I confirm the weird astroid lower warning and I don't know how to bypass it with pylint checking. ``` pylint demcompare /home/duboise/work/src/demcompare/venv/lib/python3.8/site-packages/astroid/raw_building.py:470: FutureWarning: In the future `np.long` will be defined as the corresponding NumPy scalar. (This may have returned Python scalars in past versions. getattr(sys.modules[modname], name) ... (four times) ``` Thanks in advance if there is a solution Cordially > Thanks in advance if there is a solution while annoying the warning does not make pylint fail. Just ignore it. In a CI you can just check pylint return code. It will return 0 as expected I agree, even if annoying because it feels our code as a problem somewhere, the CI with pylint doesn't fail indeed. Thanks for the answer that confirm to not bother for now. That might be fine in a CI environment, but for users, ultimately, ignoring warnings becomes difficult when there are too many such warnings. I would like to see this fixed. Oh, it was not an argument in favour of not fixing it. It was just to point out that it is not a breaking problem. It is "just" a lot of quite annoying warnings. I am following the issue because it annoys me too. So I am in the same "I hope they will fix it" boat > I don't know why https://github.com/PyCQA/astroid/pull/1514 did not fix this, I think we were capturing both stdout and stderr, so this will need some investigation. My guess would be that there's somewhere else to apply the same method to. That PR only addressed import-time. This `FutureWarning` is emitted by numpy's package-level `__getattr__` method, not during import.
2023-01-28T06:14:39Z
2.14
["tests/unittest_raw_building.py::test_build_module_getattr_catch_output"]
["tests/unittest_raw_building.py::RawBuildingTC::test_attach_dummy_node", "tests/unittest_raw_building.py::RawBuildingTC::test_build_class", "tests/unittest_raw_building.py::RawBuildingTC::test_build_from_import", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_args", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_deepinspect_deprecation", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_defaults", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_kwonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_posonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_module", "tests/unittest_raw_building.py::RawBuildingTC::test_io_is__io", "tests/unittest_raw_building.py::RawBuildingTC::test_module_object_with_broken_getattr"]
0c9ab0fe56703fa83c73e514a1020d398d23fa7f
pylint-dev/astroid
pylint-dev__astroid-1333
d2a5b3c7b1e203fec3c7ca73c30eb1785d3d4d0a
diff --git a/astroid/modutils.py b/astroid/modutils.py --- a/astroid/modutils.py +++ b/astroid/modutils.py @@ -297,6 +297,9 @@ def _get_relative_base_path(filename, path_to_check): if os.path.normcase(real_filename).startswith(path_to_check): importable_path = real_filename + # if "var" in path_to_check: + # breakpoint() + if importable_path: base_path = os.path.splitext(importable_path)[0] relative_base_path = base_path[len(path_to_check) :] @@ -307,8 +310,11 @@ def _get_relative_base_path(filename, path_to_check): def modpath_from_file_with_callback(filename, path=None, is_package_cb=None): filename = os.path.expanduser(_path_from_filename(filename)) + paths_to_check = sys.path.copy() + if path: + paths_to_check += path for pathname in itertools.chain( - path or [], map(_cache_normalize_path, sys.path), sys.path + paths_to_check, map(_cache_normalize_path, paths_to_check) ): if not pathname: continue
diff --git a/tests/unittest_modutils.py b/tests/unittest_modutils.py --- a/tests/unittest_modutils.py +++ b/tests/unittest_modutils.py @@ -30,6 +30,7 @@ import tempfile import unittest import xml +from pathlib import Path from xml import etree from xml.etree import ElementTree @@ -189,6 +190,30 @@ def test_load_from_module_symlink_on_symlinked_paths_in_syspath(self) -> None: # this should be equivalent to: import secret self.assertEqual(modutils.modpath_from_file(symlink_secret_path), ["secret"]) + def test_load_packages_without_init(self) -> None: + """Test that we correctly find packages with an __init__.py file. + + Regression test for issue reported in: + https://github.com/PyCQA/astroid/issues/1327 + """ + tmp_dir = Path(tempfile.gettempdir()) + self.addCleanup(os.chdir, os.curdir) + os.chdir(tmp_dir) + + self.addCleanup(shutil.rmtree, tmp_dir / "src") + os.mkdir(tmp_dir / "src") + os.mkdir(tmp_dir / "src" / "package") + with open(tmp_dir / "src" / "__init__.py", "w", encoding="utf-8"): + pass + with open(tmp_dir / "src" / "package" / "file.py", "w", encoding="utf-8"): + pass + + # this should be equivalent to: import secret + self.assertEqual( + modutils.modpath_from_file(str(Path("src") / "package"), ["."]), + ["src", "package"], + ) + class LoadModuleFromPathTest(resources.SysPathSetup, unittest.TestCase): def test_do_not_load_twice(self) -> None:
astroid 2.9.1 breaks pylint with missing __init__.py: F0010: error while code parsing: Unable to load file __init__.py ### Steps to reproduce > Steps provided are for Windows 11, but initial problem found in Ubuntu 20.04 > Update 2022-01-04: Corrected repro steps and added more environment details 1. Set up simple repo with following structure (all files can be empty): ``` root_dir/ |--src/ |----project/ # Notice the missing __init__.py |------file.py # It can be empty, but I added `import os` at the top |----__init__.py ``` 2. Open a command prompt 3. `cd root_dir` 4. `python -m venv venv` 5. `venv/Scripts/activate` 6. `pip install pylint astroid==2.9.1` # I also repro'd on the latest, 2.9.2 7. `pylint src/project` # Updated from `pylint src` 8. Observe failure: ``` src\project\__init__.py:1:0: F0010: error while code parsing: Unable to load file src\project\__init__.py: ``` ### Current behavior Fails with `src\project\__init__.py:1:0: F0010: error while code parsing: Unable to load file src\project\__init__.py:` ### Expected behavior Does not fail with error. > If you replace step 6 with `pip install pylint astroid==2.9.0`, you get no failure with an empty output - since no files have content ### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output 2.9.1 `python 3.9.1` `pylint 2.12.2 ` This issue has been observed with astroid `2.9.1` and `2.9.2`
I can't seem to reproduce this in my `virtualenv`. This might be specific to `venv`? Needs some further investigation. @interifter Which version of `pylint` are you using? Right, ``pip install pylint astroid==2.9.0``, will keep the local version if you already have one, so I thought it was ``2.12.2`` but that could be false. In fact it probably isn't 2.12.2. For the record, you're not supposed to set the version of ``astroid`` yourself, pylint does, and bad thing will happen if you try to set the version of an incompatible astroid. We might want to update the issue's template to have this information next. My apologies... I updated the repro steps with a critical missed detail: `pylint src/project`, instead of `pylint src` But I verified that either with, or without, `venv`, the issue is reproduced. Also, I never have specified the `astroid` version, before. However, this isn't the first time the issue has been observed. Back in early 2019, a [similar issue](https://stackoverflow.com/questions/48024049/pylint-raises-error-if-directory-doesnt-contain-init-py-file) was observed with either `astroid 2.2.0` or `isort 4.3.5`, which led me to try pinning `astroid==2.9.0`, which worked. > @interifter Which version of `pylint` are you using? `2.12.2` Full env info: ``` Package Version ----------------- ------- astroid 2.9.2 colorama 0.4.4 isort 5.10.1 lazy-object-proxy 1.7.1 mccabe 0.6.1 pip 20.2.3 platformdirs 2.4.1 pylint 2.12.2 setuptools 49.2.1 toml 0.10.2 typing-extensions 4.0.1 wrapt 1.13.3 ``` I confirm the bug and i'm able to reproduce it with `python 3.9.1`. ``` $> pip freeze astroid==2.9.2 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.6.1 platformdirs==2.4.1 pylint==2.12.2 toml==0.10.2 typing-extensions==4.0.1 wrapt==1.13.3 ``` Bisected and this is the faulty commit: https://github.com/PyCQA/astroid/commit/2ee20ccdf62450db611acc4a1a7e42f407ce8a14 Fix in #1333, no time to write tests yet so if somebody has any good ideas: please let me know!
2022-01-08T19:36:45Z
2.10
["tests/unittest_modutils.py::ModPathFromFileTest::test_load_packages_without_init"]
["tests/unittest_modutils.py::ModuleFileTest::test_find_egg_module", "tests/unittest_modutils.py::ModuleFileTest::test_find_zipped_module", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_known_values_load_module_from_name_1", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_known_values_load_module_from_name_2", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_raise_load_module_from_name_1", "tests/unittest_modutils.py::GetModulePartTest::test_get_module_part_exception", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_builtin_module_part", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_compiled_module_part", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_module_part_1", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_module_part_2", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_module_part_3", "tests/unittest_modutils.py::ModPathFromFileTest::test_import_symlink_both_outside_of_path", "tests/unittest_modutils.py::ModPathFromFileTest::test_import_symlink_with_source_outside_of_path", "tests/unittest_modutils.py::ModPathFromFileTest::test_known_values_modpath_from_file_1", "tests/unittest_modutils.py::ModPathFromFileTest::test_load_from_module_symlink_on_symlinked_paths_in_syspath", "tests/unittest_modutils.py::ModPathFromFileTest::test_raise_modpath_from_file_exception", "tests/unittest_modutils.py::LoadModuleFromPathTest::test_do_not_load_twice", "tests/unittest_modutils.py::FileFromModPathTest::test_builtin", "tests/unittest_modutils.py::FileFromModPathTest::test_site_packages", "tests/unittest_modutils.py::FileFromModPathTest::test_std_lib", "tests/unittest_modutils.py::FileFromModPathTest::test_unexisting", "tests/unittest_modutils.py::FileFromModPathTest::test_unicode_in_package_init", "tests/unittest_modutils.py::GetSourceFileTest::test", "tests/unittest_modutils.py::GetSourceFileTest::test_raise", "tests/unittest_modutils.py::StandardLibModuleTest::test_4", "tests/unittest_modutils.py::StandardLibModuleTest::test_builtin", "tests/unittest_modutils.py::StandardLibModuleTest::test_builtins", "tests/unittest_modutils.py::StandardLibModuleTest::test_custom_path", "tests/unittest_modutils.py::StandardLibModuleTest::test_datetime", "tests/unittest_modutils.py::StandardLibModuleTest::test_failing_edge_cases", "tests/unittest_modutils.py::StandardLibModuleTest::test_nonstandard", "tests/unittest_modutils.py::StandardLibModuleTest::test_unknown", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative2", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative3", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative4", "tests/unittest_modutils.py::IsRelativeTest::test_is_relative_bad_path", "tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_1", "tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_3", "tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_4", "tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_5", "tests/unittest_modutils.py::GetModuleFilesTest::test_get_all_files", "tests/unittest_modutils.py::GetModuleFilesTest::test_get_module_files_1", "tests/unittest_modutils.py::GetModuleFilesTest::test_load_module_set_attribute", "tests/unittest_modutils.py::ExtensionPackageWhitelistTest::test_is_module_name_part_of_extension_package_whitelist_success", "tests/unittest_modutils.py::ExtensionPackageWhitelistTest::test_is_module_name_part_of_extension_package_whitelist_true"]
da745538c7236028a22cdf0405f6829fcf6886bc
pylint-dev/astroid
pylint-dev__astroid-1196
39c2a9805970ca57093d32bbaf0e6a63e05041d8
diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py --- a/astroid/nodes/node_classes.py +++ b/astroid/nodes/node_classes.py @@ -2346,24 +2346,33 @@ def itered(self): """ return [key for (key, _) in self.items] - def getitem(self, index, context=None): + def getitem( + self, index: Const | Slice, context: InferenceContext | None = None + ) -> NodeNG: """Get an item from this node. :param index: The node to use as a subscript index. - :type index: Const or Slice :raises AstroidTypeError: When the given index cannot be used as a subscript index, or if this node is not subscriptable. :raises AstroidIndexError: If the given index does not exist in the dictionary. """ + # pylint: disable-next=import-outside-toplevel; circular import + from astroid.helpers import safe_infer + for key, value in self.items: # TODO(cpopa): no support for overriding yet, {1:2, **{1: 3}}. if isinstance(key, DictUnpack): + inferred_value = safe_infer(value, context) + if not isinstance(inferred_value, Dict): + continue + try: - return value.getitem(index, context) + return inferred_value.getitem(index, context) except (AstroidTypeError, AstroidIndexError): continue + for inferredkey in key.infer(context): if inferredkey is util.Uninferable: continue
diff --git a/tests/unittest_python3.py b/tests/unittest_python3.py --- a/tests/unittest_python3.py +++ b/tests/unittest_python3.py @@ -5,7 +5,9 @@ import unittest from textwrap import dedent -from astroid import nodes +import pytest + +from astroid import exceptions, nodes from astroid.builder import AstroidBuilder, extract_node from astroid.test_utils import require_version @@ -285,6 +287,33 @@ def test_unpacking_in_dict_getitem(self) -> None: self.assertIsInstance(value, nodes.Const) self.assertEqual(value.value, expected) + @staticmethod + def test_unpacking_in_dict_getitem_with_ref() -> None: + node = extract_node( + """ + a = {1: 2} + {**a, 2: 3} #@ + """ + ) + assert isinstance(node, nodes.Dict) + + for key, expected in ((1, 2), (2, 3)): + value = node.getitem(nodes.Const(key)) + assert isinstance(value, nodes.Const) + assert value.value == expected + + @staticmethod + def test_unpacking_in_dict_getitem_uninferable() -> None: + node = extract_node("{**a, 2: 3}") + assert isinstance(node, nodes.Dict) + + with pytest.raises(exceptions.AstroidIndexError): + node.getitem(nodes.Const(1)) + + value = node.getitem(nodes.Const(2)) + assert isinstance(value, nodes.Const) + assert value.value == 3 + def test_format_string(self) -> None: code = "f'{greetings} {person}'" node = extract_node(code)
getitem does not infer the actual unpacked value When trying to call `Dict.getitem()` on a context where we have a dict unpacking of anything beside a real dict, astroid currently raises an `AttributeError: 'getitem'`, which has 2 problems: - The object might be a reference against something constant, this pattern is usually seen when we have different sets of dicts that extend each other, and all of their values are inferrable. - We can have something that is uninferable, but in that case instead of an `AttributeError` I think it makes sense to raise the usual `AstroidIndexError` which is supposed to be already handled by the downstream. Here is a short reproducer; ```py from astroid import parse source = """ X = { 'A': 'B' } Y = { **X } KEY = 'A' """ tree = parse(source) first_dict = tree.body[0].value second_dict = tree.body[1].value key = tree.body[2].value print(f'{first_dict.getitem(key).value = }') print(f'{second_dict.getitem(key).value = }') ``` The current output; ``` $ python t1.py 3ms first_dict.getitem(key).value = 'B' Traceback (most recent call last): File "/home/isidentical/projects/astroid/t1.py", line 23, in <module> print(f'{second_dict.getitem(key).value = }') File "/home/isidentical/projects/astroid/astroid/nodes/node_classes.py", line 2254, in getitem return value.getitem(index, context) AttributeError: 'Name' object has no attribute 'getitem' ``` Expeceted output; ``` $ python t1.py 4ms first_dict.getitem(key).value = 'B' second_dict.getitem(key).value = 'B' ```
2021-10-03T15:58:07Z
2.12
["tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem_uninferable", "tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem_with_ref"]
["tests/unittest_python3.py::Python3TC::test_annotation_as_string", "tests/unittest_python3.py::Python3TC::test_annotation_support", "tests/unittest_python3.py::Python3TC::test_as_string", "tests/unittest_python3.py::Python3TC::test_async_comprehensions", "tests/unittest_python3.py::Python3TC::test_async_comprehensions_as_string", "tests/unittest_python3.py::Python3TC::test_async_comprehensions_outside_coroutine", "tests/unittest_python3.py::Python3TC::test_format_string", "tests/unittest_python3.py::Python3TC::test_kwonlyargs_annotations_supper", "tests/unittest_python3.py::Python3TC::test_metaclass_ancestors", "tests/unittest_python3.py::Python3TC::test_metaclass_error", "tests/unittest_python3.py::Python3TC::test_metaclass_imported", "tests/unittest_python3.py::Python3TC::test_metaclass_multiple_keywords", "tests/unittest_python3.py::Python3TC::test_metaclass_yes_leak", "tests/unittest_python3.py::Python3TC::test_nested_unpacking_in_dicts", "tests/unittest_python3.py::Python3TC::test_old_syntax_works", "tests/unittest_python3.py::Python3TC::test_parent_metaclass", "tests/unittest_python3.py::Python3TC::test_simple_metaclass", "tests/unittest_python3.py::Python3TC::test_starred_notation", "tests/unittest_python3.py::Python3TC::test_underscores_in_numeral_literal", "tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem", "tests/unittest_python3.py::Python3TC::test_unpacking_in_dicts", "tests/unittest_python3.py::Python3TC::test_yield_from", "tests/unittest_python3.py::Python3TC::test_yield_from_as_string", "tests/unittest_python3.py::Python3TC::test_yield_from_is_generator"]
52f6d2d7722db383af035be929f18af5e9fe8cd5
pylint-dev/astroid
pylint-dev__astroid-1866
6cf238d089cf4b6753c94cfc089b4a47487711e5
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py --- a/astroid/brain/brain_builtin_inference.py +++ b/astroid/brain/brain_builtin_inference.py @@ -954,8 +954,10 @@ def _infer_str_format_call( try: formatted_string = format_template.format(*pos_values, **keyword_values) - except (IndexError, KeyError): - # If there is an IndexError there are too few arguments to interpolate + except (IndexError, KeyError, TypeError, ValueError): + # IndexError: there are too few arguments to interpolate + # TypeError: Unsupported format string + # ValueError: Unknown format code return iter([util.Uninferable]) return iter([nodes.const_factory(formatted_string)])
diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py --- a/tests/unittest_brain_builtin.py +++ b/tests/unittest_brain_builtin.py @@ -103,6 +103,12 @@ def test_string_format(self, format_string: str) -> None: """ "My name is {fname}, I'm {age}".format(fsname = "Daniel", age = 12) """, + """ + "My unicode character is {:c}".format(None) + """, + """ + "My hex format is {:4x}".format('1') + """, ], ) def test_string_format_uninferable(self, format_string: str) -> None:
"TypeError: unsupported format string passed to NoneType.__format__" while running type inference in version 2.12.x ### Steps to reproduce I have no concise reproducer. Exception happens every time I run pylint on some internal code, with astroid 2.12.10 and 2.12.12 (debian bookworm). It does _not_ happen with earlier versions of astroid (not with version 2.9). The pylinted code itself is "valid", it runs in production here. ### Current behavior When running pylint on some code, I get this exception: ``` Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pylint/utils/ast_walker.py", line 90, in walk callback(astroid) File "/usr/lib/python3/dist-packages/pylint/checkers/classes/special_methods_checker.py", line 183, in visit_functiondef inferred = _safe_infer_call_result(node, node) File "/usr/lib/python3/dist-packages/pylint/checkers/classes/special_methods_checker.py", line 42, in _safe_infer_call_result value = next(inferit) File "/usr/lib/python3/dist-packages/astroid/nodes/scoped_nodes/scoped_nodes.py", line 1749, in infer_call_result yield from returnnode.value.infer(context) File "/usr/lib/python3/dist-packages/astroid/nodes/node_ng.py", line 159, in infer results = list(self._explicit_inference(self, context, **kwargs)) File "/usr/lib/python3/dist-packages/astroid/inference_tip.py", line 45, in _inference_tip_cached result = _cache[func, node] = list(func(*args, **kwargs)) File "/usr/lib/python3/dist-packages/astroid/brain/brain_builtin_inference.py", line 956, in _infer_str_format_call formatted_string = format_template.format(*pos_values, **keyword_values) TypeError: unsupported format string passed to NoneType.__format__ ``` ### Expected behavior TypeError exception should not happen ### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output 2.12.10, 2.12.12
Hi @crosser, thanks for the report. > I have no concise reproducer. We might be able to help you distill one. `pylint` produces a crash report, and shows the link in your terminal, like this: ```shell ************* Module a a.py:1:0: F0002: a.py: Fatal error while checking 'a.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/Users/.../Library/Caches/pylint/pylint-crash-2022-10-29-08-48-25.txt'. (astroid-error) ``` The offending file is at the top of the crash report. If the code is too long, or contains sensitive information, you can use the knowledge that the crash happened in `_infer_str_format_call` to look for calls to `.format()` on strings. You should be able to then just provide us those calls--and enough surrounding code to rebuild the objects you provided to `format()`. Doing this would be a tremendous help! > `pylint` produces a crash report, and shows the link in your terminal, like this: No, not really, it does not. I am attaching a (censored) stderr from running the test. The line in the source code that apparently triggers the problem is pretty innocuous: ``` @property def vnet_id(self): # <---- this is the line 266 that is mentioned in the "Exception on node" message if ...: ``` There is very similar property definition right before this one, that does not trigger the problem. [pyerr.txt](https://github.com/PyCQA/astroid/files/9900190/pyerr.txt) Pylint command was `python3 -m pylint --jobs=0 --rcfile=test/style/pylint.conf <project-dir>` ``` $ pylint --version pylint 2.15.5 astroid 2.12.12 Python 3.10.8 (main, Oct 24 2022, 10:07:16) [GCC 12.2.0] ``` edit: > enough surrounding code to rebuild the objects you provided to format(). _I_ did not provide any objects to `format()`, astroid did... Thanks for providing the traceback. > No, not really, it does not. I am attaching a (censored) stderr from running the test. I see now that it's because you're invoking pylint from a unittest, so your test is managing the output. > The line in the source code that apparently triggers the problem is pretty innocuous: The deeper failure is on the call in line 268, not the function def on line 266. Is there anything you can sanitize and tell us about line 268? Thanks again for providing the help. > I see now that it's because you're invoking pylint from a unittest, so your test is managing the output. When I run pylint by hand ``` pylint --jobs=0 --rcfile=test/style/pylint.conf <module-name> | tee /tmp/pyerr.txt ``` there is still no "Fatal error while checking ..." message in the output > > The line in the source code that apparently triggers the problem is pretty innocuous: > > The deeper failure is on the call in line 268, not the function def on line 266. Is there anything you can sanitize and tell us about line 268? Thanks again for providing the help. Oh yes, there is a `something.format()` in that line! But the "something" is a literal string: ``` @property def vnet_id(self): if self.backend == "something": return "{:04x}{:04x}n{:d}".format( # <---- this is line 268 self.<some-attr>, self.<another-attr>, self.<third-attr> ) if self.backend == "somethingelse": return "h{:08}n{:d}".format(self.<more-attr>, self.<and more>) return None ``` Thanks, that was very helpful. Here is a reproducer: ```python x = "{:c}".format(None) ```
2022-11-12T19:21:34Z
2.13
["tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\\n"]
["tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes-from-positional]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes-from-keyword]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[mixed-indexes-from-mixed]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes-on-variable]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\"I", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_with_specs"]
fe058bff95745371df5796286d33677c21137847
pylint-dev/astroid
pylint-dev__astroid-1268
ce5cbce5ba11cdc2f8139ade66feea1e181a7944
diff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py --- a/astroid/nodes/as_string.py +++ b/astroid/nodes/as_string.py @@ -36,6 +36,7 @@ MatchSingleton, MatchStar, MatchValue, + Unknown, ) # pylint: disable=unused-argument @@ -643,6 +644,9 @@ def visit_property(self, node): def visit_evaluatedobject(self, node): return node.original.accept(self) + def visit_unknown(self, node: "Unknown") -> str: + return str(node) + def _import_string(names): """return a list of (name, asname) formatted as a string"""
diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py --- a/tests/unittest_nodes.py +++ b/tests/unittest_nodes.py @@ -306,6 +306,11 @@ def test_f_strings(self): ast = abuilder.string_build(code) self.assertEqual(ast.as_string().strip(), code.strip()) + @staticmethod + def test_as_string_unknown() -> None: + assert nodes.Unknown().as_string() == "Unknown.Unknown()" + assert nodes.Unknown(lineno=1, col_offset=0).as_string() == "Unknown.Unknown()" + class _NodeTest(unittest.TestCase): """test transformation of If Node"""
'AsStringVisitor' object has no attribute 'visit_unknown' ```python >>> import astroid >>> astroid.nodes.Unknown().as_string() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py", line 609, in as_string return AsStringVisitor()(self) File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/as_string.py", line 56, in __call__ return node.accept(self).replace(DOC_NEWLINE, "\n") File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py", line 220, in accept func = getattr(visitor, "visit_" + self.__class__.__name__.lower()) AttributeError: 'AsStringVisitor' object has no attribute 'visit_unknown' >>> ``` ### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output 2.8.6-dev0
Thank you for opening the issue. I don't believe `Unknown().as_string()` is ever called regularly. AFAIK it's only used during inference. What should the string representation of an `Unknown` node be? So not sure this needs to be addressed. Probably just `'Unknown'`. It's mostly only a problem when we do something like this: ```python inferred = infer(node) if inferred is not Uninferable: if inferred.as_string().contains(some_value): ... ``` So for the most part, as long as it doesn't crash we're good.
2021-11-21T16:15:23Z
2.9
["tests/unittest_nodes.py::AsStringTest::test_as_string_unknown"]
["tests/unittest_nodes.py::AsStringTest::test_3k_annotations_and_metaclass", "tests/unittest_nodes.py::AsStringTest::test_3k_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable", "tests/unittest_nodes.py::AsStringTest::test_class_def", "tests/unittest_nodes.py::AsStringTest::test_ellipsis", "tests/unittest_nodes.py::AsStringTest::test_f_strings", "tests/unittest_nodes.py::AsStringTest::test_frozenset_as_string", "tests/unittest_nodes.py::AsStringTest::test_func_signature_issue_185", "tests/unittest_nodes.py::AsStringTest::test_int_attribute", "tests/unittest_nodes.py::AsStringTest::test_module2_as_string", "tests/unittest_nodes.py::AsStringTest::test_module_as_string", "tests/unittest_nodes.py::AsStringTest::test_operator_precedence", "tests/unittest_nodes.py::AsStringTest::test_slice_and_subscripts", "tests/unittest_nodes.py::AsStringTest::test_slices", "tests/unittest_nodes.py::AsStringTest::test_tuple_as_string", "tests/unittest_nodes.py::AsStringTest::test_varargs_kwargs_as_string", "tests/unittest_nodes.py::IfNodeTest::test_block_range", "tests/unittest_nodes.py::IfNodeTest::test_if_elif_else_node", "tests/unittest_nodes.py::IfNodeTest::test_if_sys_guard", "tests/unittest_nodes.py::IfNodeTest::test_if_typing_guard", "tests/unittest_nodes.py::TryExceptNodeTest::test_block_range", "tests/unittest_nodes.py::TryFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::TryExceptFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::ImportNodeTest::test_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_as_string", "tests/unittest_nodes.py::ImportNodeTest::test_bad_import_inference", "tests/unittest_nodes.py::ImportNodeTest::test_conditional", "tests/unittest_nodes.py::ImportNodeTest::test_conditional_import", "tests/unittest_nodes.py::ImportNodeTest::test_from_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_import_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_more_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_real_name", "tests/unittest_nodes.py::CmpNodeTest::test_as_string", "tests/unittest_nodes.py::ConstNodeTest::test_bool", "tests/unittest_nodes.py::ConstNodeTest::test_complex", "tests/unittest_nodes.py::ConstNodeTest::test_copy", "tests/unittest_nodes.py::ConstNodeTest::test_float", "tests/unittest_nodes.py::ConstNodeTest::test_int", "tests/unittest_nodes.py::ConstNodeTest::test_none", "tests/unittest_nodes.py::ConstNodeTest::test_str", "tests/unittest_nodes.py::ConstNodeTest::test_str_kind", "tests/unittest_nodes.py::ConstNodeTest::test_unicode", "tests/unittest_nodes.py::NameNodeTest::test_assign_to_true", "tests/unittest_nodes.py::TestNamedExprNode::test_frame", "tests/unittest_nodes.py::TestNamedExprNode::test_scope", "tests/unittest_nodes.py::AnnAssignNodeTest::test_as_string", "tests/unittest_nodes.py::AnnAssignNodeTest::test_complex", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value", "tests/unittest_nodes.py::ArgumentsNodeTC::test_kwoargs", "tests/unittest_nodes.py::ArgumentsNodeTC::test_positional_only", "tests/unittest_nodes.py::UnboundMethodNodeTest::test_no_super_getattr", "tests/unittest_nodes.py::BoundMethodNodeTest::test_is_property", "tests/unittest_nodes.py::AliasesTest::test_aliases", "tests/unittest_nodes.py::Python35AsyncTest::test_async_await_keywords", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncfor_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncwith_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_await_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string", "tests/unittest_nodes.py::ContextTest::test_list_del", "tests/unittest_nodes.py::ContextTest::test_list_load", "tests/unittest_nodes.py::ContextTest::test_list_store", "tests/unittest_nodes.py::ContextTest::test_starred_load", "tests/unittest_nodes.py::ContextTest::test_starred_store", "tests/unittest_nodes.py::ContextTest::test_subscript_del", "tests/unittest_nodes.py::ContextTest::test_subscript_load", "tests/unittest_nodes.py::ContextTest::test_subscript_store", "tests/unittest_nodes.py::ContextTest::test_tuple_load", "tests/unittest_nodes.py::ContextTest::test_tuple_store", "tests/unittest_nodes.py::test_unknown", "tests/unittest_nodes.py::test_type_comments_with", "tests/unittest_nodes.py::test_type_comments_for", "tests/unittest_nodes.py::test_type_coments_assign", "tests/unittest_nodes.py::test_type_comments_invalid_expression", "tests/unittest_nodes.py::test_type_comments_invalid_function_comments", "tests/unittest_nodes.py::test_type_comments_function", "tests/unittest_nodes.py::test_type_comments_arguments", "tests/unittest_nodes.py::test_type_comments_posonly_arguments", "tests/unittest_nodes.py::test_correct_function_type_comment_parent", "tests/unittest_nodes.py::test_is_generator_for_yield_assignments", "tests/unittest_nodes.py::test_f_string_correct_line_numbering", "tests/unittest_nodes.py::test_assignment_expression", "tests/unittest_nodes.py::test_assignment_expression_in_functiondef", "tests/unittest_nodes.py::test_get_doc", "tests/unittest_nodes.py::test_parse_fstring_debug_mode", "tests/unittest_nodes.py::test_parse_type_comments_with_proper_parent", "tests/unittest_nodes.py::test_const_itered", "tests/unittest_nodes.py::test_is_generator_for_yield_in_while", "tests/unittest_nodes.py::test_is_generator_for_yield_in_if", "tests/unittest_nodes.py::test_is_generator_for_yield_in_aug_assign"]
0d1211558670cfefd95b39984b8d5f7f34837f32
pyvista/pyvista
pyvista__pyvista-4315
db6ee8dd4a747b8864caae36c5d05883976a3ae5
diff --git a/pyvista/core/grid.py b/pyvista/core/grid.py --- a/pyvista/core/grid.py +++ b/pyvista/core/grid.py @@ -135,23 +135,30 @@ def __init__(self, *args, check_duplicates=False, deep=False, **kwargs): self.shallow_copy(args[0]) elif isinstance(args[0], (str, pathlib.Path)): self._from_file(args[0], **kwargs) - elif isinstance(args[0], np.ndarray): - self._from_arrays(args[0], None, None, check_duplicates) + elif isinstance(args[0], (np.ndarray, Sequence)): + self._from_arrays(np.asanyarray(args[0]), None, None, check_duplicates) else: raise TypeError(f'Type ({type(args[0])}) not understood by `RectilinearGrid`') elif len(args) == 3 or len(args) == 2: - arg0_is_arr = isinstance(args[0], np.ndarray) - arg1_is_arr = isinstance(args[1], np.ndarray) + arg0_is_arr = isinstance(args[0], (np.ndarray, Sequence)) + arg1_is_arr = isinstance(args[1], (np.ndarray, Sequence)) if len(args) == 3: - arg2_is_arr = isinstance(args[2], np.ndarray) + arg2_is_arr = isinstance(args[2], (np.ndarray, Sequence)) else: arg2_is_arr = False if all([arg0_is_arr, arg1_is_arr, arg2_is_arr]): - self._from_arrays(args[0], args[1], args[2], check_duplicates) + self._from_arrays( + np.asanyarray(args[0]), + np.asanyarray(args[1]), + np.asanyarray(args[2]), + check_duplicates, + ) elif all([arg0_is_arr, arg1_is_arr]): - self._from_arrays(args[0], args[1], None, check_duplicates) + self._from_arrays( + np.asanyarray(args[0]), np.asanyarray(args[1]), None, check_duplicates + ) else: raise TypeError("Arguments not understood by `RectilinearGrid`.")
diff --git a/tests/test_grid.py b/tests/test_grid.py --- a/tests/test_grid.py +++ b/tests/test_grid.py @@ -735,6 +735,21 @@ def test_create_rectilinear_grid_from_specs(): assert grid.n_cells == 9 * 3 * 19 assert grid.n_points == 10 * 4 * 20 assert grid.bounds == (-10.0, 8.0, -10.0, 5.0, -10.0, 9.0) + + # with Sequence + xrng = [0, 1] + yrng = [0, 1, 2] + zrng = [0, 1, 2, 3] + grid = pyvista.RectilinearGrid(xrng) + assert grid.n_cells == 1 + assert grid.n_points == 2 + grid = pyvista.RectilinearGrid(xrng, yrng) + assert grid.n_cells == 2 + assert grid.n_points == 6 + grid = pyvista.RectilinearGrid(xrng, yrng, zrng) + assert grid.n_cells == 6 + assert grid.n_points == 24 + # 2D example cell_spacings = np.array([1.0, 1.0, 2.0, 2.0, 5.0, 10.0]) x_coordinates = np.cumsum(cell_spacings)
Rectilinear grid does not allow Sequences as inputs ### Describe the bug, what's wrong, and what you expected. Rectilinear grid gives an error when `Sequence`s are passed in, but `ndarray` are ok. ### Steps to reproduce the bug. This doesn't work ```python import pyvista as pv pv.RectilinearGrid([0, 1], [0, 1], [0, 1]) ``` This works ```py import pyvista as pv import numpy as np pv.RectilinearGrid(np.ndarray([0, 1]), np.ndarray([0, 1]), np.ndarray([0, 1])) ``` ### System Information ```shell -------------------------------------------------------------------------------- Date: Wed Apr 19 20:15:10 2023 UTC OS : Linux CPU(s) : 2 Machine : x86_64 Architecture : 64bit Environment : IPython GPU Vendor : Mesa/X.org GPU Renderer : llvmpipe (LLVM 11.0.1, 256 bits) GPU Version : 4.5 (Core Profile) Mesa 20.3.5 Python 3.11.2 (main, Mar 23 2023, 17:12:29) [GCC 10.2.1 20210110] pyvista : 0.38.5 vtk : 9.2.6 numpy : 1.24.2 imageio : 2.27.0 scooby : 0.7.1 pooch : v1.7.0 matplotlib : 3.7.1 IPython : 8.12.0 -------------------------------------------------------------------------------- ``` ### Screenshots _No response_
2023-04-21T13:47:31Z
0.39
["tests/test_grid.py::test_create_rectilinear_grid_from_specs"]
["tests/test_grid.py::test_volume", "tests/test_grid.py::test_init_from_polydata", "tests/test_grid.py::test_init_from_structured", "tests/test_grid.py::test_init_from_unstructured", "tests/test_grid.py::test_init_from_numpy_arrays", "tests/test_grid.py::test_init_bad_input", "tests/test_grid.py::test_init_from_arrays[False]", "tests/test_grid.py::test_init_from_arrays[True]", "tests/test_grid.py::test_init_from_dict[False-False]", "tests/test_grid.py::test_init_from_dict[False-True]", "tests/test_grid.py::test_init_from_dict[True-False]", "tests/test_grid.py::test_init_from_dict[True-True]", "tests/test_grid.py::test_init_polyhedron", "tests/test_grid.py::test_cells_dict_hexbeam_file", "tests/test_grid.py::test_cells_dict_variable_length", "tests/test_grid.py::test_cells_dict_empty_grid", "tests/test_grid.py::test_cells_dict_alternating_cells", "tests/test_grid.py::test_destructor", "tests/test_grid.py::test_surface_indices", "tests/test_grid.py::test_extract_feature_edges", "tests/test_grid.py::test_triangulate_inplace", "tests/test_grid.py::test_save[.vtu-True]", "tests/test_grid.py::test_save[.vtu-False]", "tests/test_grid.py::test_save[.vtk-True]", "tests/test_grid.py::test_save[.vtk-False]", "tests/test_grid.py::test_pathlib_read_write", "tests/test_grid.py::test_init_bad_filename", "tests/test_grid.py::test_save_bad_extension", "tests/test_grid.py::test_linear_copy", "tests/test_grid.py::test_linear_copy_surf_elem", "tests/test_grid.py::test_extract_cells[True]", "tests/test_grid.py::test_extract_cells[False]", "tests/test_grid.py::test_merge", "tests/test_grid.py::test_merge_not_main", "tests/test_grid.py::test_merge_list", "tests/test_grid.py::test_merge_invalid", "tests/test_grid.py::test_init_structured_raise", "tests/test_grid.py::test_init_structured", "tests/test_grid.py::test_no_copy_polydata_init", "tests/test_grid.py::test_no_copy_polydata_points_setter", "tests/test_grid.py::test_no_copy_structured_mesh_init", "tests/test_grid.py::test_no_copy_structured_mesh_points_setter", "tests/test_grid.py::test_no_copy_pointset_init", "tests/test_grid.py::test_no_copy_pointset_points_setter", "tests/test_grid.py::test_no_copy_unstructured_grid_points_setter", "tests/test_grid.py::test_no_copy_rectilinear_grid", "tests/test_grid.py::test_grid_repr", "tests/test_grid.py::test_slice_structured", "tests/test_grid.py::test_invalid_init_structured", "tests/test_grid.py::test_save_structured[.vtk-True]", "tests/test_grid.py::test_save_structured[.vtk-False]", "tests/test_grid.py::test_save_structured[.vts-True]", "tests/test_grid.py::test_save_structured[.vts-False]", "tests/test_grid.py::test_load_structured_bad_filename", "tests/test_grid.py::test_instantiate_by_filename", "tests/test_grid.py::test_create_rectilinear_after_init", "tests/test_grid.py::test_create_rectilinear_grid_from_file", "tests/test_grid.py::test_read_rectilinear_grid_from_file", "tests/test_grid.py::test_read_rectilinear_grid_from_pathlib", "tests/test_grid.py::test_raise_rectilinear_grid_non_unique", "tests/test_grid.py::test_cast_rectilinear_grid", "tests/test_grid.py::test_create_uniform_grid_from_specs", "tests/test_grid.py::test_uniform_grid_invald_args", "tests/test_grid.py::test_uniform_setters", "tests/test_grid.py::test_create_uniform_grid_from_file", "tests/test_grid.py::test_read_uniform_grid_from_file", "tests/test_grid.py::test_read_uniform_grid_from_pathlib", "tests/test_grid.py::test_cast_uniform_to_structured", "tests/test_grid.py::test_cast_uniform_to_rectilinear", "tests/test_grid.py::test_uniform_grid_to_tetrahedra", "tests/test_grid.py::test_fft_and_rfft", "tests/test_grid.py::test_fft_low_pass", "tests/test_grid.py::test_fft_high_pass", "tests/test_grid.py::test_save_rectilinear[.vtk-True]", "tests/test_grid.py::test_save_rectilinear[.vtk-False]", "tests/test_grid.py::test_save_rectilinear[.vtr-True]", "tests/test_grid.py::test_save_rectilinear[.vtr-False]", "tests/test_grid.py::test_save_uniform[.vtk-True]", "tests/test_grid.py::test_save_uniform[.vtk-False]", "tests/test_grid.py::test_save_uniform[.vti-True]", "tests/test_grid.py::test_save_uniform[.vti-False]", "tests/test_grid.py::test_grid_points", "tests/test_grid.py::test_grid_extract_selection_points", "tests/test_grid.py::test_gaussian_smooth", "tests/test_grid.py::test_remove_cells[ind0]", "tests/test_grid.py::test_remove_cells[ind1]", "tests/test_grid.py::test_remove_cells[ind2]", "tests/test_grid.py::test_remove_cells_not_inplace[ind0]", "tests/test_grid.py::test_remove_cells_not_inplace[ind1]", "tests/test_grid.py::test_remove_cells_not_inplace[ind2]", "tests/test_grid.py::test_remove_cells_invalid", "tests/test_grid.py::test_hide_cells[ind0]", "tests/test_grid.py::test_hide_cells[ind1]", "tests/test_grid.py::test_hide_cells[ind2]", "tests/test_grid.py::test_hide_points[ind0]", "tests/test_grid.py::test_hide_points[ind1]", "tests/test_grid.py::test_hide_points[ind2]", "tests/test_grid.py::test_set_extent", "tests/test_grid.py::test_UnstructuredGrid_cast_to_explicit_structured_grid", "tests/test_grid.py::test_ExplicitStructuredGrid_init", "tests/test_grid.py::test_ExplicitStructuredGrid_cast_to_unstructured_grid", "tests/test_grid.py::test_ExplicitStructuredGrid_save", "tests/test_grid.py::test_ExplicitStructuredGrid_hide_cells", "tests/test_grid.py::test_ExplicitStructuredGrid_show_cells", "tests/test_grid.py::test_ExplicitStructuredGrid_dimensions", "tests/test_grid.py::test_ExplicitStructuredGrid_visible_bounds", "tests/test_grid.py::test_ExplicitStructuredGrid_cell_id", "tests/test_grid.py::test_ExplicitStructuredGrid_cell_coords", "tests/test_grid.py::test_ExplicitStructuredGrid_neighbors", "tests/test_grid.py::test_ExplicitStructuredGrid_compute_connectivity", "tests/test_grid.py::test_ExplicitStructuredGrid_compute_connections", "tests/test_grid.py::test_ExplicitStructuredGrid_raise_init", "tests/test_grid.py::test_copy_no_copy_wrap_object", "tests/test_grid.py::test_copy_no_copy_wrap_object_vtk9"]
4c2d1aed10b1600d520271beba8579c71433e808
pydicom/pydicom
pydicom__pydicom-1694
f8cf45b6c121e5a4bf4a43f71aba3bc64af3db9c
diff --git a/pydicom/dataset.py b/pydicom/dataset.py --- a/pydicom/dataset.py +++ b/pydicom/dataset.py @@ -2492,8 +2492,8 @@ def to_json_dict( json_dataset = {} for key in self.keys(): json_key = '{:08X}'.format(key) - data_element = self[key] try: + data_element = self[key] json_dataset[json_key] = data_element.to_json_dict( bulk_data_element_handler=bulk_data_element_handler, bulk_data_threshold=bulk_data_threshold
diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py --- a/pydicom/tests/test_json.py +++ b/pydicom/tests/test_json.py @@ -7,7 +7,7 @@ from pydicom import dcmread from pydicom.data import get_testdata_file -from pydicom.dataelem import DataElement +from pydicom.dataelem import DataElement, RawDataElement from pydicom.dataset import Dataset from pydicom.tag import Tag, BaseTag from pydicom.valuerep import PersonName @@ -284,7 +284,23 @@ def test_suppress_invalid_tags(self, _): ds_json = ds.to_json_dict(suppress_invalid_tags=True) - assert ds_json.get("00100010") is None + assert "00100010" not in ds_json + + def test_suppress_invalid_tags_with_failed_dataelement(self): + """Test tags that raise exceptions don't if suppress_invalid_tags True. + """ + ds = Dataset() + # we have to add a RawDataElement as creating a DataElement would + # already raise an exception + ds[0x00082128] = RawDataElement( + Tag(0x00082128), 'IS', 4, b'5.25', 0, True, True) + + with pytest.raises(TypeError): + ds.to_json_dict() + + ds_json = ds.to_json_dict(suppress_invalid_tags=True) + + assert "00082128" not in ds_json class TestSequence:
Dataset.to_json_dict can still generate exceptions when suppress_invalid_tags=True **Describe the bug** I'm using `Dataset.to_json_dict(suppress_invalid_tags=True)` and can live with losing invalid tags. Unfortunately, I can still trigger an exception with something like `2.0` in an `IS` field. **Expected behavior** to_json_dict shouldn't throw an error about an invalid tag when `suppress_invalid_tags` is enabled. My thought was simply to move the `data_element = self[key]` into the try/catch block that's right after it. **Steps To Reproduce** Traceback: ``` File "dicom.py", line 143, in create_dict json_ds = ds.to_json_dict(suppress_invalid_tags=True) File "/usr/lib/python3/dist-packages/pydicom/dataset.py", line 2495, in to_json_dict data_element = self[key] File "/usr/lib/python3/dist-packages/pydicom/dataset.py", line 939, in __getitem__ self[tag] = DataElement_from_raw(elem, character_set, self) File "/usr/lib/python3/dist-packages/pydicom/dataelem.py", line 859, in DataElement_from_raw value = convert_value(vr, raw, encoding) File "/usr/lib/python3/dist-packages/pydicom/values.py", line 771, in convert_value return converter(byte_string, is_little_endian, num_format) File "/usr/lib/python3/dist-packages/pydicom/values.py", line 348, in convert_IS_string return MultiString(num_string, valtype=pydicom.valuerep.IS) File "/usr/lib/python3/dist-packages/pydicom/valuerep.py", line 1213, in MultiString return valtype(splitup[0]) File "/usr/lib/python3/dist-packages/pydicom/valuerep.py", line 1131, in __new__ raise TypeError("Could not convert value to integer without loss") TypeError: Could not convert value to integer without loss ``` **Your environment** python 3.7, pydicom 2.3
2022-09-20T18:52:53Z
2.3
["pydicom/tests/test_json.py::TestDataSetToJson::test_suppress_invalid_tags_with_failed_dataelement"]
["pydicom/tests/test_json.py::TestPersonName::test_json_pn_from_file", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_value_in_json", "pydicom/tests/test_json.py::TestAT::test_invalid_tag_in_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataset_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataelement_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_sort_order", "pydicom/tests/test_json.py::TestDataSetToJson::test_suppress_invalid_tags", "pydicom/tests/test_json.py::TestSequence::test_nested_sequences", "pydicom/tests/test_json.py::TestBinary::test_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_invalid_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_valid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_invalid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_2", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_within_SQ", "pydicom/tests/test_json.py::TestNumeric::test_numeric_values", "pydicom/tests/test_json.py::TestNumeric::test_numeric_types"]
a8be738418dee0a2b93c241fbd5e0bc82f4b8680
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
185
Edit dataset card