instance_id
stringlengths
10
57
base_commit
stringlengths
40
40
created_at
stringdate
2014-04-30 14:58:36
2025-04-30 20:14:11
environment_setup_commit
stringlengths
40
40
hints_text
stringlengths
0
273k
patch
stringlengths
251
7.06M
problem_statement
stringlengths
11
52.5k
repo
stringlengths
7
53
test_patch
stringlengths
231
997k
meta
dict
version
stringclasses
851 values
install_config
dict
requirements
stringlengths
93
34.2k
environment
stringlengths
760
20.5k
FAIL_TO_PASS
listlengths
1
9.39k
FAIL_TO_FAIL
listlengths
0
2.69k
PASS_TO_PASS
listlengths
0
7.87k
PASS_TO_FAIL
listlengths
0
192
license_name
stringclasses
55 values
__index_level_0__
int64
0
21.4k
before_filepaths
listlengths
1
105
after_filepaths
listlengths
1
105
robshakir__pyangbind-200
a3694e5434ba841016a737fc2d2373337d0c583e
2018-05-15 20:14:17
bcb1d8677f4d11e0aca61d658ccab0d48c7b6322
diff --git a/pyangbind/lib/yangtypes.py b/pyangbind/lib/yangtypes.py index aa6fe79..8b73346 100644 --- a/pyangbind/lib/yangtypes.py +++ b/pyangbind/lib/yangtypes.py @@ -377,19 +377,25 @@ def TypedListType(*args, **kwargs): _list = list() def __init__(self, *args, **kwargs): + self._unique = kwargs.pop('unique', False) self._allowed_type = allowed_type self._list = list() if len(args): if isinstance(args[0], list): tmp = [] for i in args[0]: - tmp.append(self.check(i)) + if not self._unique or i not in tmp: + tmp.append(self.check(i)) self._list.extend(tmp) else: tmp = self.check(args[0]) self._list.append(tmp) def check(self, v): + # Short circuit uniqueness check + if self._unique and v in self._list: + raise ValueError("Values in this list must be unique.") + passed = False count = 0 for i in self._allowed_type: @@ -446,16 +452,16 @@ def TypedListType(*args, **kwargs): del self._list[i] def __setitem__(self, i, v): - self.check(v) - self._list.insert(i, v) + self.insert(i, v) def insert(self, i, v): val = self.check(v) self._list.insert(i, val) def append(self, v): - val = self.check(v) - self._list.append(val) + if not self._unique or v not in self._list: + val = self.check(v) + self._list.append(val) def __str__(self): return str(self._list) diff --git a/pyangbind/plugin/pybind.py b/pyangbind/plugin/pybind.py index 98ef25e..3707c08 100644 --- a/pyangbind/plugin/pybind.py +++ b/pyangbind/plugin/pybind.py @@ -844,7 +844,7 @@ def get_children(ctx, fd, i_children, module, parent, path=str(), # TypedList (see lib.yangtypes) with a particular set of types allowed. class_str["name"] = "__%s" % (i["name"]) class_str["type"] = "YANGDynClass" - class_str["arg"] = "base=" + class_str["arg"] = "unique=True, base=" if isinstance(i["type"]["native_type"][1], list): allowed_type = "[" for subtype in i["type"]["native_type"][1]: diff --git a/tox.ini b/tox.ini index 51e59dc..d11d8c3 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py{27,34,35,36,37,py2,py3},flake8 +envlist = py{27,34,35,36,37,py2},flake8 skip_missing_interpreters = True [testenv]
Leaf-list stores multiple duplicate values Hello, I noticed in [RFC 6020 section 7.7 for leaf-list](https://tools.ietf.org/html/rfc6020#section-7.7) that there is a requirement on leaf-list which we do not follow in pyangbind. `The values in a leaf-list MUST be unique.` ### Example: Given the following yang model: ```yang module test { namespace "http://foo/bar/test/1.0"; prefix test; leaf-list my-leaf-list { type string; } } ``` #### Expected ```python >>> from test import test >>> from pyangbind.lib.xpathhelper import YANGPathHelper >>> >>> graph = test(ph=YANGPathHelper()) >>> >>> graph.my_leaf_list = ['foo', 'foo'] >>> graph.get() {'my-leaf-list': [u'foo']} ``` #### Actual ```python >>> graph.get() {'my-leaf-list': [u'foo', u'foo']} ``` I think the leaf-list structure might need to resemble a set instead of a list, unless I misunderstood the rfc.
robshakir/pyangbind
diff --git a/tests/leaf-list/run.py b/tests/leaf-list/run.py index 331167b..f84c6cf 100755 --- a/tests/leaf-list/run.py +++ b/tests/leaf-list/run.py @@ -16,22 +16,21 @@ class LeafListTests(PyangBindTestCase): self.leaflist_obj = self.bindings.leaflist() def test_container_exists(self): - self.assertTrue(hasattr(self.leaflist_obj, "container"), "Base container is missing.") + self.assertTrue(hasattr(self.leaflist_obj, "container")) def test_leaflist_exists(self): - self.assertTrue(hasattr(self.leaflist_obj.container, "leaflist"), "Leaf-list instance is missing.") + self.assertTrue(hasattr(self.leaflist_obj.container, "leaflist")) def test_leaflist_length_is_zero(self): - self.assertEqual(len(self.leaflist_obj.container.leaflist), 0, "Length of leaflist was not zero.") + self.assertEqual(len(self.leaflist_obj.container.leaflist), 0) def test_append_to_leaflist(self): self.leaflist_obj.container.leaflist.append("itemOne") - self.assertEqual(len(self.leaflist_obj.container.leaflist), 1, "Did not successfully append string to list.") + self.assertEqual(len(self.leaflist_obj.container.leaflist), 1) def test_retrieve_leaflist_item_value(self): self.leaflist_obj.container.leaflist.append("itemOne") - self.assertEqual(self.leaflist_obj.container.leaflist[0], "itemOne", - "Cannot successfully address an item from the list.") + self.assertEqual(self.leaflist_obj.container.leaflist[0], "itemOne") def test_append_int_to_string_leaflist(self): with self.assertRaises(ValueError): @@ -41,14 +40,14 @@ class LeafListTests(PyangBindTestCase): self.leaflist_obj.container.leaflist.append("itemOne") self.leaflist_obj.container.leaflist.append("itemTwo") - self.assertEqual(self.leaflist_obj.container.leaflist[1], "itemTwo", "getitem did not return the correct value.") + self.assertEqual(self.leaflist_obj.container.leaflist[1], "itemTwo") def test_setitem(self): self.leaflist_obj.container.leaflist.append("itemOne") self.leaflist_obj.container.leaflist.append("itemTwo") self.leaflist_obj.container.leaflist[1] = "indexOne" - self.assertEqual(self.leaflist_obj.container.leaflist[1], "indexOne", "setitem did not set the correct node.") + self.assertEqual(self.leaflist_obj.container.leaflist[1], "indexOne") def test_insert(self): self.leaflist_obj.container.leaflist.append("itemOne") @@ -56,7 +55,7 @@ class LeafListTests(PyangBindTestCase): self.leaflist_obj.container.leaflist[1] = "indexOne" self.leaflist_obj.container.leaflist.insert(0, "indexZero") - self.assertEqual(self.leaflist_obj.container.leaflist[0], "indexZero", "Incorrectly set index 0 value") + self.assertEqual(self.leaflist_obj.container.leaflist[0], "indexZero") def test_leaflist_grows_from_various_modification_methods(self): self.leaflist_obj.container.leaflist.append("itemOne") @@ -64,7 +63,7 @@ class LeafListTests(PyangBindTestCase): self.leaflist_obj.container.leaflist[1] = "indexOne" self.leaflist_obj.container.leaflist.insert(0, "indexZero") - self.assertEqual(len(self.leaflist_obj.container.leaflist), 4, "List item was not added by insert()") + self.assertEqual(len(self.leaflist_obj.container.leaflist), 4) def test_delete_item_from_leaflist(self): self.leaflist_obj.container.leaflist.append("itemOne") @@ -74,7 +73,7 @@ class LeafListTests(PyangBindTestCase): del self.leaflist_obj.container.leaflist[0] - self.assertEqual(len(self.leaflist_obj.container.leaflist), 3, "List item not successfully removed by delitem") + self.assertEqual(len(self.leaflist_obj.container.leaflist), 3) def test_get_full_leaflist(self): self.leaflist_obj.container.leaflist.append("itemOne") @@ -87,15 +86,13 @@ class LeafListTests(PyangBindTestCase): self.leaflist_obj.get(), {'container': {'leaflist': ['itemOne', 'indexOne', 'itemTwo'], 'listtwo': [], - 'listthree': []}}, - "get did not correctly return the dictionary" + 'listthree': []}} ) def test_leaflist_assignment(self): self.leaflist_obj.container.leaflist = ["itemOne", "itemTwo"] - self.assertEqual(self.leaflist_obj.container.leaflist, ["itemOne", "itemTwo"], - "Leaflist assignment did not function correctly") + self.assertEqual(self.leaflist_obj.container.leaflist, ["itemOne", "itemTwo"]) def test_leaflist_assignment_of_wrong_type(self): with self.assertRaises(ValueError): @@ -103,7 +100,7 @@ class LeafListTests(PyangBindTestCase): def test_restricted_string(self): self.leaflist_obj.container.listtwo.append("a-valid-string") - self.assertEqual(len(self.leaflist_obj.container.listtwo), 1, "Restricted lefalist did not function correctly.") + self.assertEqual(len(self.leaflist_obj.container.listtwo), 1) def test_restricted_string_invalid_value(self): with self.assertRaises(ValueError): @@ -117,8 +114,23 @@ class LeafListTests(PyangBindTestCase): self.leaflist_obj.container.listthree.append(pair[0]) except ValueError: allowed = False - self.assertEqual(allowed, pair[1], "leaf-list of union type had invalid result (%s != %s for %s)" % - (allowed, pair[1], pair[0])) + self.assertEqual(allowed, pair[1]) + + def test_leaf_lists_are_unique_after_assignment(self): + self.leaflist_obj.container.leaflist = ['foo', 'bar', 'foo'] + self.assertEqual(self.leaflist_obj.container.get(filter=True), {'leaflist': ['foo', 'bar']}) + + def test_leaf_lists_are_unique_after_append(self): + self.leaflist_obj.container.leaflist.append('foo') + self.leaflist_obj.container.leaflist.append('bar') + self.leaflist_obj.container.leaflist.append('foo') + self.assertEqual(self.leaflist_obj.container.get(filter=True), {'leaflist': ['foo', 'bar']}) + + def test_leaf_lists_insert_non_unique_value_raises_keyerror(self): + self.leaflist_obj.container.leaflist[0] = 'foo' + self.leaflist_obj.container.leaflist[1] = 'bar' + with self.assertRaises(ValueError): + self.leaflist_obj.container.leaflist[2] = 'foo' if __name__ == '__main__':
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 3 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "flake8", "requests" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
bitarray==3.3.0 certifi==2025.1.31 charset-normalizer==3.4.1 enum34==1.1.10 exceptiongroup==1.2.2 flake8==7.2.0 idna==3.10 iniconfig==2.1.0 lxml==5.3.1 mccabe==0.7.0 packaging==24.2 pluggy==1.5.0 pyang==2.6.1 -e git+https://github.com/robshakir/pyangbind.git@a3694e5434ba841016a737fc2d2373337d0c583e#egg=pyangbind pycodestyle==2.13.0 pyflakes==3.3.1 pytest==8.3.5 regex==2024.11.6 requests==2.32.3 six==1.17.0 tomli==2.2.1 urllib3==2.3.0
name: pyangbind channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - bitarray==3.3.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - enum34==1.1.10 - exceptiongroup==1.2.2 - flake8==7.2.0 - idna==3.10 - iniconfig==2.1.0 - lxml==5.3.1 - mccabe==0.7.0 - packaging==24.2 - pluggy==1.5.0 - pyang==2.6.1 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pytest==8.3.5 - regex==2024.11.6 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/pyangbind
[ "tests/leaf-list/run.py::LeafListTests::test_leaf_lists_are_unique_after_append", "tests/leaf-list/run.py::LeafListTests::test_leaf_lists_are_unique_after_assignment", "tests/leaf-list/run.py::LeafListTests::test_leaf_lists_insert_non_unique_value_raises_keyerror" ]
[]
[ "tests/leaf-list/run.py::LeafListTests::test_append_int_to_string_leaflist", "tests/leaf-list/run.py::LeafListTests::test_append_to_leaflist", "tests/leaf-list/run.py::LeafListTests::test_container_exists", "tests/leaf-list/run.py::LeafListTests::test_delete_item_from_leaflist", "tests/leaf-list/run.py::LeafListTests::test_get_full_leaflist", "tests/leaf-list/run.py::LeafListTests::test_getitem", "tests/leaf-list/run.py::LeafListTests::test_insert", "tests/leaf-list/run.py::LeafListTests::test_leaflist_assignment", "tests/leaf-list/run.py::LeafListTests::test_leaflist_assignment_of_wrong_type", "tests/leaf-list/run.py::LeafListTests::test_leaflist_exists", "tests/leaf-list/run.py::LeafListTests::test_leaflist_grows_from_various_modification_methods", "tests/leaf-list/run.py::LeafListTests::test_leaflist_length_is_zero", "tests/leaf-list/run.py::LeafListTests::test_restricted_string", "tests/leaf-list/run.py::LeafListTests::test_restricted_string_invalid_value", "tests/leaf-list/run.py::LeafListTests::test_retrieve_leaflist_item_value", "tests/leaf-list/run.py::LeafListTests::test_setitem", "tests/leaf-list/run.py::LeafListTests::test_union_type" ]
[]
Apache License 2.0
2,530
[ "pyangbind/plugin/pybind.py", "tox.ini", "pyangbind/lib/yangtypes.py" ]
[ "pyangbind/plugin/pybind.py", "tox.ini", "pyangbind/lib/yangtypes.py" ]
python-cmd2__cmd2-403
a9b712108e5af49937b0af3aa51db2ebe5c159e4
2018-05-16 04:23:38
8f88f819fae7508066a81a8d961a7115f2ec4bed
diff --git a/cmd2/parsing.py b/cmd2/parsing.py index ce15bd38..655e0c58 100644 --- a/cmd2/parsing.py +++ b/cmd2/parsing.py @@ -250,23 +250,27 @@ class StatementParser: tokens = self.tokenize(rawinput) # of the valid terminators, find the first one to occur in the input - terminator_pos = len(tokens)+1 - for test_terminator in self.terminators: - try: - pos = tokens.index(test_terminator) - if pos < terminator_pos: + terminator_pos = len(tokens) + 1 + for pos, cur_token in enumerate(tokens): + for test_terminator in self.terminators: + if cur_token.startswith(test_terminator): terminator_pos = pos terminator = test_terminator + # break the inner loop, and we want to break the + # outer loop too break - except ValueError: - # the terminator is not in the tokens - pass + else: + # this else clause is only run if the inner loop + # didn't execute a break. If it didn't, then + # continue to the next iteration of the outer loop + continue + # inner loop was broken, break the outer + break if terminator: if terminator == LINE_FEED: terminator_pos = len(tokens)+1 - else: - terminator_pos = tokens.index(terminator) + # everything before the first terminator is the command and the args argv = tokens[:terminator_pos] (command, args) = self._command_and_args(argv)
Allow continuous run of terminators to end a multiline command `test_cmd ;;;;;` (Results in a new line) `test_cmd ;;;;; ;` (Completes the command) Both of these input lines should complete the command.
python-cmd2/cmd2
diff --git a/tests/test_parsing.py b/tests/test_parsing.py index 41966c71..7b361b7e 100644 --- a/tests/test_parsing.py +++ b/tests/test_parsing.py @@ -250,6 +250,23 @@ def test_parse_redirect_inside_terminator(parser): assert statement.argv == ['has', '>', 'inside'] assert statement.terminator == ';' [email protected]('line,terminator',[ + ('multiline with | inside;', ';'), + ('multiline with | inside ;', ';'), + ('multiline with | inside;;;', ';'), + ('multiline with | inside;; ;;', ';'), + ('multiline with | inside&', '&'), + ('multiline with | inside &;', '&'), + ('multiline with | inside&&;', '&'), + ('multiline with | inside &; &;', '&'), +]) +def test_parse_multiple_terminators(parser, line, terminator): + statement = parser.parse(line) + assert statement.multiline_command == 'multiline' + assert statement.args == 'with | inside' + assert statement.argv == ['multiline', 'with', '|', 'inside'] + assert statement.terminator == terminator + def test_parse_unfinished_multiliine_command(parser): line = 'multiline has > inside an unfinished command' statement = parser.parse(line) @@ -261,7 +278,10 @@ def test_parse_unfinished_multiliine_command(parser): @pytest.mark.parametrize('line,terminator',[ ('multiline has > inside;', ';'), + ('multiline has > inside;;;', ';'), + ('multiline has > inside;; ;;', ';'), ('multiline has > inside &', '&'), + ('multiline has > inside & &', '&'), ]) def test_parse_multiline_command_ignores_redirectors_within_it(parser, line, terminator): statement = parser.parse(line) @@ -388,8 +408,15 @@ def test_parse_alias_pipe(parser, line): assert not statement.args assert statement.pipe_to == ['less'] -def test_parse_alias_terminator_no_whitespace(parser): - line = 'helpalias;' [email protected]('line', [ + 'helpalias;', + 'helpalias;;', + 'helpalias;; ;', + 'helpalias ;', + 'helpalias ; ;', + 'helpalias ;; ;', +]) +def test_parse_alias_terminator_no_whitespace(parser, line): statement = parser.parse(line) assert statement.command == 'help' assert not statement.args @@ -448,6 +475,8 @@ def test_parse_command_only_quoted_args(parser): 'helpalias>>out.txt', 'help|less', 'helpalias;', + 'help ;;', + 'help; ;;', ]) def test_parse_command_only_specialchars(parser, line): statement = parser.parse_command_only(line) @@ -455,6 +484,11 @@ def test_parse_command_only_specialchars(parser, line): @pytest.mark.parametrize('line', [ ';', + ';;', + ';; ;', + '&', + '& &', + ' && &', '>', "'", '"',
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-mock", "argcomplete" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
argcomplete==3.6.1 -e git+https://github.com/python-cmd2/cmd2.git@a9b712108e5af49937b0af3aa51db2ebe5c159e4#egg=cmd2 colorama==0.4.6 coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pyperclip==1.9.0 pytest==8.3.5 pytest-cov==6.0.0 pytest-mock==3.14.0 tomli==2.2.1 wcwidth==0.2.13
name: cmd2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argcomplete==3.6.1 - colorama==0.4.6 - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pyperclip==1.9.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - tomli==2.2.1 - wcwidth==0.2.13 prefix: /opt/conda/envs/cmd2
[ "tests/test_parsing.py::test_parse_multiple_terminators[multiline", "tests/test_parsing.py::test_parse_multiline_command_ignores_redirectors_within_it[multiline", "tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;]", "tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;", "tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias" ]
[]
[ "tests/test_parsing.py::test_parse_empty_string", "tests/test_parsing.py::test_tokenize[command-tokens0]", "tests/test_parsing.py::test_tokenize[command", "tests/test_parsing.py::test_tokenize[42", "tests/test_parsing.py::test_tokenize[l-tokens4]", "tests/test_parsing.py::test_tokenize[termbare", "tests/test_parsing.py::test_tokenize[termbare;", "tests/test_parsing.py::test_tokenize[termbare&", "tests/test_parsing.py::test_tokenize[help|less-tokens9]", "tests/test_parsing.py::test_tokenize[l|less-tokens10]", "tests/test_parsing.py::test_tokenize_unclosed_quotes", "tests/test_parsing.py::test_command_and_args[tokens0-None-None]", "tests/test_parsing.py::test_command_and_args[tokens1-command-None]", "tests/test_parsing.py::test_command_and_args[tokens2-command-arg1", "tests/test_parsing.py::test_parse_single_word[plainword]", "tests/test_parsing.py::test_parse_single_word[\"one", "tests/test_parsing.py::test_parse_single_word['one", "tests/test_parsing.py::test_parse_word_plus_terminator[termbare;-;]", "tests/test_parsing.py::test_parse_word_plus_terminator[termbare", "tests/test_parsing.py::test_parse_word_plus_terminator[termbare&-&]", "tests/test_parsing.py::test_parse_suffix_after_terminator[termbare;", "tests/test_parsing.py::test_parse_suffix_after_terminator[termbare", "tests/test_parsing.py::test_parse_suffix_after_terminator[termbare&", "tests/test_parsing.py::test_parse_command_with_args", "tests/test_parsing.py::test_parse_command_with_quoted_args", "tests/test_parsing.py::test_parse_command_with_args_terminator_and_suffix", "tests/test_parsing.py::test_parse_hashcomment", "tests/test_parsing.py::test_parse_c_comment", "tests/test_parsing.py::test_parse_c_comment_empty", "tests/test_parsing.py::test_parse_what_if_quoted_strings_seem_to_start_comments", "tests/test_parsing.py::test_parse_simple_pipe[simple", "tests/test_parsing.py::test_parse_simple_pipe[simple|piped]", "tests/test_parsing.py::test_parse_double_pipe_is_not_a_pipe", "tests/test_parsing.py::test_parse_complex_pipe", "tests/test_parsing.py::test_parse_redirect[help", "tests/test_parsing.py::test_parse_redirect[help>out.txt->]", "tests/test_parsing.py::test_parse_redirect[help>>out.txt->>]", "tests/test_parsing.py::test_parse_redirect_with_args", "tests/test_parsing.py::test_parse_redirect_with_dash_in_path", "tests/test_parsing.py::test_parse_redirect_append", "tests/test_parsing.py::test_parse_pipe_and_redirect", "tests/test_parsing.py::test_parse_output_to_paste_buffer", "tests/test_parsing.py::test_parse_redirect_inside_terminator", "tests/test_parsing.py::test_parse_unfinished_multiliine_command", "tests/test_parsing.py::test_parse_multiline_with_incomplete_comment", "tests/test_parsing.py::test_parse_multiline_with_complete_comment", "tests/test_parsing.py::test_parse_multiline_termninated_by_empty_line", "tests/test_parsing.py::test_parse_multiline_ignores_terminators_in_comments", "tests/test_parsing.py::test_parse_command_with_unicode_args", "tests/test_parsing.py::test_parse_unicode_command", "tests/test_parsing.py::test_parse_redirect_to_unicode_filename", "tests/test_parsing.py::test_parse_unclosed_quotes", "tests/test_parsing.py::test_empty_statement_raises_exception", "tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias-help-None]", "tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias", "tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42-theanswer-None]", "tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42", "tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls-shell-ls]", "tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls", "tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[l-shell-ls", "tests/test_parsing.py::test_parse_alias_on_multiline_command", "tests/test_parsing.py::test_parse_alias_redirection[helpalias", "tests/test_parsing.py::test_parse_alias_redirection[helpalias>out.txt->]", "tests/test_parsing.py::test_parse_alias_redirection[helpalias>>out.txt->>]", "tests/test_parsing.py::test_parse_alias_pipe[helpalias", "tests/test_parsing.py::test_parse_alias_pipe[helpalias|less]", "tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;]", "tests/test_parsing.py::test_parse_command_only_command_and_args", "tests/test_parsing.py::test_parse_command_only_emptyline", "tests/test_parsing.py::test_parse_command_only_strips_line", "tests/test_parsing.py::test_parse_command_only_expands_alias", "tests/test_parsing.py::test_parse_command_only_expands_shortcuts", "tests/test_parsing.py::test_parse_command_only_quoted_args", "tests/test_parsing.py::test_parse_command_only_specialchars[helpalias", "tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>out.txt]", "tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>>out.txt]", "tests/test_parsing.py::test_parse_command_only_specialchars[help|less]", "tests/test_parsing.py::test_parse_command_only_specialchars[helpalias;]", "tests/test_parsing.py::test_parse_command_only_specialchars[help", "tests/test_parsing.py::test_parse_command_only_specialchars[help;", "tests/test_parsing.py::test_parse_command_only_none[;]", "tests/test_parsing.py::test_parse_command_only_none[;;]", "tests/test_parsing.py::test_parse_command_only_none[;;", "tests/test_parsing.py::test_parse_command_only_none[&]", "tests/test_parsing.py::test_parse_command_only_none[&", "tests/test_parsing.py::test_parse_command_only_none[", "tests/test_parsing.py::test_parse_command_only_none[>]", "tests/test_parsing.py::test_parse_command_only_none[']", "tests/test_parsing.py::test_parse_command_only_none[\"]", "tests/test_parsing.py::test_parse_command_only_none[|]" ]
[]
MIT License
2,531
[ "cmd2/parsing.py" ]
[ "cmd2/parsing.py" ]
streamlink__streamlink-1660
e2a55461decc6856912325e8103cefb359027811
2018-05-16 14:48:22
060d38d3f0acc2c4f3b463ea988361622a9b6544
codecov[bot]: # [Codecov](https://codecov.io/gh/streamlink/streamlink/pull/1660?src=pr&el=h1) Report > Merging [#1660](https://codecov.io/gh/streamlink/streamlink/pull/1660?src=pr&el=desc) into [master](https://codecov.io/gh/streamlink/streamlink/commit/e2a55461decc6856912325e8103cefb359027811?src=pr&el=desc) will **decrease** coverage by `0.17%`. > The diff coverage is `100%`. ```diff @@ Coverage Diff @@ ## master #1660 +/- ## ========================================== - Coverage 33.17% 32.99% -0.18% ========================================== Files 229 229 Lines 12898 12898 ========================================== - Hits 4279 4256 -23 - Misses 8619 8642 +23 ``` karlo2105: Thanks. gravyboat: Nice, thanks @beardypig.
diff --git a/src/streamlink/plugins/tf1.py b/src/streamlink/plugins/tf1.py index 189f124c..88b5e585 100644 --- a/src/streamlink/plugins/tf1.py +++ b/src/streamlink/plugins/tf1.py @@ -9,13 +9,20 @@ from streamlink.stream import HLSStream class TF1(Plugin): - url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(tf1|tmc|tfx|tf1-series-films)/direct|(lci).fr/direct)/?") + url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/([\w-]+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" - hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci", "tfx" : "nt1live", "tf1-series-films" : "hd1live" } - hls_channel_remap = {"lci": "LCI", "tf1": "V4", "tfx" : "nt1", "tf1-series-films" : "hd1" } + hds_channel_remap = {"tf1": "androidliveconnect", + "lci": "androidlivelci", + "tfx": "nt1live", + "hd1": "hd1live", # renamed to tfx + "tf1-series-films": "hd1live"} + hls_channel_remap = {"lci": "LCI", + "tf1": "V4", + "tfx": "nt1", + "tf1-series-films": "hd1"} @classmethod def can_handle_url(cls, url): @@ -23,6 +30,7 @@ class TF1(Plugin): def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) + self.logger.debug("Using HDS channel name: {0}".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text
LCI not covered by TF1 home page anymore ### Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description I pointed out since a while that tf1 plugin doesn't cover anymore LCI from tf1.fr home website. It did before. ### Expected / Actual behavior Here I point out result with older tf1 plugin : ``` streamlink "https://www.tf1.fr/lci/direct" [cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct error: Unable to open URL: http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@30158 5/manifest.f4m?hdnea=st=1526479986~exp=1526481786~acl=/*~hmac=207f41547435bb3422 e9f51af166cae855bdbb387ac875524827deb528999d9e (403 Client Error: Forbidden for url: http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@301585/manifest.f4m?hdnea=s t=1526479986~exp=1526481786~acl=/*~hmac=207f41547435bb3422e9f51af166cae855bdbb38 7ac875524827deb528999d9e&g=DSCLJVQYJHGR&hdcore=3.1.0) ``` The latest tf1 plugin gives such result : ``` streamlink "https://www.tf1.fr/lci/direct" [cli][info] Found matching plugin resolve for URL https://www.tf1.fr/lci/direct [plugin.resolve][info] Found iframes: Traceback (most recent call last): File "C:\Program Files\Python27\Scripts\streamlink-script.py", line 11, in <mo dule> load_entry_point('streamlink==0.12.1+8.ge2a5546', 'console_scripts', 'stream link')() File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin e 1113, in main handle_url() File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin e 505, in handle_url streams = fetch_streams(plugin) File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin e 402, in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "c:\program files\python27\lib\site-packages\streamlink\plugin\plugin.py" , line 385, in get_streams return self.streams(*args, **kwargs) File "c:\program files\python27\lib\site-packages\streamlink\plugin\plugin.py" , line 288, in streams ostreams = self._get_streams() File "c:\program files\python27\lib\site-packages\streamlink\plugins\resolve.p y", line 480, in _get_streams IndexError: list index out of range ``` ### Reproduction steps / Explicit stream URLs to test 1. ` streamlink "https://www.tf1.fr/lci/direct"` ### Logs ``` streamlink -l debug [cli][debug] OS: Windows 7 [cli][debug] Python: 2.7.13 [cli][debug] Streamlink: 0.12.1+8.ge2a5546 [cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.46.0) ``` Both tests were made with the latest streamlink build, I just replaced newer tf1 plugin with older. Thanks for up.
streamlink/streamlink
diff --git a/tests/test_plugin_tf1.py b/tests/test_plugin_tf1.py index 77afd8d8..f8e48790 100644 --- a/tests/test_plugin_tf1.py +++ b/tests/test_plugin_tf1.py @@ -12,11 +12,11 @@ class TestPluginTF1(unittest.TestCase): self.assertTrue(TF1.can_handle_url("http://lci.fr/direct")) self.assertTrue(TF1.can_handle_url("http://www.lci.fr/direct")) self.assertTrue(TF1.can_handle_url("http://tf1.fr/tmc/direct")) + self.assertTrue(TF1.can_handle_url("http://tf1.fr/lci/direct")) + def test_can_handle_url_negative(self): # shouldn't match self.assertFalse(TF1.can_handle_url("http://tf1.fr/direct")) -# self.assertFalse(TF1.can_handle_url("http://tf1.fr/nt1/direct")) NOTE : TF1 redirect old channel names to new ones (for now). -# self.assertFalse(TF1.can_handle_url("http://tf1.fr/hd1/direct")) self.assertFalse(TF1.can_handle_url("http://www.tf1.fr/direct")) self.assertFalse(TF1.can_handle_url("http://www.tvcatchup.com/")) self.assertFalse(TF1.can_handle_url("http://www.youtube.com/"))
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "codecov", "coverage", "mock", "requests-mock", "pynsist", "unittest2" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 codecov==2.1.13 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 iso-639==0.4.5 iso3166==2.1.1 Jinja2==3.1.6 linecache2==1.0.0 MarkupSafe==3.0.2 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pycryptodome==3.22.0 pynsist==2.8 PySocks==1.7.1 pytest==8.3.5 pytest-cov==6.0.0 requests==2.32.3 requests-mock==1.12.1 requests_download==0.1.2 six==1.17.0 -e git+https://github.com/streamlink/streamlink.git@e2a55461decc6856912325e8103cefb359027811#egg=streamlink tomli==2.2.1 traceback2==1.4.0 unittest2==1.1.0 urllib3==2.3.0 websocket-client==1.8.0 yarg==0.1.10
name: streamlink channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - codecov==2.1.13 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - iso-639==0.4.5 - iso3166==2.1.1 - jinja2==3.1.6 - linecache2==1.0.0 - markupsafe==3.0.2 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pycryptodome==3.22.0 - pynsist==2.8 - pysocks==1.7.1 - pytest==8.3.5 - pytest-cov==6.0.0 - requests==2.32.3 - requests-download==0.1.2 - requests-mock==1.12.1 - six==1.17.0 - tomli==2.2.1 - traceback2==1.4.0 - unittest2==1.1.0 - urllib3==2.3.0 - websocket-client==1.8.0 - yarg==0.1.10 prefix: /opt/conda/envs/streamlink
[ "tests/test_plugin_tf1.py::TestPluginTF1::test_can_handle_url" ]
[]
[ "tests/test_plugin_tf1.py::TestPluginTF1::test_can_handle_url_negative" ]
[]
BSD 2-Clause "Simplified" License
2,532
[ "src/streamlink/plugins/tf1.py" ]
[ "src/streamlink/plugins/tf1.py" ]
spyder-ide__qtsass-23
7e9855f2c7943bb5bec22629ab27b6cbec106f95
2018-05-16 16:56:38
77b25a562e774cf87bf8df3f5209f910dfabd78d
diff --git a/.gitignore b/.gitignore index 8943659..a2d1ea3 100644 --- a/.gitignore +++ b/.gitignore @@ -260,4 +260,7 @@ atlassian-ide-plugin.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties -crashlytics-build.properties \ No newline at end of file +crashlytics-build.properties + +# pytest +.pytest_cache diff --git a/examples/complex/_base.scss b/examples/complex/_base.scss new file mode 100644 index 0000000..957d676 --- /dev/null +++ b/examples/complex/_base.scss @@ -0,0 +1,4 @@ +@import 'defaults'; +@import 'widgets/qwidget'; +@import 'widgets/qpushbutton'; +@import 'widgets/qlineedit'; diff --git a/examples/complex/_defaults.scss b/examples/complex/_defaults.scss new file mode 100644 index 0000000..931feda --- /dev/null +++ b/examples/complex/_defaults.scss @@ -0,0 +1,13 @@ +// Fonts +$font-stack: Helvetica, sans-serif !default; + +// Colors +$background: rgb(255, 255, 255) !default; +$primary: rgb(35, 35, 35) !default; +$accent: rgb(35, 75, 135) !default; + +// Paddings +$text-padding: 16px 8px 16px 8px !default; + +// Borders +$border-radius: 2px !default; diff --git a/examples/complex/dark.scss b/examples/complex/dark.scss new file mode 100644 index 0000000..579b607 --- /dev/null +++ b/examples/complex/dark.scss @@ -0,0 +1,9 @@ +// Change default values + +$background: rgb(35, 35, 35); +$primary: rgb(255, 255, 255); + + +// Import base style + +@import 'base'; diff --git a/examples/complex/light.scss b/examples/complex/light.scss new file mode 100644 index 0000000..d71f710 --- /dev/null +++ b/examples/complex/light.scss @@ -0,0 +1,1 @@ +@import 'base'; diff --git a/examples/complex/widgets/_qlineedit.scss b/examples/complex/widgets/_qlineedit.scss new file mode 100644 index 0000000..0462da3 --- /dev/null +++ b/examples/complex/widgets/_qlineedit.scss @@ -0,0 +1,6 @@ +QLineEdit { + color: $primary; + padding: $text-padding; + border: 0; + border-bottom: 1px solid $primary; +} diff --git a/examples/complex/widgets/_qpushbutton.scss b/examples/complex/widgets/_qpushbutton.scss new file mode 100644 index 0000000..0207748 --- /dev/null +++ b/examples/complex/widgets/_qpushbutton.scss @@ -0,0 +1,13 @@ +QPushButton { + background: $background; + color: $accent; + padding: $text-padding; + border: 0; + border-radius: $border-radius; +} + +QPushButton:hover, +QPushButton:focus { + background: $accent; + color: $background; +} diff --git a/examples/complex/widgets/_qwidget.scss b/examples/complex/widgets/_qwidget.scss new file mode 100644 index 0000000..aae4685 --- /dev/null +++ b/examples/complex/widgets/_qwidget.scss @@ -0,0 +1,4 @@ +QWidget { + background: $background; + color: $primary; +} diff --git a/qtsass/__init__.py b/qtsass/__init__.py index f5c2fff..3c14623 100644 --- a/qtsass/__init__.py +++ b/qtsass/__init__.py @@ -11,7 +11,7 @@ from __future__ import absolute_import # Local imports -from qtsass.api import compile, compile_and_save +from qtsass.api import compile, compile_filename, compile_dirname, watch VERSION_INFO = (0, 1, 0) diff --git a/qtsass/__main__.py b/qtsass/__main__.py index 1d0dfce..317f82d 100644 --- a/qtsass/__main__.py +++ b/qtsass/__main__.py @@ -11,10 +11,11 @@ # Standard library imports from __future__ import absolute_import +import sys # Local imports from qtsass import cli if __name__ == '__main__': - cli.main() + cli.main(sys.argv[1:]) diff --git a/qtsass/api.py b/qtsass/api.py index 63e12cb..e224c7b 100644 --- a/qtsass/api.py +++ b/qtsass/api.py @@ -15,11 +15,13 @@ import os # Third party imports import sass +from watchdog.observers import Observer # Local imports from qtsass.conformers import scss_conform, qt_conform from qtsass.functions import qlineargradient, rgba from qtsass.importers import qss_importer +from qtsass.events import SourceEventHandler logging.basicConfig(level=logging.DEBUG) @@ -27,6 +29,8 @@ _log = logging.getLogger(__name__) def compile(input_file): + """Compile QtSASS to CSS.""" + _log.debug('Compiling {}...'.format(input_file)) with open(input_file, 'r') as f: @@ -50,11 +54,57 @@ def compile(input_file): return "" -def compile_and_save(input_file, dest_file): - stylesheet = compile(input_file) - if dest_file: - with open(dest_file, 'w') as css_file: - css_file.write(stylesheet) - _log.info('Created CSS file {}'.format(dest_file)) +def compile_filename(input_file, dest_file): + """Compile QtSASS to CSS and save.""" + + css = compile(input_file) + with open(dest_file, 'w') as css_file: + css_file.write(css) + _log.info('Created CSS file {}'.format(dest_file)) + + +def compile_dirname(input_dir, output_dir): + """Compiles QtSASS files in a directory including subdirectories.""" + + def is_valid(file): + return not file.startswith('_') and file.endswith('.scss') + + for root, subdirs, files in os.walk(input_dir): + relative_root = os.path.relpath(root, input_dir) + output_root = os.path.join(output_dir, relative_root) + + for file in [f for f in files if is_valid(f)]: + scss_path = os.path.join(root, file) + css_file = os.path.splitext(file)[0] + '.css' + css_path = os.path.join(output_root, css_file) + if not os.path.isdir(output_root): + os.makedirs(output_root) + compile_filename(scss_path, css_path) + + +def watch(source, destination, compiler=None, recursive=True): + """ + Watches a source file or directory, compiling QtSass files when modified. + + The compiler function defaults to compile_filename when source is a file + and compile_dirname when source is a directory. + + :param source: Path to source QtSass file or directory. + :param destination: Path to output css file or directory. + :param compiler: Compile function (optional) + :param recursive: If True, watch subdirectories (default: True). + :returns: watchdog.Observer + """ + + if os.path.isfile(source): + watch_dir = os.path.dirname(source) + compiler = compiler or compile_filename else: - print(stylesheet) + watch_dir = source + compiler = compiler or compile_dirname + + event_handler = SourceEventHandler(source, destination, compiler) + + observer = Observer() + observer.schedule(event_handler, watch_dir, recursive=recursive) + return observer diff --git a/qtsass/cli.py b/qtsass/cli.py index 7d60c62..5cc22c6 100644 --- a/qtsass/cli.py +++ b/qtsass/cli.py @@ -13,22 +13,20 @@ from __future__ import absolute_import, print_function import argparse import os +import sys import time import logging - -# Third party imports -from watchdog.observers import Observer +import signal # Local imports -from qtsass.api import compile_and_save -from qtsass.events import SourceModificationEventHandler +from qtsass.api import compile, compile_filename, compile_dirname, watch logging.basicConfig(level=logging.DEBUG) _log = logging.getLogger(__name__) -def main_parser(): +def create_parser(): """Create qtsass's cli parser.""" parser = argparse.ArgumentParser( @@ -51,23 +49,35 @@ def main_parser(): return parser -def main(): +def main(args): """qtsass's cli entry point.""" - args = main_parser().parse_args() - compile_and_save(args.input, args.output) + args = create_parser().parse_args(args) + file_mode = os.path.isfile(args.input) + dir_mode = os.path.isdir(args.input) + + if file_mode and not args.output: + css = compile(args.input) + print(css) + sys.exit(0) + + elif file_mode: + compile_filename(args.input, args.output) + + elif dir_mode and not args.output: + print('Error: missing required option: -o/--output') + sys.exit(1) + + elif dir_mode: + compile_dirname(args.input, args.output) + + else: + print('Error: input must be a file or a directory') + sys.exit(1) if args.watch: - watched_dir = os.path.abspath(os.path.dirname(args.input)) - event_handler = SourceModificationEventHandler( - args.input, - args.output, - watched_dir, - compile_and_save - ) _log.info('qtsass is watching {}...'.format(args.input)) - observer = Observer() - observer.schedule(event_handler, watched_dir, recursive=False) + observer = watch(args.input, args.output) observer.start() try: while True: @@ -75,3 +85,4 @@ def main(): except KeyboardInterrupt: observer.stop() observer.join() + sys.exit(0) diff --git a/qtsass/conformers.py b/qtsass/conformers.py index eae8a1e..a5d773d 100644 --- a/qtsass/conformers.py +++ b/qtsass/conformers.py @@ -6,7 +6,7 @@ # Licensed under the terms of the MIT License # (See LICENSE.txt for details) # ----------------------------------------------------------------------------- -"""Conform qss to compliant scss and css to valid qss.""" +"""Conform qss to compliant scss and css to valid qss.""" # Standard library imports from __future__ import absolute_import, print_function @@ -134,4 +134,5 @@ def qt_conform(input_str): conformed = input_str for conformer in conformers[::-1]: conformed = conformer.to_qss(conformed) + return conformed diff --git a/qtsass/events.py b/qtsass/events.py index 72ff73f..e10939e 100644 --- a/qtsass/events.py +++ b/qtsass/events.py @@ -8,54 +8,17 @@ # ----------------------------------------------------------------------------- """Source files event handler.""" -# Standard library imports -import os -import time - # Third party imports from watchdog.events import FileSystemEventHandler -# py2 has no FileNotFoundError -try: - FileNotFoundError -except NameError: - FileNotFoundError = IOError - - -class SourceModificationEventHandler(FileSystemEventHandler): +class SourceEventHandler(FileSystemEventHandler): - def __init__(self, input_file, dest_file, watched_dir, compiler): - super(SourceModificationEventHandler, self).__init__() - self._input_file = input_file - self._dest_file = dest_file + def __init__(self, source, destination, compiler): + super(SourceEventHandler, self).__init__() + self._source = source + self._destination = destination self._compiler = compiler - self._watched_dir = watched_dir - self._watched_extension = os.path.splitext(self._input_file)[1] - - def _recompile(self): - i = 0 - success = False - while i < 10 and not success: - try: - time.sleep(0.2) - self._compiler(self._input_file, self._dest_file) - success = True - except FileNotFoundError: - i += 1 def on_modified(self, event): - # On Mac, event will always be a directory. - # On Windows, only recompile if event's file - # has the same extension as the input file - we_should_recompile = ( - event.is_directory and - os.path.samefile(event.src_path, self._watched_dir) or - os.path.splitext(event.src_path)[1] == self._watched_extension - ) - if we_should_recompile: - self._recompile() - - def on_created(self, event): - if os.path.splitext(event.src_path)[1] == self._watched_extension: - self._recompile() + self._compiler(self._source, self._destination) diff --git a/qtsass/importers.py b/qtsass/importers.py index 5e8228a..e4bc7a5 100644 --- a/qtsass/importers.py +++ b/qtsass/importers.py @@ -16,6 +16,10 @@ import os from qtsass.conformers import scss_conform +def norm_path(*parts): + return os.path.normpath(os.path.join(*parts)) + + def qss_importer(where): """ Returns a function which conforms imported qss files to valid scss to be @@ -26,17 +30,29 @@ def qss_importer(where): def find_file(import_file): - if os.path.isfile(import_file): - return import_file - extensions = ['.scss', '.css', '.sass'] - for ext in extensions: - potential_file = import_file + ext - if os.path.isfile(potential_file): - return potential_file - potential_file = os.path.join(where, import_file + ext) + # Create partial import filename + dirname, basename = os.path.split(import_file) + if dirname: + import_partial_file = '/'.join([dirname, '_' + basename]) + else: + import_partial_file = '_' + basename + + # Build potential file paths for @import "import_file" + potential_files = [] + for ext in ['', '.scss', '.css', '.sass']: + full_name = import_file + ext + partial_name = import_partial_file + ext + potential_files.append(full_name) + potential_files.append(partial_name) + potential_files.append(norm_path(where, full_name)) + potential_files.append(norm_path(where, partial_name)) + + # Return first existing potential file + for potential_file in potential_files: if os.path.isfile(potential_file): return potential_file - return import_file + + return None def import_and_conform_file(import_file):
CLI - build/watch directory The current CLI only supports building and watching a single sass file. This may be suitable for small projects, but, large projects tend to have more varied structures. For example, a project may have a base stylesheet with dark and light variants. - /scss - _base.scss - dark.scss - light.scss To support the above scenario we should add a CLI option -d/--directory that will compile and watch for changes in all the scss files contained in the directory except for those starting with an underscore. The -d/--directory and the -f/--file options should be mutually exclusive raising an error when both are provided. When using the -d flag the -o flag specifies an output directory for the compiled css. Valid usages ``` qtsass -d scss -o css qtsass -d scss -o css -w qtsass -f scss/dark.scss -o css/dark.css qtsass -f scss/dark.scss -o css/dark.css -w ```
spyder-ide/qtsass
diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..28b8e43 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,205 @@ +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------- +# Copyright (c) 2015 Yann Lanthony +# Copyright (c) 2017-2018 Spyder Project Contributors +# +# Licensed under the terms of the MIT License +# (See LICENSE.txt for details) +# ----------------------------------------------------------------------------- +"""Test qtsass cli.""" + +# Standard library imports +from __future__ import absolute_import +import os +import time +import signal +import sys +from os.path import join, dirname, normpath, exists, basename +from textwrap import dedent +from subprocess import Popen, PIPE +from collections import namedtuple + + +PY3 = sys.version_info.major == 3 +PROJECT_DIR = normpath(dirname(dirname(__file__))) +Result = namedtuple('Result', "code stdout stderr") + + +def example(*paths): + """Get path to an example.""" + + return normpath(join(dirname(__file__), '..', 'examples', *paths)) + + +def touch(file): + """Touch a file.""" + + with open(file, 'a') as f: + os.utime(file, None) + + +def await_condition(condition, timeout=2000): + """Return True if a condition is met in the given timeout period""" + + for _ in range(timeout): + if condition(): + return True + time.sleep(0.001) + return False + + +def invoke(args): + """Invoke qtsass cli with specified args""" + + kwargs = dict( + stdout=PIPE, + stderr=PIPE, + cwd=PROJECT_DIR + ) + proc = Popen(['python', '-m', 'qtsass'] + args, **kwargs) + return proc + + +def invoke_with_result(args): + """Invoke qtsass cli and return a Result obj""" + + proc = invoke(args) + out, err = proc.communicate() + out = out.decode('ascii', errors="ignore") + err = err.decode('ascii', errors="ignore") + return Result(proc.returncode, out, err) + + +def test_compile_dummy_to_stdout(): + """CLI compile dummy example to stdout.""" + + args = [example('dummy.scss')] + result = invoke_with_result(args) + + assert result.code == 0 + assert result.stdout + + +def test_compile_dummy_to_file(tmpdir): + """CLI compile dummy example to file.""" + + input = example('dummy.scss') + output = tmpdir.join('dummy.css') + args = [input, '-o', output.strpath] + result = invoke_with_result(args) + + assert result.code == 0 + assert exists(output.strpath) + + +def test_watch_dummy(tmpdir): + """CLI watch dummy example.""" + + input = example('dummy.scss') + output = tmpdir.join('dummy.css') + args = [input, '-o', output.strpath, '-w'] + proc = invoke(args) + + # Wait for initial compile + output_exists = lambda: exists(output.strpath) + if not await_condition(output_exists): + proc.terminate() + assert False, "Failed to compile dummy.scss" + + # Ensure subprocess is still alive + assert proc.poll() is None + + # Touch input file, triggering a recompile + created = output.mtime() + file_modified = lambda: output.mtime() > created + time.sleep(0.1) + touch(input) + + if not await_condition(file_modified): + proc.terminate() + assert False, 'Output file has not been recompiled...' + + proc.terminate() + + +def test_compile_complex(tmpdir): + """CLI compile complex example.""" + + input = example('complex') + output = tmpdir.mkdir('output') + args = [input, '-o', output.strpath] + result = invoke_with_result(args) + + assert result.code == 0 + + expected_files = [output.join('light.css'), output.join('dark.css')] + for file in expected_files: + assert exists(file.strpath) + + +def test_watch_complex(tmpdir): + """CLI watch complex example.""" + + input = example('complex') + output = tmpdir.mkdir('output') + args = [input, '-o', output.strpath, '-w'] + proc = invoke(args) + + expected_files = [output.join('light.css'), output.join('dark.css')] + + # Wait for initial compile + files_created = lambda: all([exists(f.strpath) for f in expected_files]) + if not await_condition(files_created): + assert False, 'All expected files have not been created...' + + # Ensure subprocess is still alive + assert proc.poll() is None + + # Input files to touch + input_full = example('complex', 'light.scss') + input_partial = example('complex', '_base.scss') + input_nested = example('complex', 'widgets', '_qwidget.scss') + + def touch_and_wait(input_file, timeout=2000): + """Touch a file, triggering a recompile""" + + filename = basename(input_file) + old_mtimes = [f.mtime() for f in expected_files] + files_modified = lambda: all( + [f.mtime() > old_mtimes[i] for i, f in enumerate(expected_files)] + ) + time.sleep(0.1) + touch(input_file) + + if not await_condition(files_modified, timeout): + proc.terminate() + err = 'Modifying %s did not trigger recompile.' % filename + assert False, err + + return True + + assert touch_and_wait(input_full) + assert touch_and_wait(input_partial) + assert touch_and_wait(input_nested) + + proc.terminate() + + +def test_invalid_input(): + """CLI input is not a file or dir.""" + + proc = invoke_with_result(['file_does_not_exist.scss']) + assert proc.code == 1 + assert 'Error: input must be' in proc.stdout + + proc = invoke_with_result(['./dir/does/not/exist']) + assert proc.code == 1 + assert 'Error: input must be' in proc.stdout + + +def test_dir_missing_output(): + """CLI dir missing output option""" + + proc = invoke_with_result([example('complex')]) + assert proc.code == 1 + assert 'Error: missing required option' in proc.stdout diff --git a/tests/test_conformers.py b/tests/test_conformers.py index e77fc4d..22299a0 100644 --- a/tests/test_conformers.py +++ b/tests/test_conformers.py @@ -6,7 +6,7 @@ # Licensed under the terms of the MIT License # (See LICENSE.txt for details) # ----------------------------------------------------------------------------- -"""Test suite for qtsass.""" +"""Test qtsass conformers.""" # Standard library imports from __future__ import absolute_import
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 8 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 libsass==0.23.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 -e git+https://github.com/spyder-ide/qtsass.git@7e9855f2c7943bb5bec22629ab27b6cbec106f95#egg=qtsass tomli==2.2.1 watchdog==6.0.0
name: qtsass channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - libsass==0.23.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 - watchdog==6.0.0 prefix: /opt/conda/envs/qtsass
[ "tests/test_cli.py::test_compile_complex", "tests/test_cli.py::test_watch_complex", "tests/test_cli.py::test_invalid_input", "tests/test_cli.py::test_dir_missing_output" ]
[]
[ "tests/test_cli.py::test_compile_dummy_to_stdout", "tests/test_cli.py::test_compile_dummy_to_file", "tests/test_cli.py::test_watch_dummy", "tests/test_conformers.py::TestNotConformer::test_conform_to_qss", "tests/test_conformers.py::TestNotConformer::test_conform_to_scss", "tests/test_conformers.py::TestNotConformer::test_round_trip", "tests/test_conformers.py::TestQLinearGradientConformer::test_conform_multiline_str", "tests/test_conformers.py::TestQLinearGradientConformer::test_conform_nostops_str", "tests/test_conformers.py::TestQLinearGradientConformer::test_conform_singleline_str", "tests/test_conformers.py::TestQLinearGradientConformer::test_conform_vars_str", "tests/test_conformers.py::TestQLinearGradientConformer::test_conform_weird_whitespace_str", "tests/test_conformers.py::TestQLinearGradientConformer::test_does_not_affect_css_form" ]
[]
MIT License
2,533
[ "qtsass/conformers.py", "examples/complex/widgets/_qpushbutton.scss", "qtsass/importers.py", "examples/complex/widgets/_qlineedit.scss", "examples/complex/widgets/_qwidget.scss", "examples/complex/_defaults.scss", "qtsass/api.py", "examples/complex/light.scss", ".gitignore", "examples/complex/_base.scss", "qtsass/cli.py", "qtsass/__main__.py", "examples/complex/dark.scss", "qtsass/__init__.py", "qtsass/events.py" ]
[ "qtsass/conformers.py", "examples/complex/widgets/_qpushbutton.scss", "qtsass/importers.py", "examples/complex/widgets/_qlineedit.scss", "examples/complex/widgets/_qwidget.scss", "examples/complex/_defaults.scss", "qtsass/api.py", "examples/complex/light.scss", ".gitignore", "examples/complex/_base.scss", "qtsass/cli.py", "qtsass/__main__.py", "examples/complex/dark.scss", "qtsass/__init__.py", "qtsass/events.py" ]
Yelp__swagger_spec_validator-93
40e1cc926775777ff2d56e271fd61697c6235579
2018-05-16 17:24:26
40e1cc926775777ff2d56e271fd61697c6235579
diff --git a/swagger_spec_validator/validator20.py b/swagger_spec_validator/validator20.py index fe17ded..77920c1 100644 --- a/swagger_spec_validator/validator20.py +++ b/swagger_spec_validator/validator20.py @@ -7,6 +7,7 @@ from __future__ import unicode_literals import functools import logging import string +from collections import defaultdict from jsonschema.validators import Draft4Validator from jsonschema.validators import RefResolver @@ -196,6 +197,8 @@ def validate_apis(apis, deref): :raises: :py:class:`swagger_spec_validator.SwaggerValidationError` :raises: :py:class:`jsonschema.exceptions.ValidationError` """ + operation_tag_to_operation_id_set = defaultdict(set) + for api_name, api_body in iteritems(apis): api_body = deref(api_body) api_params = deref(api_body.get('parameters', [])) @@ -206,6 +209,20 @@ def validate_apis(apis, deref): if oper_name == 'parameters' or oper_name.startswith('x-'): continue oper_body = deref(api_body[oper_name]) + oper_tags = deref(oper_body.get('tags', [None])) + + # Check that, if this operation has an operationId defined, + # no other operation with a same tag also has that + # operationId. + operation_id = oper_body.get('operationId') + if operation_id is not None: + for oper_tag in oper_tags: + if operation_id in operation_tag_to_operation_id_set[oper_tag]: + raise SwaggerValidationError( + "Duplicate operationId: {}".format(operation_id) + ) + operation_tag_to_operation_id_set[oper_tag].add(operation_id) + oper_params = deref(oper_body.get('parameters', [])) validate_duplicate_param(oper_params, deref) all_path_params = list(set(
Validator does not check uniqueness of operation ids According to the Swagger spec, the `operationId` of an operation object is: > Unique string used to identify the operation. The id MUST be unique among all operations described in the API. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is recommended to follow common programming naming conventions. The validator does not currently check that `operationId`s are unique across the API. This would be a helpful feature because some codegen tools fail if this constraint is not met.
Yelp/swagger_spec_validator
diff --git a/tests/validator20/validate_apis_test.py b/tests/validator20/validate_apis_test.py index 56f1e14..d1198d6 100644 --- a/tests/validator20/validate_apis_test.py +++ b/tests/validator20/validate_apis_test.py @@ -152,3 +152,91 @@ def test_api_check_default_fails(partial_parameter_spec, validator, instance): validation_error = excinfo.value.args[1] assert validation_error.instance == instance assert validation_error.validator == validator + + [email protected]( + 'apis', + [ + { + '/api': { + 'get': { + 'operationId': 'duplicateOperationId', + 'responses': {}, + }, + 'post': { + 'operationId': 'duplicateOperationId', + 'responses': {}, + }, + }, + }, + { + '/api1': { + 'get': { + 'operationId': 'duplicateOperationId', + 'responses': {}, + }, + }, + '/api2': { + 'get': { + 'operationId': 'duplicateOperationId', + 'responses': {}, + }, + }, + }, + { + '/api1': { + 'get': { + 'operationId': 'duplicateOperationId', + 'tags': ['tag1', 'tag2'], + 'responses': {}, + }, + }, + '/api2': { + 'get': { + 'operationId': 'duplicateOperationId', + 'tags': ['tag1'], + 'responses': {}, + }, + }, + }, + ] +) +def test_duplicate_operationIds_fails(apis): + with pytest.raises(SwaggerValidationError) as excinfo: + validate_apis(apis, lambda x: x) + + swagger_validation_error = excinfo.value + error_message = swagger_validation_error.args[0] + + assert error_message == "Duplicate operationId: duplicateOperationId" + + [email protected]( + 'apis', + [ + { + '/api1': { + 'get': { + 'operationId': 'duplicateOperationId', + 'tags': ['tag1'], + 'responses': {}, + }, + }, + '/api2': { + 'get': { + 'operationId': 'duplicateOperationId', + 'tags': ['tag2'], + 'responses': {}, + }, + }, + '/api3': { + 'get': { + 'operationId': 'duplicateOperationId', + 'responses': {}, + }, + }, + }, + ] +) +def test_duplicate_operationIds_succeeds_if_tags_differ(apis): + validate_apis(apis, lambda x: x) diff --git a/tests/validator20/validate_rich_spec_test.py b/tests/validator20/validate_rich_spec_test.py index 593b9c0..0f5df04 100644 --- a/tests/validator20/validate_rich_spec_test.py +++ b/tests/validator20/validate_rich_spec_test.py @@ -36,10 +36,11 @@ def test_failure_on_duplicate_operation_parameters(swagger_spec): def test_failure_on_unresolvable_path_parameter(swagger_spec): - swagger_spec['paths']['/pet/{foo}'] = swagger_spec['paths']['/pet'] + swagger_spec['paths']['/pet/{petId}']['get']['parameters'] = [] + with pytest.raises(SwaggerValidationError) as exc_info: validate_spec(swagger_spec) - assert "Path parameter 'foo' used is not documented on '/pet/{foo}'" in str(exc_info.value) + assert "Path parameter 'petId' used is not documented on '/pet/{petId}'" in str(exc_info.value) def test_failure_on_path_parameter_used_but_not_defined(swagger_spec):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": null, "python": "3.6", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 httpretty==1.1.4 importlib-metadata==4.8.3 iniconfig==1.1.1 jsonschema==3.2.0 mock==5.2.0 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 -e git+https://github.com/Yelp/swagger_spec_validator.git@40e1cc926775777ff2d56e271fd61697c6235579#egg=swagger_spec_validator tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: swagger_spec_validator channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - httpretty==1.1.4 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jsonschema==3.2.0 - mock==5.2.0 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/swagger_spec_validator
[ "tests/validator20/validate_apis_test.py::test_duplicate_operationIds_fails[apis0]", "tests/validator20/validate_apis_test.py::test_duplicate_operationIds_fails[apis1]", "tests/validator20/validate_apis_test.py::test_duplicate_operationIds_fails[apis2]" ]
[ "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec0]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec1]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec2]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec3]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec4]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec5]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec6]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec7]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec8]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec9]", "tests/validator20/validate_apis_test.py::test_api_check_default_succeed[partial_parameter_spec10]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec0-type-wrong_type]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec1-type-wrong_type]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec2-type-wrong_type]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec3-type-wrong_type]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec4-type-wrong_type]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec5-type-wrong_type]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec6-type--1]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec7-minLength-short_string]", "tests/validator20/validate_apis_test.py::test_api_check_default_fails[partial_parameter_spec8-type-not_a_number_or_boolean]", "tests/validator20/validate_rich_spec_test.py::test_failure_on_duplicate_api_parameters", "tests/validator20/validate_rich_spec_test.py::test_failure_on_duplicate_operation_parameters", "tests/validator20/validate_rich_spec_test.py::test_failure_on_unresolvable_path_parameter", "tests/validator20/validate_rich_spec_test.py::test_failure_on_path_parameter_used_but_not_defined", "tests/validator20/validate_rich_spec_test.py::test_failure_on_unresolvable_ref_of_props_required_list" ]
[ "tests/validator20/validate_apis_test.py::test_api_level_params_ok", "tests/validator20/validate_apis_test.py::test_api_level_x_hyphen_ok", "tests/validator20/validate_apis_test.py::test_duplicate_operationIds_succeeds_if_tags_differ[apis0]", "tests/validator20/validate_rich_spec_test.py::test_failure_on_unresolvable_model_reference_from_model", "tests/validator20/validate_rich_spec_test.py::test_failure_on_unresolvable_model_reference_from_param", "tests/validator20/validate_rich_spec_test.py::test_failure_on_unresolvable_model_reference_from_resp" ]
[]
Apache License 2.0
2,534
[ "swagger_spec_validator/validator20.py" ]
[ "swagger_spec_validator/validator20.py" ]
Azure__iotedgedev-173
ce59bad1286bf650d442b2b7fbe16a3db676a497
2018-05-16 17:52:55
a22c7b0c59505964c5aeab6f8ff859842783c236
diff --git a/iotedgedev/azurecli.py b/iotedgedev/azurecli.py index c5bce70..6bce331 100644 --- a/iotedgedev/azurecli.py +++ b/iotedgedev/azurecli.py @@ -226,10 +226,10 @@ class AzureCli: return result - def apply_configuration(self, deviceId, connection_string, config): - self.output.status(f("Deploying '{config}' to '{deviceId}'...")) + def apply_configuration(self, device_id, connection_string, hub_name, config): + self.output.status(f("Deploying '{config}' to '{device_id}'...")) - return self.invoke_az_cli_outproc(["iot", "hub", "apply-configuration", "-d", deviceId, "-k", config, "-l", connection_string], error_message=f("Failed to deploy '{config}' to '{deviceId}'..."), suppress_output=True) + return self.invoke_az_cli_outproc(["iot", "hub", "apply-configuration", "-d", device_id, "-n", hub_name, "-k", config, "-l", connection_string], error_message=f("Failed to deploy '{config}' to '{device_id}'..."), suppress_output=True) def get_free_iothub(self): with output_io_cls() as io: diff --git a/iotedgedev/connectionstring.py b/iotedgedev/connectionstring.py index cc29b68..2c8c19e 100644 --- a/iotedgedev/connectionstring.py +++ b/iotedgedev/connectionstring.py @@ -1,10 +1,10 @@ class ConnectionString: def __init__(self, value): - self.value = value + self.ConnectionString = value self.data = dict() - if self.value: - parts = value.split(';') + if self.ConnectionString: + parts = self.ConnectionString.split(';') if len(parts) > 0: for part in parts: subpart = part.split('=', 1) @@ -13,6 +13,8 @@ class ConnectionString: if self.data: self.HostName = self["hostname"] + if self.HostName: + self.HubName = self.HostName.split('.')[0] self.SharedAccessKey = self["sharedaccesskey"] def __getitem__(self, key): @@ -23,7 +25,7 @@ class IoTHubConnectionString(ConnectionString): def __init__(self, value): ConnectionString.__init__(self, value) - if self.value: + if self.ConnectionString: self.SharedAccessKeyName = self["sharedaccesskeyname"] @@ -31,5 +33,5 @@ class DeviceConnectionString(ConnectionString): def __init__(self, value): ConnectionString.__init__(self, value) - if self.value: + if self.ConnectionString: self.DeviceId = self["deviceid"] diff --git a/iotedgedev/edge.py b/iotedgedev/edge.py index 6e71ba0..4d20943 100644 --- a/iotedgedev/edge.py +++ b/iotedgedev/edge.py @@ -10,11 +10,11 @@ class Edge: self.output.header("DEPLOYING CONFIGURATION") - self.envvars.verify_envvar_has_val("IOTHUB_CONNECTION_STRING", self.envvars.IOTHUB_CONNECTION_STRING) - self.envvars.verify_envvar_has_val("DEVICE_CONNECTION_STRING", self.envvars.DEVICE_CONNECTION_STRING) + self.envvars.verify_envvar_has_val("IOTHUB_CONNECTION_INFO", self.envvars.IOTHUB_CONNECTION_INFO) + self.envvars.verify_envvar_has_val("DEVICE_CONNECTION_INFO", self.envvars.DEVICE_CONNECTION_INFO) self.envvars.verify_envvar_has_val("DEPLOYMENT_CONFIG_FILE", self.envvars.DEPLOYMENT_CONFIG_FILE) - self.azure_cli.apply_configuration(self.envvars.DEVICE_CONNECTION_INFO.DeviceId, self.envvars.IOTHUB_CONNECTION_STRING, self.envvars.DEPLOYMENT_CONFIG_FILE_PATH) + self.azure_cli.apply_configuration(self.envvars.DEVICE_CONNECTION_INFO.DeviceId, self.envvars.IOTHUB_CONNECTION_INFO.ConnectionString, self.envvars.IOTHUB_CONNECTION_INFO.HubName, self.envvars.DEPLOYMENT_CONFIG_FILE_PATH) self.output.footer("DEPLOYMENT COMPLETE") \ No newline at end of file
AZ IOT HUB apply-configuration needs hubname. If user has old version of az cli iot extension installed they get this: `az iot hub apply-configuration: error: argument --hub-name/-n is required ` - add the -n parameter to the apply-configuration call. you can get it in IOTHUB_CONNECTION_INFO.HostName apply-configuration might need ONLY hubname, but HostName has [name].azuredevices.net. Therefore, You might have to split the ConnectionString.HostName property and add a new property to that class called HubName.
Azure/iotedgedev
diff --git a/tests/test_connectionstring.py b/tests/test_connectionstring.py new file mode 100644 index 0000000..21d0dc9 --- /dev/null +++ b/tests/test_connectionstring.py @@ -0,0 +1,78 @@ +import os +import pytest +from dotenv import load_dotenv +from iotedgedev.connectionstring import ConnectionString, IoTHubConnectionString, DeviceConnectionString + +emptystring = "" +valid_connectionstring = "HostName=testhub.azure-devices.net;SharedAccessKey=gibberish" +valid_iothub_connectionstring = "HostName=testhub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=moregibberish" +valid_device_connectionstring = "HostName=testhub.azure-devices.net;DeviceId=testdevice;SharedAccessKey=othergibberish" +invalid_connectionstring = "HostName=azure-devices.net;SharedAccessKey=gibberish" +invalid_iothub_connectionstring = "HostName=testhub.azure-devices.net;SharedAccessKey=moregibberish" +invalid_device_connectionstring = "HostName=testhub.azure-devices.net;DeviceId=;SharedAccessKey=othergibberish" + +def test_empty_connectionstring(): + connectionstring = ConnectionString(emptystring) + assert not connectionstring.data + +def test_empty_iothub_connectionstring(): + connectionstring = IoTHubConnectionString(emptystring) + assert not connectionstring.data + +def test_empty_device_connectionstring(): + connectionstring = DeviceConnectionString(emptystring) + assert not connectionstring.data + +def test_valid_connectionstring(): + connectionstring = ConnectionString(valid_connectionstring) + assert connectionstring.HostName == "testhub.azure-devices.net" + assert connectionstring.HubName == "testhub" + assert connectionstring.SharedAccessKey == "gibberish" + +def test_valid_iothub_connectionstring(): + connectionstring = IoTHubConnectionString(valid_iothub_connectionstring) + assert connectionstring.HostName == "testhub.azure-devices.net" + assert connectionstring.HubName == "testhub" + assert connectionstring.SharedAccessKeyName == "iothubowner" + assert connectionstring.SharedAccessKey == "moregibberish" + +def test_valid_devicehub_connectionstring(): + connectionstring = DeviceConnectionString(valid_device_connectionstring) + assert connectionstring.HostName == "testhub.azure-devices.net" + assert connectionstring.HubName == "testhub" + assert connectionstring.DeviceId == "testdevice" + assert connectionstring.SharedAccessKey == "othergibberish" + +def test_invalid_connectionstring(): + connectionstring = ConnectionString(invalid_connectionstring) + assert connectionstring.HubName != "testhub" + +def test_invalid_iothub_connectionstring(): + with pytest.raises(KeyError): + IoTHubConnectionString(invalid_iothub_connectionstring) + +def test_invalid_devicehub_connectionstring(): + connectionstring = DeviceConnectionString(invalid_device_connectionstring) + assert connectionstring.HostName == "testhub.azure-devices.net" + assert connectionstring.HubName == "testhub" + assert not connectionstring.DeviceId + assert connectionstring.SharedAccessKey == "othergibberish" + +def test_valid_env_iothub_connectionstring(): + load_dotenv(".env") + env_iothub_connectionstring = os.getenv("IOTHUB_CONNECTION_STRING") + connectionstring = IoTHubConnectionString(env_iothub_connectionstring) + assert connectionstring.HostName + assert connectionstring.HubName + assert connectionstring.SharedAccessKey + assert connectionstring.SharedAccessKeyName + +def test_valid_env_device_connectionstring(): + load_dotenv(".env") + env_device_connectionstring = os.getenv("DEVICE_CONNECTION_STRING") + connectionstring = DeviceConnectionString(env_device_connectionstring) + assert connectionstring.HostName + assert connectionstring.HubName + assert connectionstring.SharedAccessKey + assert connectionstring.DeviceId + \ No newline at end of file diff --git a/tests/test_iotedgedev.py b/tests/test_iotedgedev.py index 2d08bad..c809c15 100644 --- a/tests/test_iotedgedev.py +++ b/tests/test_iotedgedev.py @@ -153,7 +153,7 @@ def test_monitor(request, capfd): print (err) print (result.output) - assert 'application properties' in out + assert 'timeCreated' in out @pytest.fixture
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 3 }
0.79
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
adal==1.2.7 applicationinsights==0.11.10 argcomplete==1.12.3 attrs==22.2.0 azure-cli==2.40.0 azure-cli-cloud==2.1.1 azure-cli-command-modules-nspkg==2.0.3 azure-cli-configure==2.0.24 azure-cli-core==2.40.0 azure-cli-extension==0.2.5 azure-cli-iot==0.3.11 azure-cli-nspkg==3.0.4 azure-cli-profile==2.1.5 azure-cli-resource==2.1.16 azure-cli-telemetry==1.0.8 azure-common==1.1.28 azure-core==1.24.2 azure-iot-edge-runtime-ctl==1.0.0rc22 azure-mgmt-authorization==0.50.0 azure-mgmt-core==1.3.2 azure-mgmt-iothub==0.8.2 azure-mgmt-iothubprovisioningservices==0.2.0 azure-mgmt-managementgroups==0.1.0 azure-mgmt-nspkg==3.0.2 azure-nspkg==3.0.2 bcrypt==4.0.1 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 click==8.0.4 cryptography==39.0.2 docker==3.0.0 docker-pycreds==0.4.0 enum34==1.1.10 fstrings==0.1.0 humanfriendly==10.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/Azure/iotedgedev.git@ce59bad1286bf650d442b2b7fbe16a3db676a497#egg=iotedgedev isodate==0.6.1 jmespath==0.10.0 knack==0.10.1 msal==1.18.0b1 msal-extensions==1.0.0 msrest==0.7.1 msrestazure==0.6.4.post1 oauthlib==3.2.2 packaging==21.3 paramiko==2.12.0 pkginfo==1.10.0 pluggy==1.0.0 portalocker==2.7.0 psutil==5.9.8 py==1.11.0 pycparser==2.21 Pygments==2.14.0 PyJWT==2.4.0 PyNaCl==1.5.0 pyOpenSSL==23.2.0 pyparsing==3.1.4 PySocks==1.7.1 pytest==7.0.1 python-dateutil==2.9.0.post0 python-dotenv==0.20.0 PyYAML==6.0.1 requests==2.27.1 requests-oauthlib==2.0.0 six==1.17.0 tabulate==0.8.10 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 websocket-client==1.3.1 zipp==3.6.0
name: iotedgedev channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - adal==1.2.7 - applicationinsights==0.11.10 - argcomplete==1.12.3 - attrs==22.2.0 - azure-cli==2.40.0 - azure-cli-cloud==2.1.1 - azure-cli-command-modules-nspkg==2.0.3 - azure-cli-configure==2.0.24 - azure-cli-core==2.40.0 - azure-cli-extension==0.2.5 - azure-cli-iot==0.3.11 - azure-cli-nspkg==3.0.4 - azure-cli-profile==2.1.5 - azure-cli-resource==2.1.16 - azure-cli-telemetry==1.0.8 - azure-common==1.1.28 - azure-core==1.24.2 - azure-iot-edge-runtime-ctl==1.0.0rc22 - azure-mgmt-authorization==0.50.0 - azure-mgmt-core==1.3.2 - azure-mgmt-iothub==0.8.2 - azure-mgmt-iothubprovisioningservices==0.2.0 - azure-mgmt-managementgroups==0.1.0 - azure-mgmt-nspkg==3.0.2 - azure-nspkg==3.0.2 - bcrypt==4.0.1 - cffi==1.15.1 - charset-normalizer==2.0.12 - click==8.0.4 - cryptography==39.0.2 - docker==3.0.0 - docker-pycreds==0.4.0 - enum34==1.1.10 - fstrings==0.1.0 - humanfriendly==10.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isodate==0.6.1 - jmespath==0.10.0 - knack==0.10.1 - msal==1.18.0b1 - msal-extensions==1.0.0 - msrest==0.7.1 - msrestazure==0.6.4.post1 - oauthlib==3.2.2 - packaging==21.3 - paramiko==2.12.0 - pkginfo==1.10.0 - pluggy==1.0.0 - portalocker==2.7.0 - psutil==5.9.8 - py==1.11.0 - pycparser==2.21 - pygments==2.14.0 - pyjwt==2.4.0 - pynacl==1.5.0 - pyopenssl==23.2.0 - pyparsing==3.1.4 - pysocks==1.7.1 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - python-dotenv==0.20.0 - pyyaml==6.0.1 - requests==2.27.1 - requests-oauthlib==2.0.0 - six==1.17.0 - tabulate==0.8.10 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - websocket-client==1.3.1 - zipp==3.6.0 prefix: /opt/conda/envs/iotedgedev
[ "tests/test_connectionstring.py::test_valid_connectionstring", "tests/test_connectionstring.py::test_valid_iothub_connectionstring", "tests/test_connectionstring.py::test_valid_devicehub_connectionstring", "tests/test_connectionstring.py::test_invalid_connectionstring", "tests/test_connectionstring.py::test_invalid_devicehub_connectionstring" ]
[ "tests/test_connectionstring.py::test_valid_env_iothub_connectionstring", "tests/test_connectionstring.py::test_valid_env_device_connectionstring" ]
[ "tests/test_connectionstring.py::test_empty_connectionstring", "tests/test_connectionstring.py::test_empty_iothub_connectionstring", "tests/test_connectionstring.py::test_empty_device_connectionstring", "tests/test_connectionstring.py::test_invalid_iothub_connectionstring" ]
[]
MIT License
2,535
[ "iotedgedev/connectionstring.py", "iotedgedev/azurecli.py", "iotedgedev/edge.py" ]
[ "iotedgedev/connectionstring.py", "iotedgedev/azurecli.py", "iotedgedev/edge.py" ]
cekit__cekit-226
7067fb770515c44b28d661fddb5d0f25f706baf3
2018-05-17 10:40:18
69d214d02d424956a1951dec7dea4a61aeb77a62
diff --git a/bash_completion/cekit b/bash_completion/cekit index e1465c3..ec29995 100755 --- a/bash_completion/cekit +++ b/bash_completion/cekit @@ -7,6 +7,7 @@ _cekit_global_options() options+='--overrides ' options+='--target ' options+='--descriptor ' + options+='--work-dir ' echo "$options" } @@ -53,6 +54,10 @@ _cekit_complete() _filedir -d return + elif [[ '--work-dir' == $prev ]]; then + _filedir -d + return + elif [[ 'build generate' =~ .*$prev.* ]]; then local options options+=$(_cekit_global_options) diff --git a/cekit/cli.py b/cekit/cli.py index 55f9dd6..922d488 100644 --- a/cekit/cli.py +++ b/cekit/cli.py @@ -54,6 +54,11 @@ class Cekit(object): action='store_true', help='Set default options for Red Hat internal infrasructure.') + parser.add_argument('--work-dir', + dest='work_dir', + help="Location of cekit working directory, it's " + "used to store dist-git repos.") + test_group = parser.add_argument_group('test', "Arguments valid for the 'test' target") @@ -165,6 +170,8 @@ class Cekit(object): if self.args.redhat: tools.cfg['common']['redhat'] = True + if self.args.work_dir: + tools.cfg['common']['work_dir'] = self.args.work_dir # We need to construct Generator first, because we need overrides # merged in diff --git a/docs/build.rst b/docs/build.rst index 78d1f6d..1a466e6 100644 --- a/docs/build.rst +++ b/docs/build.rst @@ -20,6 +20,7 @@ You can execute an container image build by running: * ``--tag`` -- an image tag used to build image (can be specified multiple times) * ``--redhat`` -- build image using Red Hat defaults. See :ref:`Configuration section for Red Hat specific options<redhat_config>` for additional details. +* ``--work-dir`` -- sets Cekit works directory where dist_git repositories are cloned into See :ref:`Configuration section for work_dir<workdir_config>` * ``--build-engine`` -- a builder engine to use ``osbs``, ``buildah`` or ``docker`` [#f1]_ * ``--build-pull`` -- ask a builder engine to check and fetch latest base image * ``--build-osbs-stage`` -- use ``rhpkg-stage`` tool instead of ``rhpkg`` diff --git a/docs/configuration.rst b/docs/configuration.rst index dc1a6ca..645cc78 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -18,12 +18,20 @@ Below you can find description of available sections together with options descr ``common`` ------------ +.. _workdir_config: + ``work_dir`` ^^^^^^^^^^^^ Contains location of Cekit working directory, which is used to store some persistent data like dist_git repositories. +.. code:: yaml + + [common] + work_dir=/tmp + + ``ssl_verify`` ^^^^^^^^^^^^^^
Make it possible to specify where dist-git repositories should be cloned It is important so we do not reuse the same directories when running in parallel.
cekit/cekit
diff --git a/tests/test_unit_args.py b/tests/test_unit_args.py index fdb2042..6c5a555 100644 --- a/tests/test_unit_args.py +++ b/tests/test_unit_args.py @@ -81,6 +81,15 @@ def test_args_config_default(mocker): assert Cekit().parse().args.config == '~/.cekit/config' +def test_args_workd_dir(mocker): + mocker.patch.object(sys, 'argv', ['cekit', + 'generate', + '--work-dir', + 'foo']) + + assert Cekit().parse().args.work_dir == 'foo' + + def test_args_config(mocker): mocker.patch.object(sys, 'argv', ['cekit', '--config',
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 4 }
2.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "behave", "docker", "lxml", "mock", "pytest", "pytest-cov", "pytest-mock", "pykwalify" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
behave==1.2.6 -e git+https://github.com/cekit/cekit.git@7067fb770515c44b28d661fddb5d0f25f706baf3#egg=cekit certifi==2025.1.31 charset-normalizer==3.4.1 colorlog==6.9.0 coverage==7.8.0 docker==7.1.0 docopt==0.6.2 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 Jinja2==3.1.6 lxml==5.3.1 MarkupSafe==3.0.2 mock==5.2.0 packaging==24.2 parse==1.20.2 parse_type==0.6.4 pluggy==1.5.0 pykwalify==1.8.0 pytest==8.3.5 pytest-cov==6.0.0 pytest-mock==3.14.0 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 ruamel.yaml==0.18.10 ruamel.yaml.clib==0.2.12 six==1.17.0 tomli==2.2.1 urllib3==2.3.0
name: cekit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - behave==1.2.6 - certifi==2025.1.31 - charset-normalizer==3.4.1 - colorlog==6.9.0 - coverage==7.8.0 - docker==7.1.0 - docopt==0.6.2 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - jinja2==3.1.6 - lxml==5.3.1 - markupsafe==3.0.2 - mock==5.2.0 - packaging==24.2 - parse==1.20.2 - parse-type==0.6.4 - pluggy==1.5.0 - pykwalify==1.8.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - ruamel-yaml==0.18.10 - ruamel-yaml-clib==0.2.12 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/cekit
[ "tests/test_unit_args.py::test_args_workd_dir" ]
[]
[ "tests/test_unit_args.py::test_args_command[generate]", "tests/test_unit_args.py::test_args_command[build]", "tests/test_unit_args.py::test_args_command[test]", "tests/test_unit_args.py::test_args_not_valid_command", "tests/test_unit_args.py::test_args_tags[tags0-build_tags0-expected0]", "tests/test_unit_args.py::test_args_tags[tags1-build_tags1-expected1]", "tests/test_unit_args.py::test_args_tags[tags2-build_tags2-expected2]", "tests/test_unit_args.py::test_args_tags[tags3-build_tags3-expected3]", "tests/test_unit_args.py::test_args_build_pull", "tests/test_unit_args.py::test_args_build_engine[osbs]", "tests/test_unit_args.py::test_args_build_engine[docker]", "tests/test_unit_args.py::test_args_build_engine[buildah]", "tests/test_unit_args.py::test_args_osbs_stage", "tests/test_unit_args.py::test_args_osbs_stage_false", "tests/test_unit_args.py::test_args_invalid_build_engine", "tests/test_unit_args.py::test_args_osbs_user", "tests/test_unit_args.py::test_args_config_default", "tests/test_unit_args.py::test_args_config", "tests/test_unit_args.py::test_args_target", "tests/test_unit_args.py::test_args_redhat", "tests/test_unit_args.py::test_args_redhat_default", "tests/test_unit_args.py::test_args_osbs_nowait", "tests/test_unit_args.py::test_args_osbs_no_nowait" ]
[]
MIT License
2,536
[ "cekit/cli.py", "docs/build.rst", "bash_completion/cekit", "docs/configuration.rst" ]
[ "cekit/cli.py", "docs/build.rst", "bash_completion/cekit", "docs/configuration.rst" ]
python-useful-helpers__logwrap-21
1e040b43e3053f54f74a0b3ec95526e4430425b3
2018-05-17 11:17:03
f31146e46482f95dcf003432b96844edd4d3ceb7
diff --git a/README.rst b/README.rst index 7d46a7e..03d3821 100644 --- a/README.rst +++ b/README.rst @@ -116,7 +116,7 @@ Get decorator for use without parameters: Call example: -.. code-block:: python3 +.. code-block:: python import logwrap @@ -140,18 +140,18 @@ This code during execution will produce log records: Calling: 'example_function1'( # POSITIONAL_OR_KEYWORD: - 'arg1'=u'''arg1''', - 'arg2'=u'''arg2''', + 'arg1'=u'''arg1''', # type: <class 'str'> + 'arg2'=u'''arg2''', # type: <class 'str'> # VAR_POSITIONAL: 'args'=(), # KEYWORD_ONLY: - 'kwarg1'=u'''kwarg1''', - 'kwarg2'=u'''kwarg2''', + 'kwarg1'=u'''kwarg1''', # type: <class 'str'> + 'kwarg2'=u'''kwarg2''', # type: <class 'str'> # VAR_KEYWORD: 'kwargs'= - dict({ + dict({ 'kwarg3': u'''kwarg3''', - }), + }), ) Done: 'example_function1' with result: diff --git a/logwrap/_log_wrap_shared.py b/logwrap/_log_wrap_shared.py index 274454c..0e076ed 100644 --- a/logwrap/_log_wrap_shared.py +++ b/logwrap/_log_wrap_shared.py @@ -49,7 +49,7 @@ logger = logging.getLogger(__name__) # type: logging.Logger indent = 4 -fmt = "\n{spc:<{indent}}{{key!r}}={{val}},".format( +fmt = "\n{spc:<{indent}}{{key!r}}={{val}},{{annotation}}".format( spc='', indent=indent, ).format @@ -580,8 +580,14 @@ class BaseLogWrap(_class_decorator.BaseDecorator): param_str += comment(kind=param.kind) last_kind = param.kind + if param.empty == param.annotation: + annotation = "" + else: + annotation = " # type: {param.annotation!s}".format(param=param) + param_str += fmt( key=param.name, + annotation=annotation, val=val, ) if param_str: diff --git a/logwrap/_log_wrap_shared.pyi b/logwrap/_log_wrap_shared.pyi index 88102d5..37b2880 100644 --- a/logwrap/_log_wrap_shared.pyi +++ b/logwrap/_log_wrap_shared.pyi @@ -27,11 +27,11 @@ class BoundParameter(object): '_value' ) - POSITIONAL_ONLY = Parameter.POSITIONAL_ONLY # type: enum.IntEnum - POSITIONAL_OR_KEYWORD = Parameter.POSITIONAL_OR_KEYWORD # type: enum.IntEnum - VAR_POSITIONAL = Parameter.VAR_POSITIONAL # type: enum.IntEnum - KEYWORD_ONLY = Parameter.KEYWORD_ONLY # type: enum.IntEnum - VAR_KEYWORD = Parameter.VAR_KEYWORD # type: enum.IntEnum + POSITIONAL_ONLY = Parameter.POSITIONAL_ONLY + POSITIONAL_OR_KEYWORD = Parameter.POSITIONAL_OR_KEYWORD + VAR_POSITIONAL = Parameter.VAR_POSITIONAL + KEYWORD_ONLY = Parameter.KEYWORD_ONLY + VAR_KEYWORD = Parameter.VAR_KEYWORD empty = Parameter.empty # type: typing.Type diff --git a/logwrap/_repr_utils.py b/logwrap/_repr_utils.py index 987e183..a9752aa 100644 --- a/logwrap/_repr_utils.py +++ b/logwrap/_repr_utils.py @@ -54,14 +54,93 @@ def _simple(item): # type: (typing.Any) -> bool return not isinstance(item, (list, set, tuple, dict, frozenset)) +class ReprParameter(object): + """Parameter wrapper wor repr and str operations over signature.""" + + __slots__ = ( + '_value', + '_parameter' + ) + + POSITIONAL_ONLY = Parameter.POSITIONAL_ONLY + POSITIONAL_OR_KEYWORD = Parameter.POSITIONAL_OR_KEYWORD + VAR_POSITIONAL = Parameter.VAR_POSITIONAL + KEYWORD_ONLY = Parameter.KEYWORD_ONLY + VAR_KEYWORD = Parameter.VAR_KEYWORD + + empty = Parameter.empty + + def __init__( + self, + parameter, # type: Parameter + value=None # type: typing.Optional[typing.Any] + ): # type: (...) -> None + """Parameter-like object store for repr and str tasks. + + :param parameter: parameter from signature + :type parameter: inspect.Parameter + :param value: default value override + :type value: typing.Any + """ + self._parameter = parameter + self._value = value if value is not None else parameter.default + + @property + def parameter(self): # type: () -> Parameter + """Parameter object.""" + return self._parameter + + @property + def name(self): # type: () -> typing.Union[None, str] + """Parameter name. + + For `*args` and `**kwargs` add prefixes + """ + if self.kind == Parameter.VAR_POSITIONAL: + return '*' + self.parameter.name + elif self.kind == Parameter.VAR_KEYWORD: + return '**' + self.parameter.name + return self.parameter.name + + @property + def value(self): # type: () -> typing.Any + """Parameter value to log. + + If function is bound to class -> value is class instance else default value. + """ + return self._value + + @property + def annotation(self): # type: () -> typing.Union[Parameter.empty, str] + """Parameter annotation.""" + return self.parameter.annotation + + @property + def kind(self): # type: () -> int + """Parameter kind.""" + return self.parameter.kind + + def __hash__(self): # pragma: no cover + """Block hashing. + + :raises TypeError: Not hashable. + """ + msg = "unhashable type: '{0}'".format(self.__class__.__name__) + raise TypeError(msg) + + def __repr__(self): + """Debug purposes.""" + return '<{} "{}">'.format(self.__class__.__name__, self) + + # pylint: disable=no-member def _prepare_repr( func # type: typing.Union[types.FunctionType, types.MethodType] -): # type: (...) -> typing.Iterator[typing.Union[str, typing.Tuple[str, typing.Any]]] +): # type: (...) -> typing.Iterator[ReprParameter] """Get arguments lists with defaults. :type func: typing.Union[types.FunctionType, types.MethodType] - :rtype: typing.Iterator[typing.Union[str, typing.Tuple[str, typing.Any]]] + :rtype: typing.Iterator[ReprParameter] """ isfunction = isinstance(func, types.FunctionType) real_func = func if isfunction else func.__func__ # type: typing.Callable @@ -71,18 +150,11 @@ def _prepare_repr( params = iter(parameters) if not isfunction and func.__self__ is not None: try: - yield next(params).name, func.__self__ + yield ReprParameter(next(params), value=func.__self__) except StopIteration: # pragma: no cover return for arg in params: - if arg.default != Parameter.empty: - yield arg.name, arg.default - elif arg.kind == Parameter.VAR_POSITIONAL: - yield '*' + arg.name - elif arg.kind == Parameter.VAR_KEYWORD: - yield '**' + arg.name - else: - yield arg.name + yield ReprParameter(arg) # pylint: enable=no-member @@ -455,31 +527,35 @@ class PrettyRepr(PrettyFormat): param_str = "" for param in _prepare_repr(src): - if isinstance(param, tuple): - param_str += "\n{spc:<{indent}}{key}={val},".format( - spc='', - indent=self.next_indent(indent), - key=param[0], + param_str += "\n{spc:<{indent}}{param.name}".format( + spc='', + indent=self.next_indent(indent), + param=param + ) + if param.annotation != param.empty: + param_str += ': {param.annotation}'.format(param=param) + if param.value != param.empty: + param_str += '={val}'.format( val=self.process_element( - src=param[1], + src=param.value, indent=indent, no_indent_start=True, ) ) - else: - param_str += "\n{spc:<{indent}}{key},".format( - spc='', - indent=self.next_indent(indent), - key=param - ) + param_str += ',' if param_str: param_str += "\n" + " " * indent - return "\n{spc:<{indent}}<{obj!r} with interface ({args})>".format( + + sig = signature(src) + annotation = '' if sig.return_annotation == Parameter.empty else ' -> {sig.return_annotation!r}'.format(sig=sig) + + return "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format( spc="", indent=indent, obj=src, args=param_str, + annotation=annotation ) @staticmethod @@ -627,31 +703,35 @@ class PrettyStr(PrettyFormat): param_str = "" for param in _prepare_repr(src): - if isinstance(param, tuple): - param_str += "\n{spc:<{indent}}{key}={val},".format( - spc='', - indent=self.next_indent(indent), - key=param[0], + param_str += "\n{spc:<{indent}}{param.name}".format( + spc='', + indent=self.next_indent(indent), + param=param + ) + if param.annotation != param.empty: + param_str += ': {param.annotation}'.format(param=param) + if param.value != param.empty: + param_str += '={val}'.format( val=self.process_element( - src=param[1], + src=param.value, indent=indent, no_indent_start=True, ) ) - else: - param_str += "\n{spc:<{indent}}{key},".format( - spc='', - indent=self.next_indent(indent), - key=param - ) + param_str += ',' if param_str: param_str += "\n" + " " * indent - return "\n{spc:<{indent}}<{obj!s} with interface ({args})>".format( + + sig = signature(src) + annotation = '' if sig.return_annotation == Parameter.empty else ' -> {sig.return_annotation!r}'.format(sig=sig) + + return "\n{spc:<{indent}}<{obj!s} with interface ({args}){annotation}>".format( spc="", indent=indent, obj=src, args=param_str, + annotation=annotation ) @staticmethod diff --git a/logwrap/py.typed b/logwrap/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/setup.py b/setup.py index e454818..25ed0e7 100644 --- a/setup.py +++ b/setup.py @@ -267,6 +267,8 @@ setup_args = dict( 'logwrap': [ os.path.basename(filename) for filename in glob.glob(os.path.join('logwrap', '*.pyi')) + ] + [ + 'py.typed' ], }, )
Add type annotations to Callable objects when possible On python 3 typing annotations is accessible and should be used in logging.
python-useful-helpers/logwrap
diff --git a/test/test_log_wrap_py3.py b/test/test_log_wrap_py3.py index be03200..bd97db9 100644 --- a/test/test_log_wrap_py3.py +++ b/test/test_log_wrap_py3.py @@ -21,6 +21,8 @@ try: except ImportError: asyncio = None import logging +import sys +import typing # noqa # pylint: disable=unused-import import unittest try: from unittest import mock @@ -139,3 +141,42 @@ class TestLogWrapAsync(unittest.TestCase): ), ] ) + + +# noinspection PyUnusedLocal,PyMissingOrEmptyDocstring [email protected]('logwrap._log_wrap_shared.logger', autospec=True) [email protected]( + sys.version_info[:2] < (3, 4), + 'Strict python 3.3+ API' +) +class TestAnnotated(unittest.TestCase): + def test_annotation_args(self, logger): + namespace = {'logwrap': logwrap} + + exec(""" +import typing [email protected] +def func(a: typing.Optional[int]=None): + pass + """, + namespace + ) + func = namespace['func'] # type: typing.Callable[..., None] + func() + self.assertEqual( + logger.mock_calls, + [ + mock.call.log( + level=logging.DEBUG, + msg="Calling: \n" + "'func'(\n" + " # POSITIONAL_OR_KEYWORD:\n" + " 'a'=None, # type: typing.Union[int, NoneType]\n" + ")" + ), + mock.call.log( + level=logging.DEBUG, + msg="Done: 'func' with result:\nNone" + ) + ] + ) diff --git a/test/test_repr_utils.py b/test/test_repr_utils.py index b3edea6..2e45147 100644 --- a/test/test_repr_utils.py +++ b/test/test_repr_utils.py @@ -21,11 +21,10 @@ from __future__ import absolute_import from __future__ import unicode_literals +import sys import unittest import logwrap -# noinspection PyProtectedMember -from logwrap import _repr_utils # noinspection PyUnusedLocal,PyMissingOrEmptyDocstring @@ -113,74 +112,6 @@ class TestPrettyRepr(unittest.TestCase): ) self.assertEqual(exp_repr, logwrap.pretty_repr(test_obj)) - def test_prepare_repr(self): - def empty_func(): - pass - - def full_func(arg, darg=1, *positional, **named): - pass - - # noinspection PyMissingOrEmptyDocstring - class TstClass(object): - def tst_method(self, arg, darg=1, *positional, **named): - pass - - @classmethod - def tst_classmethod(cls, arg, darg=1, *positional, **named): - pass - - @staticmethod - def tst_staticmethod(arg, darg=1, *positional, **named): - pass - - tst_instance = TstClass() - - self.assertEqual( - list(_repr_utils._prepare_repr(empty_func)), - [] - ) - - self.assertEqual( - list(_repr_utils._prepare_repr(full_func)), - ['arg', ('darg', 1), '*positional', '**named'] - ) - - self.assertEqual( - list(_repr_utils._prepare_repr(TstClass.tst_method)), - ['self', 'arg', ('darg', 1), '*positional', '**named'] - ) - - self.assertEqual( - list(_repr_utils._prepare_repr(TstClass.tst_classmethod)), - [('cls', TstClass), 'arg', ('darg', 1), '*positional', '**named'] - ) - - self.assertEqual( - list(_repr_utils._prepare_repr(TstClass.tst_staticmethod)), - ['arg', ('darg', 1), '*positional', '**named'] - ) - - self.assertEqual( - list(_repr_utils._prepare_repr(tst_instance.tst_method)), - [ - ('self', tst_instance), - 'arg', - ('darg', 1), - '*positional', - '**named', - ] - ) - - self.assertEqual( - list(_repr_utils._prepare_repr(tst_instance.tst_classmethod)), - [('cls', TstClass), 'arg', ('darg', 1), '*positional', '**named'] - ) - - self.assertEqual( - list(_repr_utils._prepare_repr(tst_instance.tst_staticmethod)), - ['arg', ('darg', 1), '*positional', '**named'] - ) - def test_callable(self): fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args})>".format @@ -355,3 +286,115 @@ class TestPrettyRepr(unittest.TestCase): def test_py2_compatibility_flag(self): self.assertIsInstance(logwrap.pretty_repr(u'Text', py2_str=True), str) + + +# noinspection PyUnusedLocal,PyMissingOrEmptyDocstring [email protected]( + sys.version_info[:2] < (3, 4), + 'Strict python 3.3+ API' +) +class TestAnnotated(unittest.TestCase): + def test_001_annotation_args(self): + fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format + namespace = {} + + exec(""" +import typing +def func(a: typing.Optional[int]=None): + pass + """, + namespace + ) + func = namespace['func'] # type: typing.Callable[..., None] + + self.assertEqual( + logwrap.pretty_repr(func), + fmt( + spc='', + indent=0, + obj=func, + args="\n a: typing.Union[int, NoneType]=None,\n", + annotation="" + ) + ) + + self.assertEqual( + logwrap.pretty_str(func), + fmt( + spc='', + indent=0, + obj=func, + args="\n a: typing.Union[int, NoneType]=None,\n", + annotation="" + ) + ) + + def test_002_annotation_return(self): + fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format + namespace = {} + + exec(""" +import typing +def func() -> None: + pass + """, + namespace + ) + func = namespace['func'] # type: typing.Callable[[], None] + + self.assertEqual( + logwrap.pretty_repr(func), + fmt( + spc='', + indent=0, + obj=func, + args='', + annotation=' -> None' + ) + ) + + self.assertEqual( + logwrap.pretty_str(func), + fmt( + spc='', + indent=0, + obj=func, + args='', + annotation=' -> None' + ) + ) + + def test_003_complex(self): + fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format + namespace = {} + + exec(""" +import typing +def func(a: typing.Optional[int]=None) -> None: + pass + """, + namespace + ) + func = namespace['func'] # type: typing.Callable[..., None] + + self.assertEqual( + logwrap.pretty_repr(func), + fmt( + spc='', + indent=0, + obj=func, + args="\n a: typing.Union[int, NoneType]=None,\n", + annotation=" -> None" + ) + ) + + self.assertEqual( + logwrap.pretty_str(func), + fmt( + spc='', + indent=0, + obj=func, + args="\n a: typing.Union[int, NoneType]=None,\n", + annotation=" -> None" + ) + )
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 5 }
3.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/python-useful-helpers/logwrap.git@1e040b43e3053f54f74a0b3ec95526e4430425b3#egg=logwrap packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 six==1.17.0 tomli==1.2.3 typing==3.7.4.3 typing_extensions==4.1.1 zipp==3.6.0
name: logwrap channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - six==1.17.0 - tomli==1.2.3 - typing==3.7.4.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/logwrap
[ "test/test_log_wrap_py3.py::TestAnnotated::test_annotation_args", "test/test_repr_utils.py::TestAnnotated::test_001_annotation_args", "test/test_repr_utils.py::TestAnnotated::test_002_annotation_return", "test/test_repr_utils.py::TestAnnotated::test_003_complex" ]
[]
[ "test/test_log_wrap_py3.py::TestLogWrapAsync::test_coroutine_async", "test/test_log_wrap_py3.py::TestLogWrapAsync::test_coroutine_async_as_argumented", "test/test_log_wrap_py3.py::TestLogWrapAsync::test_coroutine_fail", "test/test_log_wrap_py3.py::TestLogWrapAsync::test_exceptions_blacklist", "test/test_repr_utils.py::TestPrettyRepr::test_callable", "test/test_repr_utils.py::TestPrettyRepr::test_dict", "test/test_repr_utils.py::TestPrettyRepr::test_indent", "test/test_repr_utils.py::TestPrettyRepr::test_iterable", "test/test_repr_utils.py::TestPrettyRepr::test_magic_override", "test/test_repr_utils.py::TestPrettyRepr::test_nested_obj", "test/test_repr_utils.py::TestPrettyRepr::test_py2_compatibility_flag", "test/test_repr_utils.py::TestPrettyRepr::test_simple", "test/test_repr_utils.py::TestPrettyRepr::test_text" ]
[]
Apache License 2.0
2,537
[ "README.rst", "logwrap/_log_wrap_shared.pyi", "logwrap/_repr_utils.py", "setup.py", "logwrap/_log_wrap_shared.py", "logwrap/py.typed" ]
[ "README.rst", "logwrap/_log_wrap_shared.pyi", "logwrap/_repr_utils.py", "setup.py", "logwrap/_log_wrap_shared.py", "logwrap/py.typed" ]
G-Node__python-odml-287
eeff5922987b064681d1328f81af317d8171808f
2018-05-17 17:18:09
eeff5922987b064681d1328f81af317d8171808f
diff --git a/doc/example_odMLs/ex_2.odml b/doc/example_odMLs/ex_2.odml deleted file mode 100644 index 8e4a6ca..0000000 --- a/doc/example_odMLs/ex_2.odml +++ /dev/null @@ -1,47 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?xml-stylesheet type="text/xsl" href="odmlTerms.xsl"?> -<?xml-stylesheet type="text/xsl" href="odml.xsl"?> -<odML version="1.1"> - <repository>http://portal.g-node.org/odml/terminologies/v1.1/terminologies.xml</repository> - <section> - <definition>Information on the crew</definition> - <section> - <definition>Information on the crew</definition> - <id>da908cda-19e1-4df8-b873-d1f6cd1b164d</id> - <type>crew</type> - <name>s11</name> - </section> - <section> - <definition>Information on the crew</definition> - <section> - <definition>Information on the crew</definition> - <id>18bb5a7e-2097-43f2-a782-e6f612107e93</id> - <type>crew</type> - <reference>s21</reference> - <name>s121</name> - </section> - <id>8d68e6fe-8dda-4dfe-a1d8-edaa0f410255</id> - <type>crew</type> - <name>s12</name> - </section> - <id>d1e70848-5318-4466-82d0-1c3e99a8ba85</id> - <type>crew</type> - <name>s1</name> - </section> - <section> - <definition>Information on the crew</definition> - <section> - <definition>Information on the crew</definition> - <id>4b2d0e9d-6352-4676-97d7-fc0a795e83a9</id> - <type>crew</type> - <name>s21</name> - </section> - <id>bc6cc466-5769-4da1-b90e-8e5595903a4a</id> - <type>crew</type> - <name>s2</name> - </section> - <date>1979-10-12</date> - <id>9b862019-643a-403f-b5a9-3b46db012961</id> - <version>42</version> - <author>D. N. Adams</author> -</odML> diff --git a/doc/example_odMLs/odml_ex_1_generator.py b/doc/example_odMLs/odml_ex_1_generator.py deleted file mode 100644 index 028de1c..0000000 --- a/doc/example_odMLs/odml_ex_1_generator.py +++ /dev/null @@ -1,63 +0,0 @@ -import datetime -import os - -import odml - -odml_pythonpath = "./g-node/python-odml" -odmlrepo = 'http://portal.g-node.org/odml/terminologies/v1.0/terminologies.xml' - -# CREATE A DOCUMENT -doc = odml.Document(author="D. N. Adams", - date=datetime.date(1979, 10, 12), - version=42, - repository=odmlrepo) - -# CREATE AND APPEND THE MAIN SECTIONs -doc.append(odml.Section(name="TheCrew", - definition="Information on the crew", - type="crew")) - -# SET NEW PARENT NODE -parent = doc['TheCrew'] - -# APPEND SUBSECTIONS -parent.append(odml.Section(name="Arthur Philip Dent", - type="crew/person", - definition="Information on Arthur Dent")) - - -# APPEND PROPERTIES WITH VALUES -parent.append(odml.Property(name="NameCrewMembers", - value=["Arthur Philip Dent", - "Zaphod Beeblebrox", - "Tricia Marie McMillan", - "Ford Prefect"], - dtype=odml.DType.person, - definition="List of crew members names")) - -parent.append(odml.Property(name="NoCrewMembers", - value=4, - dtype=odml.DType.int, - definition="Number of crew members", - uncertainty=1, - reference="The Hitchhiker's guide to the Galaxy (novel)")) - -# SET NEW PARENT NODE -parent = doc['TheCrew']['Arthur Philip Dent'] - -# APPEND SUBSECTIONS - -# APPEND PROPERTIES WITH VALUES -parent.append(odml.Property(name="Species", - value="Human", - dtype=odml.DType.string, - definition="Species to which subject belongs to")) - -parent.append(odml.Property(name="Nickname", - value=None, - dtype=odml.DType.string, - definition="Nickname(s) of the subject")) - -save_to = os.path.join(odml_pythonpath, "doc", "example_odMLs", "ex_1.odml") - -odml.save(doc, save_to) diff --git a/doc/example_odMLs/ex_1.odml b/doc/example_odMLs/sample_odml.odml similarity index 100% rename from doc/example_odMLs/ex_1.odml rename to doc/example_odMLs/sample_odml.odml diff --git a/doc/example_odMLs/ex_1.rdf b/doc/example_odMLs/sample_odml.rdf similarity index 100% rename from doc/example_odMLs/ex_1.rdf rename to doc/example_odMLs/sample_odml.rdf diff --git a/odml/base.py b/odml/base.py index a1109e8..7d78c61 100644 --- a/odml/base.py +++ b/odml/base.py @@ -29,7 +29,7 @@ class BaseObject(object): return False for key in self._format: - if key == "id": + if key == "id" or key == "oid": continue elif getattr(self, key) != getattr(obj, key): return False diff --git a/odml/doc.py b/odml/doc.py index f71217f..103d342 100644 --- a/odml/doc.py +++ b/odml/doc.py @@ -19,11 +19,11 @@ class BaseDocument(base.Sectionable): _format = format.Document - def __init__(self, author=None, date=None, version=None, repository=None, id=None): + def __init__(self, author=None, date=None, version=None, repository=None, oid=None): super(BaseDocument, self).__init__() try: - if id is not None: - self._id = str(uuid.UUID(id)) + if oid is not None: + self._id = str(uuid.UUID(oid)) else: self._id = str(uuid.uuid4()) except ValueError as e: @@ -41,6 +41,14 @@ class BaseDocument(base.Sectionable): return "<Doc %s by %s (%d sections)>" % (self._version, self._author, len(self._sections)) + @property + def oid(self): + """ + The uuid for the document. Required for entity creation and comparison, + saving and loading. + """ + return self.id + @property def id(self): """ @@ -48,15 +56,15 @@ class BaseDocument(base.Sectionable): """ return self._id - def new_id(self, id=None): + def new_id(self, oid=None): """ new_id sets the id of the current object to a RFC 4122 compliant UUID. If an id was provided, it is assigned if it is RFC 4122 UUID format compliant. If no id was provided, a new UUID is generated and assigned. - :param id: UUID string as specified in RFC 4122. + :param oid: UUID string as specified in RFC 4122. """ - if id is not None: - self._id = str(uuid.UUID(id)) + if oid is not None: + self._id = str(uuid.UUID(oid)) else: self._id = str(uuid.uuid4()) diff --git a/odml/format.py b/odml/format.py index 7a0a796..c0ae334 100644 --- a/odml/format.py +++ b/odml/format.py @@ -108,7 +108,8 @@ class Property(Format): } _map = { 'dependencyvalue': 'dependency_value', - 'type': 'dtype' + 'type': 'dtype', + 'id': 'oid' } _rdf_map = { 'id': _ns.hasId, @@ -142,6 +143,7 @@ class Section(Format): _map = { 'section': 'sections', 'property': 'properties', + 'id': 'oid' } _rdf_map = { 'id': _ns.hasId, @@ -168,7 +170,8 @@ class Document(Format): 'repository': 0, } _map = { - 'section': 'sections' + 'section': 'sections', + 'id': 'oid' } _rdf_map = { 'id': _ns.hasId, diff --git a/odml/property.py b/odml/property.py index f6d0211..e6fb3a5 100644 --- a/odml/property.py +++ b/odml/property.py @@ -16,7 +16,7 @@ class BaseProperty(base.BaseObject): def __init__(self, name=None, value=None, parent=None, unit=None, uncertainty=None, reference=None, definition=None, dependency=None, dependency_value=None, dtype=None, - value_origin=None, id=None): + value_origin=None, oid=None): """ Create a new Property. If a value without an explicitly stated dtype has been provided, the method will try to infer the value's dtype. @@ -45,13 +45,13 @@ class BaseProperty(base.BaseObject): if dtype is not given, the type is deduced from the values. Check odml.DType for supported data types. :param value_origin: Reference where the value originated from e.g. a file name. - :param id: UUID string as specified in RFC 4122. If no id is provided, + :param oid: object id, UUID string as specified in RFC 4122. If no id is provided, an id will be generated and assigned. An id has to be unique within an odML Document. """ try: - if id is not None: - self._id = str(uuid.UUID(id)) + if oid is not None: + self._id = str(uuid.UUID(oid)) else: self._id = str(uuid.uuid4()) except ValueError as e: @@ -101,19 +101,30 @@ class BaseProperty(base.BaseObject): raise ValueError("odml.Property.__setitem__: passed value cannot be " "converted to data type \'%s\'!" % self._dtype) + @property + def oid(self): + """ + The uuid for the property. Required for entity creation and comparison, + saving and loading. + """ + return self.id + @property def id(self): + """ + The uuid for the property. + """ return self._id - def new_id(self, id=None): + def new_id(self, oid=None): """ - new_id sets the id of the current object to an RFC 4122 compliant UUID. + new_id sets the object id of the current object to an RFC 4122 compliant UUID. If an id was provided, it is assigned if it is RFC 4122 UUID format compliant. If no id was provided, a new UUID is generated and assigned. - :param id: UUID string as specified in RFC 4122. + :param oid: UUID string as specified in RFC 4122. """ - if id is not None: - self._id = str(uuid.UUID(id)) + if oid is not None: + self._id = str(uuid.UUID(oid)) else: self._id = str(uuid.uuid4()) diff --git a/odml/section.py b/odml/section.py index 4707003..b026043 100644 --- a/odml/section.py +++ b/odml/section.py @@ -16,26 +16,24 @@ from .tools.doc_inherit import inherit_docstring, allow_inherit_docstring class BaseSection(base.Sectionable): """ An odML Section """ type = None - # id = None + reference = None # the *import* property _link = None _include = None - reference = None # the *import* property - _merged = None _format = format.Section def __init__(self, name=None, type=None, parent=None, definition=None, reference=None, - repository=None, link=None, include=None, id=None): + repository=None, link=None, include=None, oid=None): # Sets _sections Smartlist and _repository to None, so run first. super(BaseSection, self).__init__() self._props = base.SmartList(BaseProperty) try: - if id is not None: - self._id = str(uuid.UUID(id)) + if oid is not None: + self._id = str(uuid.UUID(oid)) else: self._id = str(uuid.uuid4()) except ValueError as e: @@ -76,19 +74,30 @@ class BaseSection(base.Sectionable): """ return len(self._sections) + len(self._props) + @property + def oid(self): + """ + The uuid for the section. Required for entity creation and comparison, + saving and loading. + """ + return self.id + @property def id(self): + """ + The uuid for the section. + """ return self._id - def new_id(self, id=None): + def new_id(self, oid=None): """ new_id sets the id of the current object to a RFC 4122 compliant UUID. If an id was provided, it is assigned if it is RFC 4122 UUID format compliant. If no id was provided, a new UUID is generated and assigned. - :param id: UUID string as specified in RFC 4122. + :param oid: UUID string as specified in RFC 4122. """ - if id is not None: - self._id = str(uuid.UUID(id)) + if oid is not None: + self._id = str(uuid.UUID(oid)) else: self._id = str(uuid.uuid4()) diff --git a/odml/tools/dict_parser.py b/odml/tools/dict_parser.py index 03ad0ea..19fe1ff 100644 --- a/odml/tools/dict_parser.py +++ b/odml/tools/dict_parser.py @@ -33,7 +33,8 @@ class DictWriter: tag = getattr(odml_document, attr) if tag: - parsed_doc[attr] = tag + # Always use the arguments key attribute name when saving + parsed_doc[i] = tag return parsed_doc @@ -60,7 +61,8 @@ class DictWriter: tag = getattr(section, attr) if tag: - section_dict[attr] = tag + # Always use the arguments key attribute name when saving + section_dict[i] = tag section_seq.append(section_dict) @@ -89,7 +91,8 @@ class DictWriter: prop.dtype.endswith("-tuple") and len(prop.value) > 0: prop_dict["value"] = "(%s)" % ";".join(prop.value[0]) else: - prop_dict[attr] = tag + # Always use the arguments key attribute name when saving + prop_dict[i] = tag props_seq.append(prop_dict) @@ -128,9 +131,9 @@ class DictReader: raise ParserException("Invalid odML document: Could not find odml-version.") elif self.parsed_doc.get('odml-version') != FORMAT_VERSION: - msg = ("Cannot read file: invalid odML document format version '%s'. \n" - "This package supports odML format versions: '%s'." - % (self.parsed_doc.get('odml-version'), FORMAT_VERSION)) + msg = ("Cannot parse odML document with format version '%s'. \n" + "\tUse the 'tools.VersionConverter' to import previous odML formats." + % self.parsed_doc.get('odml-version')) raise InvalidVersionException(msg) self.parsed_doc = self.parsed_doc['Document'] @@ -143,7 +146,8 @@ class DictReader: if attr == 'sections': doc_secs = self.parse_sections(self.parsed_doc['sections']) elif attr: - doc_attrs[i] = self.parsed_doc[i] + # Make sure to always use the correct odml format attribute name + doc_attrs[odmlfmt.Document.map(attr)] = self.parsed_doc[i] doc = odmlfmt.Document.create(**doc_attrs) for sec in doc_secs: @@ -166,7 +170,8 @@ class DictReader: elif attr == 'sections': children_secs = self.parse_sections(section['sections']) elif attr: - sec_attrs[attr] = section[attr] + # Make sure to always use the correct odml format attribute name + sec_attrs[odmlfmt.Section.map(attr)] = section[attr] sec = odmlfmt.Section.create(**sec_attrs) for prop in sec_props: @@ -188,7 +193,8 @@ class DictReader: for i in _property: attr = self.is_valid_attribute(i, odmlfmt.Property) if attr: - prop_attrs[attr] = _property[attr] + # Make sure to always use the correct odml format attribute name + prop_attrs[odmlfmt.Property.map(attr)] = _property[attr] prop = odmlfmt.Property.create(**prop_attrs) odml_props.append(prop) diff --git a/odml/tools/xmlparser.py b/odml/tools/xmlparser.py index 1f1552f..1a4f240 100644 --- a/odml/tools/xmlparser.py +++ b/odml/tools/xmlparser.py @@ -159,9 +159,9 @@ class XMLReader(object): raise ParserException("Could not find format version attribute " "in <odML> tag.\n") elif root.attrib['version'] != FORMAT_VERSION: - msg = ("Cannot read file: invalid odML document format version '%s'. \n" - "This package supports odML format versions: '%s'." - % (root.attrib['version'], FORMAT_VERSION)) + msg = ("Cannot parse odML document with format version '%s'. \n" + "\tUse the 'tools.VersionConverter' to import previous odML formats." + % root.attrib['version']) raise InvalidVersionException(msg) def from_file(self, xml_file): diff --git a/resources/install_osx_virtualenv.sh b/resources/install_osx_virtualenv.sh deleted file mode 100644 index c38ed9a..0000000 --- a/resources/install_osx_virtualenv.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -echo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -echo Running install_osx_virtalenv.sh -python --version; -echo travis python version: $TRAVIS_PYTHON_VERSION -echo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then - - brew update; - - if [[ "$OSXENV" == "2.7" ]]; then - echo python 2.7 - brew install python; - virtualenv venv -p python; - source venv/bin/activate; - else - echo some other version - brew install python3; - virtualenv venv -p python3; - source venv/bin/activate; - export PYCMD=python3; - export PIPCMD=pip3; - fi -fi - -which python
Rename 'id' variables When setting entity UUIDs we use the name `id` for the argument in the setter. This isn't nice since `id` is a builtin function. This doesn't cause any major issues since the scope of the functions where it's used is rather small. It's also understandable to use the name `id` for the keyword argument in the `set_id()` method and something like `id_` would be ugly. We could instead use the name `uuid`, or something like `eid` (for entity ID), or `oid` (object ID). Another idea might be `sid` (Section ID) and `pid` (Property ID). This would just be for the keyword argument in the `set_id()` method and anywhere else the word `id` might appear as a non-attribute. Thoughts and suggestions welcome.
G-Node/python-odml
diff --git a/test/test_doc.py b/test/test_doc.py index d598317..d6379dd 100644 --- a/test/test_doc.py +++ b/test/test_doc.py @@ -37,10 +37,10 @@ class TestSection(unittest.TestCase): doc = Document() self.assertIsNotNone(doc.id) - doc = Document("D", id="79b613eb-a256-46bf-84f6-207df465b8f7") + doc = Document("D", oid="79b613eb-a256-46bf-84f6-207df465b8f7") self.assertEqual(doc.id, "79b613eb-a256-46bf-84f6-207df465b8f7") - doc = Document("D", id="id") + doc = Document("D", oid="id") self.assertNotEqual(doc.id, "id") # Make sure id cannot be reset programmatically. diff --git a/test/test_doc_integration.py b/test/test_doc_integration.py index aed6dbd..fec4fbd 100644 --- a/test/test_doc_integration.py +++ b/test/test_doc_integration.py @@ -62,7 +62,7 @@ class TestDocumentIntegration(unittest.TestCase): # Test correct save and load of assigned id. assigned_id = "79b613eb-a256-46bf-84f6-207df465b8f7" - self.doc = odml.Document(id=assigned_id) + self.doc = odml.Document(oid=assigned_id) jdoc, xdoc, ydoc = self.save_load() self.assertEqual(jdoc.id, assigned_id) diff --git a/test/test_parser_json.py b/test/test_parser_json.py index 8d5808b..469bb7b 100644 --- a/test/test_parser_json.py +++ b/test/test_parser_json.py @@ -3,7 +3,7 @@ import os import unittest from odml.tools import dict_parser -from odml.tools.parser_utils import ParserException +from odml.tools.parser_utils import ParserException, InvalidVersionException class TestJSONParser(unittest.TestCase): @@ -40,12 +40,9 @@ class TestJSONParser(unittest.TestCase): def test_invalid_version(self): filename = "invalid_version.json" - message = "invalid odML document format version" with open(os.path.join(self.basepath, filename)) as json_data: parsed_doc = json.load(json_data) - with self.assertRaises(ParserException) as exc: + with self.assertRaises(InvalidVersionException): _ = self.json_reader.to_odml(parsed_doc) - - self.assertIn(message, str(exc.exception)) diff --git a/test/test_parser_xml.py b/test/test_parser_xml.py index f998209..c7bbb74 100644 --- a/test/test_parser_xml.py +++ b/test/test_parser_xml.py @@ -2,7 +2,7 @@ import os import unittest from odml.tools import xmlparser -from odml.tools.parser_utils import ParserException +from odml.tools.parser_utils import ParserException, InvalidVersionException class TestXMLParser(unittest.TestCase): @@ -33,9 +33,6 @@ class TestXMLParser(unittest.TestCase): def test_invalid_version(self): filename = "invalid_version.xml" - message = "invalid odML document format version" - with self.assertRaises(ParserException) as exc: + with self.assertRaises(InvalidVersionException): _ = self.xml_reader.from_file(os.path.join(self.basepath, filename)) - - self.assertIn(message, str(exc.exception)) diff --git a/test/test_parser_yaml.py b/test/test_parser_yaml.py index e7333aa..0c77dd1 100644 --- a/test/test_parser_yaml.py +++ b/test/test_parser_yaml.py @@ -3,7 +3,7 @@ import unittest import yaml from odml.tools import dict_parser -from odml.tools.parser_utils import ParserException +from odml.tools.parser_utils import ParserException, InvalidVersionException class TestYAMLParser(unittest.TestCase): @@ -40,12 +40,9 @@ class TestYAMLParser(unittest.TestCase): def test_invalid_version(self): filename = "invalid_version.yaml" - message = "invalid odML document format version" with open(os.path.join(self.basepath, filename)) as raw_data: parsed_doc = yaml.load(raw_data) - with self.assertRaises(ParserException) as exc: + with self.assertRaises(InvalidVersionException): _ = self.yaml_reader.to_odml(parsed_doc) - - self.assertIn(message, str(exc.exception)) diff --git a/test/test_property.py b/test/test_property.py index 9eafedb..876bc37 100644 --- a/test/test_property.py +++ b/test/test_property.py @@ -436,10 +436,10 @@ class TestProperty(unittest.TestCase): p = Property(name="P") self.assertIsNotNone(p.id) - p = Property("P", id="79b613eb-a256-46bf-84f6-207df465b8f7") + p = Property("P", oid="79b613eb-a256-46bf-84f6-207df465b8f7") self.assertEqual(p.id, "79b613eb-a256-46bf-84f6-207df465b8f7") - p = Property("P", id="id") + p = Property("P", oid="id") self.assertNotEqual(p.id, "id") # Make sure id cannot be reset programmatically. diff --git a/test/test_property_integration.py b/test/test_property_integration.py index cf30d59..b19766e 100644 --- a/test/test_property_integration.py +++ b/test/test_property_integration.py @@ -63,7 +63,7 @@ class TestPropertyIntegration(unittest.TestCase): # Test correct save and load of assigned id. prop_name = "assigned_id" assigned_id = "79b613eb-a256-46bf-84f6-207df465b8f7" - _ = odml.Property(name=prop_name, id=assigned_id, + _ = odml.Property(name=prop_name, oid=assigned_id, parent=self.doc.sections[0]) jdoc, xdoc, ydoc = self.save_load() diff --git a/test/test_section.py b/test/test_section.py index 5581928..6275513 100644 --- a/test/test_section.py +++ b/test/test_section.py @@ -207,10 +207,10 @@ class TestSection(unittest.TestCase): s = Section(name="S") self.assertIsNotNone(s.id) - s = Section("S", id="79b613eb-a256-46bf-84f6-207df465b8f7") + s = Section("S", oid="79b613eb-a256-46bf-84f6-207df465b8f7") self.assertEqual(s.id, "79b613eb-a256-46bf-84f6-207df465b8f7") - s = Section("S", id="id") + s = Section("S", oid="id") self.assertNotEqual(s.id, "id") # Make sure id cannot be reset programmatically. diff --git a/test/test_section_integration.py b/test/test_section_integration.py index f15246f..f3e667d 100644 --- a/test/test_section_integration.py +++ b/test/test_section_integration.py @@ -55,20 +55,20 @@ class TestSectionIntegration(unittest.TestCase): jdoc, xdoc, ydoc = self.save_load() - self.assertEqual(jdoc.sections[sec_name].id, sec.id) - self.assertEqual(xdoc.sections[sec_name].id, sec.id) - self.assertEqual(ydoc.sections[sec_name].id, sec.id) + self.assertEqual(jdoc.sections[sec_name].oid, sec.oid) + self.assertEqual(xdoc.sections[sec_name].oid, sec.oid) + self.assertEqual(ydoc.sections[sec_name].oid, sec.oid) # Test correct save and load of assigned id. sec_name = "assigned_id" assigned_id = "79b613eb-a256-46bf-84f6-207df465b8f7" - _ = odml.Section(name=sec_name, id=assigned_id, parent=self.doc) + _ = odml.Section(name=sec_name, oid=assigned_id, parent=self.doc) jdoc, xdoc, ydoc = self.save_load() - self.assertEqual(jdoc.sections[sec_name].id, assigned_id) - self.assertEqual(xdoc.sections[sec_name].id, assigned_id) - self.assertEqual(ydoc.sections[sec_name].id, assigned_id) + self.assertEqual(jdoc.sections[sec_name].oid, assigned_id) + self.assertEqual(xdoc.sections[sec_name].oid, assigned_id) + self.assertEqual(ydoc.sections[sec_name].oid, assigned_id) def test_simple_attributes(self): """
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_removed_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 7 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc libxml2-dev libxslt1-dev lib32z1-dev" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 isodate==0.7.2 lxml==5.3.1 -e git+https://github.com/G-Node/python-odml.git@eeff5922987b064681d1328f81af317d8171808f#egg=odML packaging==24.2 pluggy==1.5.0 pyparsing==3.2.3 pytest==8.3.5 PyYAML==6.0.2 rdflib==7.1.4 tomli==2.2.1
name: python-odml channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - isodate==0.7.2 - lxml==5.3.1 - packaging==24.2 - pluggy==1.5.0 - pyparsing==3.2.3 - pytest==8.3.5 - pyyaml==6.0.2 - rdflib==7.1.4 - tomli==2.2.1 prefix: /opt/conda/envs/python-odml
[ "test/test_doc.py::TestSection::test_id", "test/test_property.py::TestProperty::test_id", "test/test_section.py::TestSection::test_id" ]
[ "test/test_doc_integration.py::TestDocumentIntegration::test_children", "test/test_doc_integration.py::TestDocumentIntegration::test_id", "test/test_doc_integration.py::TestDocumentIntegration::test_simple_attributes", "test/test_parser_yaml.py::TestYAMLParser::test_invalid_version", "test/test_parser_yaml.py::TestYAMLParser::test_missing_root", "test/test_parser_yaml.py::TestYAMLParser::test_missing_version", "test/test_property_integration.py::TestPropertyIntegration::test_id", "test/test_property_integration.py::TestPropertyIntegration::test_simple_attributes", "test/test_section_integration.py::TestSectionIntegration::test_children", "test/test_section_integration.py::TestSectionIntegration::test_id", "test/test_section_integration.py::TestSectionIntegration::test_simple_attributes" ]
[ "test/test_doc.py::TestSection::test_append", "test/test_doc.py::TestSection::test_date", "test/test_doc.py::TestSection::test_extend", "test/test_doc.py::TestSection::test_get_terminology_equivalent", "test/test_doc.py::TestSection::test_insert", "test/test_doc.py::TestSection::test_new_id", "test/test_doc.py::TestSection::test_simple_attributes", "test/test_parser_json.py::TestJSONParser::test_invalid_version", "test/test_parser_json.py::TestJSONParser::test_missing_root", "test/test_parser_json.py::TestJSONParser::test_missing_version", "test/test_parser_xml.py::TestXMLParser::test_invalid_root", "test/test_parser_xml.py::TestXMLParser::test_invalid_version", "test/test_parser_xml.py::TestXMLParser::test_missing_version", "test/test_property.py::TestProperty::test_bool_conversion", "test/test_property.py::TestProperty::test_clone", "test/test_property.py::TestProperty::test_dtype", "test/test_property.py::TestProperty::test_get_merged_equivalent", "test/test_property.py::TestProperty::test_get_path", "test/test_property.py::TestProperty::test_get_set_value", "test/test_property.py::TestProperty::test_merge", "test/test_property.py::TestProperty::test_merge_check", "test/test_property.py::TestProperty::test_name", "test/test_property.py::TestProperty::test_new_id", "test/test_property.py::TestProperty::test_parent", "test/test_property.py::TestProperty::test_simple_attributes", "test/test_property.py::TestProperty::test_str_to_int_convert", "test/test_property.py::TestProperty::test_value", "test/test_property.py::TestProperty::test_value_append", "test/test_property.py::TestProperty::test_value_extend", "test/test_section.py::TestSection::test_append", "test/test_section.py::TestSection::test_children", "test/test_section.py::TestSection::test_clone", "test/test_section.py::TestSection::test_contains", "test/test_section.py::TestSection::test_extend", "test/test_section.py::TestSection::test_include", "test/test_section.py::TestSection::test_insert", "test/test_section.py::TestSection::test_link", "test/test_section.py::TestSection::test_merge", "test/test_section.py::TestSection::test_merge_check", "test/test_section.py::TestSection::test_name", "test/test_section.py::TestSection::test_new_id", "test/test_section.py::TestSection::test_parent", "test/test_section.py::TestSection::test_path", "test/test_section.py::TestSection::test_remove", "test/test_section.py::TestSection::test_reorder", "test/test_section.py::TestSection::test_repository", "test/test_section.py::TestSection::test_simple_attributes", "test/test_section.py::TestSection::test_unmerge", "test/test_section_integration.py::TestSectionIntegration::test_include", "test/test_section_integration.py::TestSectionIntegration::test_link" ]
[]
BSD 4-Clause "Original" or "Old" License
2,538
[ "odml/base.py", "odml/format.py", "odml/tools/dict_parser.py", "odml/doc.py", "doc/example_odMLs/ex_1.rdf", "doc/example_odMLs/odml_ex_1_generator.py", "odml/tools/xmlparser.py", "doc/example_odMLs/ex_1.odml", "resources/install_osx_virtualenv.sh", "odml/section.py", "odml/property.py", "doc/example_odMLs/ex_2.odml" ]
[ "doc/example_odMLs/sample_odml.odml", "odml/base.py", "odml/format.py", "odml/tools/dict_parser.py", "odml/doc.py", "doc/example_odMLs/odml_ex_1_generator.py", "odml/tools/xmlparser.py", "resources/install_osx_virtualenv.sh", "odml/section.py", "doc/example_odMLs/sample_odml.rdf", "odml/property.py", "doc/example_odMLs/ex_2.odml" ]
marshmallow-code__marshmallow-819
0f7fac3d034be94fa6d996cf58cd826879b15be8
2018-05-18 10:22:06
8e217c8d6fefb7049ab3389f31a8d35824fa2d96
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 50d5f9d4..d6aedd4a 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,19 +6,25 @@ Changelog Features: -* Clean up code for schema hooks (:issue:`814`). Thanks :user:`taion`. -* Minor performance improvement from simplifying ``utils.get_value`` (:issue:`811`). Thanks again :user:`taion`. -* Add ``require_tld`` argument to ``fields.URL`` (:issue:`749`). Thanks +- Clean up code for schema hooks (:issue:`814`). Thanks :user:`taion`. +- Minor performance improvement from simplifying ``utils.get_value`` (:issue:`811`). Thanks again :user:`taion`. +- Add ``require_tld`` argument to ``fields.URL`` (:issue:`749`). Thanks :user:`DenerKup` for reporting and thanks :user:`surik00` for the PR. -* ``fields.UUID`` deserializes ``bytes`` strings using ``UUID(bytes=b'...')`` (:issue:`625`). +- ``fields.UUID`` deserializes ``bytes`` strings using ``UUID(bytes=b'...')`` (:issue:`625`). Thanks :user:`JeffBerger` for the suggestion and the PR. Bug fixes: -* Fields nested within ``Dict`` correctly inherit context from their +- Fields nested within ``Dict`` correctly inherit context from their parent schema (:issue:`820`). Thanks :user:`RosanneZe` for reporting and :user:`deckar01` for the PR. -* Includes bug fix from 2.15.3. +- Includes bug fix from 2.15.3. + +Other changes: + +- *Backwards-incompatible*: Pre/Post-processors must return modified data. + ``None`` does not mean data was mutated (:issue:`347`). Thanks + :user:`tdevelioglu` for reporting. 3.0.0b10 (2018-05-10) +++++++++++++++++++++ diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 7cf5c67c..b013a526 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -456,6 +456,14 @@ It is not possible to specify a different key for serialization and deserializat Also, when ``data_key`` is specified on a field, only ``data_key`` is checked in the input data. In marshmallow 2.x the field name is checked if ``load_from`` is missing from the input data. +Pre/Post-processors must return modified data +********************************************* + +In marshmallow 2.x, ``None`` returned by a pre or post-processor is interpreted as "the data was mutated". In marshmallow 3.x, the return value is considered as processed data even if it is ``None``. + +Processors that mutate the data should be updated to also return it. + + Upgrading to 2.3 ++++++++++++++++ diff --git a/marshmallow/schema.py b/marshmallow/schema.py index c634bc26..09e853d2 100644 --- a/marshmallow/schema.py +++ b/marshmallow/schema.py @@ -927,20 +927,20 @@ class BaseSchema(base.SchemaABC): if pass_many: if pass_original: - data = utils.if_none(processor(data, many, original_data), data) + data = processor(data, many, original_data) else: - data = utils.if_none(processor(data, many), data) + data = processor(data, many) elif many: if pass_original: - data = [utils.if_none(processor(item, original), item) + data = [processor(item, original) for item, original in zip(data, original_data)] else: - data = [utils.if_none(processor(item), item) for item in data] + data = [processor(item) for item in data] else: if pass_original: - data = utils.if_none(processor(data, original_data), data) + data = processor(data, original_data) else: - data = utils.if_none(processor(data), data) + data = processor(data) return data diff --git a/marshmallow/utils.py b/marshmallow/utils.py index 91423108..592d4016 100755 --- a/marshmallow/utils.py +++ b/marshmallow/utils.py @@ -398,7 +398,3 @@ def get_func_args(func): return _signature(func) # Callable class return _signature(func.__call__) - - -def if_none(value, default): - return value if value is not None else default
Unenveloping None values doesn't work as expected Trying to unenvelope serialized data when the contained data is None continues deserialization with the original data. This makes it impossible to deserialize nested fields with enveloped data where None is a valid value. (Related: http://jsonapi.org/format/) Example (let's pretend our system allows for homeless employees): https://gist.github.com/tdevelioglu/8e433355494ba022f48f (I expect a deserialized Resource object, with an attribute 'address' with value 'None')
marshmallow-code/marshmallow
diff --git a/tests/test_decorators.py b/tests/test_decorators.py index 41a2d44a..58b1a298 100644 --- a/tests/test_decorators.py +++ b/tests/test_decorators.py @@ -22,24 +22,25 @@ def test_decorated_processors(): value = fields.Integer(as_string=True) - # Implicit default raw, pre dump, static method, return modified item. + # Implicit default raw, pre dump, static method. @pre_dump def increment_value(self, item): item['value'] += 1 return item - # Implicit default raw, post dump, class method, modify in place. + # Implicit default raw, post dump, class method. @post_dump def add_tag(self, item): item['value'] = self.TAG + item['value'] + return item - # Explicitly raw, post dump, instance method, return modified item. + # Explicitly raw, post dump, instance method. @post_dump(pass_many=True) def add_envelope(self, data, many): key = self.get_envelope_key(many) return {key: data} - # Explicitly raw, pre load, instance method, return modified item. + # Explicitly raw, pre load, instance method. @pre_load(pass_many=True) def remove_envelope(self, data, many): key = self.get_envelope_key(many) @@ -49,15 +50,17 @@ def test_decorated_processors(): def get_envelope_key(many): return 'data' if many else 'datum' - # Explicitly not raw, pre load, instance method, modify in place. + # Explicitly not raw, pre load, instance method. @pre_load(pass_many=False) def remove_tag(self, item): item['value'] = item['value'][len(self.TAG):] + return item - # Explicit default raw, post load, instance method, modify in place. + # Explicit default raw, post load, instance method. @post_load() def decrement_value(self, item): item['value'] -= 1 + return item schema = ExampleSchema() @@ -75,9 +78,44 @@ def test_decorated_processors(): items_loaded = schema.load(items_dumped, many=True) assert items_loaded == make_items() + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +def test_decorated_processor_returning_none(): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item): + return None + + @post_dump + def dump_none(self, item): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item): + return None + + @pre_dump + def dump_none(self, item): + return None + + schema = PostSchema() + assert schema.dump({'value': 3}) is None + assert schema.load({'value': 3}) is None + schema = PreSchema() + assert schema.dump({'value': 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({'value': 3}) + assert excinfo.value.messages == {'_schema': ['Invalid input type.']} + + class TestPassOriginal: - def test_pass_original_single_no_mutation(self): + def test_pass_original_single(self): class MySchema(Schema): foo = fields.Field() @@ -104,19 +142,6 @@ class TestPassOriginal: assert item_dumped['foo'] == 42 assert item_dumped['_post_dump'] == 24 - def test_pass_original_single_with_mutation(self): - class MySchema(Schema): - foo = fields.Field() - - @post_load(pass_original=True) - def post_load(self, data, input_data): - data['_post_load'] = input_data['post_load'] - - schema = MySchema() - item_loaded = schema.load({'foo': 42, 'post_load': 24}) - assert item_loaded['foo'] == 42 - assert item_loaded['_post_load'] == 24 - def test_pass_original_many(self): class MySchema(Schema): foo = fields.Field() @@ -218,6 +243,7 @@ def test_pre_dump_is_invoked_before_implicit_field_generation(): @pre_dump def hook(s, data): data['generated_field'] = 7 + return data class Meta: # Removing generated_field from here drops it from the output @@ -574,7 +600,7 @@ def test_decorator_error_handling(): @pre_load() def pre_load_error1(self, item): if item['foo'] != 0: - return + return item errors = { 'foo': ['preloadmsg1'], 'bar': ['preloadmsg2', 'preloadmsg3'], @@ -584,13 +610,13 @@ def test_decorator_error_handling(): @pre_load() def pre_load_error2(self, item): if item['foo'] != 4: - return + return item raise ValidationError('preloadmsg1', 'foo') @pre_load() def pre_load_error3(self, item): if item['foo'] != 8: - return + return item raise ValidationError('preloadmsg1') @post_load() @@ -612,7 +638,7 @@ def test_decorator_error_handling(): @pre_dump() def pre_dump_error1(self, item): if item['foo'] != 2: - return + return item errors = { 'foo': ['predumpmsg1'], 'bar': ['predumpmsg2', 'predumpmsg3'], @@ -622,7 +648,7 @@ def test_decorator_error_handling(): @pre_dump() def pre_dump_error2(self, item): if item['foo'] != 6: - return + return item raise ValidationError('predumpmsg1', 'foo') @post_dump() @@ -638,7 +664,7 @@ def test_decorator_error_handling(): @post_dump() def post_dump_error2(self, item): if item['foo'] != 7: - return + return item raise ValidationError('postdumpmsg1', 'foo') def make_item(foo, bar):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 4 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[reco]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": [ "dev-requirements.txt", "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster @ git+https://github.com/sloria/alabaster.git@667b1b676c6bf7226db057f098ec826d84d3ae40 atomicwrites==1.4.1 attrs==25.3.0 babel==2.17.0 certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 flake8==3.5.0 idna==3.10 imagesize==1.4.1 iniconfig==2.1.0 invoke==1.0.0 Jinja2==3.1.6 MarkupSafe==3.0.2 -e git+https://github.com/marshmallow-code/marshmallow.git@0f7fac3d034be94fa6d996cf58cd826879b15be8#egg=marshmallow mccabe==0.6.1 more-itertools==10.6.0 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 py==1.11.0 pycodestyle==2.3.1 pyflakes==1.6.0 Pygments==2.19.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.7.3 pytz==2018.4 requests==2.32.3 simplejson==3.15.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==1.7.4 sphinx-issues==0.4.0 sphinxcontrib-serializinghtml==2.0.0 sphinxcontrib-websupport==1.2.4 toml==0.10.2 tomli==2.2.1 tox==3.12.1 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3
name: marshmallow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.11+sloria0 - atomicwrites==1.4.1 - attrs==25.3.0 - babel==2.17.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - flake8==3.5.0 - idna==3.10 - imagesize==1.4.1 - iniconfig==2.1.0 - invoke==1.0.0 - jinja2==3.1.6 - markupsafe==3.0.2 - mccabe==0.6.1 - more-itertools==10.6.0 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - py==1.11.0 - pycodestyle==2.3.1 - pyflakes==1.6.0 - pygments==2.19.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.7.3 - pytz==2018.4 - requests==2.32.3 - simplejson==3.15.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==1.7.4 - sphinx-issues==0.4.0 - sphinxcontrib-serializinghtml==2.0.0 - sphinxcontrib-websupport==1.2.4 - toml==0.10.2 - tomli==2.2.1 - tox==3.12.1 - typing-extensions==4.13.0 - urllib3==2.3.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/marshmallow
[ "tests/test_decorators.py::test_decorated_processor_returning_none" ]
[]
[ "tests/test_decorators.py::test_decorated_processors", "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", "tests/test_decorators.py::test_decorated_processor_inheritance", "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", "tests/test_decorators.py::TestValidatesDecorator::test_validates", "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", "tests/test_decorators.py::TestValidatesDecorator::test_precedence", "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many", "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", "tests/test_decorators.py::test_decorator_error_handling", "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", "tests/test_decorators.py::test_decorator_post_dump_with_nested_pass_original_and_pass_many[data0-expected_data0-expected_original_data0]", "tests/test_decorators.py::test_decorator_post_load_with_nested_pass_original_and_pass_many[data0-expected_data0-expected_original_data0]" ]
[]
MIT License
2,542
[ "CHANGELOG.rst", "marshmallow/schema.py", "docs/upgrading.rst", "marshmallow/utils.py" ]
[ "CHANGELOG.rst", "marshmallow/schema.py", "docs/upgrading.rst", "marshmallow/utils.py" ]
algoo__hapic-51
730d2bee7907ae8f68de012c1cfd3e059840ae9e
2018-05-18 14:02:01
d72385ed5e1321d2216f42f6d6267e30f5dab28a
diff --git a/hapic/context.py b/hapic/context.py index 97aa0c4..7b5d9b9 100644 --- a/hapic/context.py +++ b/hapic/context.py @@ -135,6 +135,15 @@ class ContextInterface(object): """ raise NotImplementedError() + def is_debug(self) -> bool: + """ + Method called to know if Hapic has been called in debug mode. + Debug mode provide some informations like debug trace and error + message in body when internal error happen. + :return: True if in debug mode + """ + raise NotImplementedError() + class HandledException(object): """ diff --git a/hapic/decorator.py b/hapic/decorator.py index 10c6036..8d7f284 100644 --- a/hapic/decorator.py +++ b/hapic/decorator.py @@ -420,7 +420,10 @@ class ExceptionHandlerControllerWrapper(ControllerWrapper): func_kwargs, ) except self.handled_exception_class as exc: - response_content = self.error_builder.build_from_exception(exc) + response_content = self.error_builder.build_from_exception( + exc, + include_traceback=self.context.is_debug(), + ) # Check error format dumped = self.error_builder.dump(response_content).data diff --git a/hapic/error.py b/hapic/error.py index 9157657..073b849 100644 --- a/hapic/error.py +++ b/hapic/error.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import traceback + import marshmallow from hapic.processor import ProcessValidationError @@ -9,7 +11,11 @@ class ErrorBuilderInterface(marshmallow.Schema): ErrorBuilder is a class who represent a Schema (marshmallow.Schema) and can generate a response content from exception (build_from_exception) """ - def build_from_exception(self, exception: Exception) -> dict: + def build_from_exception( + self, + exception: Exception, + include_traceback: bool = False, + ) -> dict: """ Build the error response content from given exception :param exception: Original exception who invoke this method @@ -34,14 +40,28 @@ class DefaultErrorBuilder(ErrorBuilderInterface): details = marshmallow.fields.Dict(required=False, missing={}) code = marshmallow.fields.Raw(missing=None) - def build_from_exception(self, exception: Exception) -> dict: + def build_from_exception( + self, + exception: Exception, + include_traceback: bool = False, + ) -> dict: """ See hapic.error.ErrorBuilderInterface#build_from_exception docstring """ # TODO: "error_detail" attribute name should be configurable + message = str(exception) + if not message: + message = type(exception).__name__ + + details = { + 'error_detail': getattr(exception, 'error_detail', {}), + } + if include_traceback: + details['traceback'] = traceback.format_exc() + return { - 'message': str(exception), - 'details': getattr(exception, 'error_detail', {}), + 'message': message, + 'details': details, 'code': None, } diff --git a/hapic/ext/bottle/context.py b/hapic/ext/bottle/context.py index c5090b8..ba8d75a 100644 --- a/hapic/ext/bottle/context.py +++ b/hapic/ext/bottle/context.py @@ -33,12 +33,14 @@ class BottleContext(BaseContext): self, app: bottle.Bottle, default_error_builder: ErrorBuilderInterface=None, + debug: bool = False, ): self._handled_exceptions = [] # type: typing.List[HandledException] # nopep8 self._exceptions_handler_installed = False self.app = app self.default_error_builder = \ default_error_builder or DefaultErrorBuilder() # FDV + self.debug = debug def get_request_parameters(self, *args, **kwargs) -> RequestParameters: path_parameters = dict(bottle.request.url_args) @@ -164,3 +166,6 @@ class BottleContext(BaseContext): See hapic.context.BaseContext#_get_handled_exception_class_and_http_codes # nopep8 """ return self._handled_exceptions + + def is_debug(self) -> bool: + return self.debug diff --git a/hapic/ext/flask/context.py b/hapic/ext/flask/context.py index 0908dc2..b548d11 100644 --- a/hapic/ext/flask/context.py +++ b/hapic/ext/flask/context.py @@ -32,11 +32,13 @@ class FlaskContext(BaseContext): self, app: Flask, default_error_builder: ErrorBuilderInterface=None, + debug: bool = False, ): self._handled_exceptions = [] # type: typing.List[HandledException] # nopep8 self.app = app self.default_error_builder = \ default_error_builder or DefaultErrorBuilder() # FDV + self.debug = debug def get_request_parameters(self, *args, **kwargs) -> RequestParameters: from flask import request @@ -165,3 +167,6 @@ class FlaskContext(BaseContext): http_code: int, ) -> None: raise NotImplementedError('TODO') + + def is_debug(self) -> bool: + return self.debug diff --git a/hapic/ext/pyramid/context.py b/hapic/ext/pyramid/context.py index d39b615..6fcde49 100644 --- a/hapic/ext/pyramid/context.py +++ b/hapic/ext/pyramid/context.py @@ -31,11 +31,13 @@ class PyramidContext(BaseContext): self, configurator: 'Configurator', default_error_builder: ErrorBuilderInterface = None, + debug: bool = False, ): self._handled_exceptions = [] # type: typing.List[HandledException] # nopep8 self.configurator = configurator self.default_error_builder = \ default_error_builder or DefaultErrorBuilder() # FDV + self.debug = debug def get_request_parameters(self, *args, **kwargs) -> RequestParameters: req = args[-1] # TODO : Check @@ -189,3 +191,6 @@ class PyramidContext(BaseContext): http_code: int, ) -> None: raise NotImplementedError('TODO') + + def is_debug(self) -> bool: + return self.debug
Error catching: erro details must be given by default When error is catch and transformed to response, error information must be hidden by default. A parameter like "debug" should be able to return it.
algoo/hapic
diff --git a/tests/unit/test_decorator.py b/tests/unit/test_decorator.py index e088a8a..08906a4 100644 --- a/tests/unit/test_decorator.py +++ b/tests/unit/test_decorator.py @@ -276,7 +276,7 @@ class TestExceptionHandlerControllerWrapper(Base): response = func(42) assert HTTPStatus.INTERNAL_SERVER_ERROR == response.status_code assert { - 'details': {}, + 'details': {'error_detail': {}}, 'message': 'We are testing', 'code': None, } == json.loads(response.body) @@ -305,7 +305,7 @@ class TestExceptionHandlerControllerWrapper(Base): assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR assert { 'message': 'We are testing', - 'details': {'foo': 'bar'}, + 'details': {'error_detail': {'foo': 'bar'}}, 'code': None, } == json.loads(response.body) @@ -314,7 +314,11 @@ class TestExceptionHandlerControllerWrapper(Base): pass class MyErrorBuilder(DefaultErrorBuilder): - def build_from_exception(self, exception: Exception) -> dict: + def build_from_exception( + self, + exception: Exception, + include_traceback: bool = False, + ) -> dict: # this is not matching with DefaultErrorBuilder schema return {}
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 1 }, "num_modified_files": 6 }
0.38
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [], "python": "3.6", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.13.2 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 dataclasses==0.8 Flask==2.0.3 -e git+https://github.com/algoo/hapic.git@730d2bee7907ae8f68de012c1cfd3e059840ae9e#egg=hapic hapic-apispec==0.37.0 hupper==1.10.3 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 MarkupSafe==2.0.1 marshmallow==2.21.0 multidict==5.2.0 packaging==21.3 PasteDeploy==2.1.1 plaster==1.0 plaster-pastedeploy==0.7 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pyramid==2.0.2 pytest==7.0.1 pytest-cov==4.0.0 PyYAML==6.0.1 requests==2.27.1 soupsieve==2.3.2.post1 tomli==1.2.3 translationstring==1.4 typing_extensions==4.1.1 urllib3==1.26.20 venusian==3.0.0 waitress==2.0.0 WebOb==1.8.9 WebTest==3.0.0 Werkzeug==2.0.3 zipp==3.6.0 zope.deprecation==4.4.0 zope.interface==5.5.2
name: hapic channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.13.2 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - dataclasses==0.8 - flask==2.0.3 - hapic-apispec==0.37.0 - hupper==1.10.3 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - markupsafe==2.0.1 - marshmallow==2.21.0 - multidict==5.2.0 - packaging==21.3 - pastedeploy==2.1.1 - plaster==1.0 - plaster-pastedeploy==0.7 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pyramid==2.0.2 - pytest==7.0.1 - pytest-cov==4.0.0 - pyyaml==6.0.1 - requests==2.27.1 - soupsieve==2.3.2.post1 - tomli==1.2.3 - translationstring==1.4 - typing-extensions==4.1.1 - urllib3==1.26.20 - venusian==3.0.0 - waitress==2.0.0 - webob==1.8.9 - webtest==3.0.0 - werkzeug==2.0.3 - zipp==3.6.0 - zope-deprecation==4.4.0 - zope-interface==5.5.2 prefix: /opt/conda/envs/hapic
[ "tests/unit/test_decorator.py::TestExceptionHandlerControllerWrapper::test_unit__exception_handled__ok__nominal_case", "tests/unit/test_decorator.py::TestExceptionHandlerControllerWrapper::test_unit__exception_handled__ok__exception_error_dict" ]
[]
[ "tests/unit/test_decorator.py::TestControllerWrapper::test_unit__base_controller_wrapper__ok__no_behaviour", "tests/unit/test_decorator.py::TestControllerWrapper::test_unit__base_controller__ok__replaced_response", "tests/unit/test_decorator.py::TestControllerWrapper::test_unit__controller_wrapper__ok__overload_input", "tests/unit/test_decorator.py::TestInputControllerWrapper::test_unit__input_data_wrapping__ok__nominal_case", "tests/unit/test_decorator.py::TestInputControllerWrapper::test_unit__multi_query_param_values__ok__use_as_list", "tests/unit/test_decorator.py::TestInputControllerWrapper::test_unit__multi_query_param_values__ok__without_as_list", "tests/unit/test_decorator.py::TestOutputControllerWrapper::test_unit__output_data_wrapping__ok__nominal_case", "tests/unit/test_decorator.py::TestOutputControllerWrapper::test_unit__output_data_wrapping__fail__error_response", "tests/unit/test_decorator.py::TestExceptionHandlerControllerWrapper::test_unit__exception_handler__error__error_content_malformed" ]
[]
MIT License
2,543
[ "hapic/ext/pyramid/context.py", "hapic/ext/flask/context.py", "hapic/decorator.py", "hapic/ext/bottle/context.py", "hapic/error.py", "hapic/context.py" ]
[ "hapic/ext/pyramid/context.py", "hapic/ext/flask/context.py", "hapic/decorator.py", "hapic/ext/bottle/context.py", "hapic/error.py", "hapic/context.py" ]
CORE-GATECH-GROUP__serpent-tools-154
911894d67eb9677c4430a1aee91e9d1461ffc44b
2018-05-18 16:25:11
7c7da6012f509a2e71c3076ab510718585f75b11
diff --git a/serpentTools/objects/containers.py b/serpentTools/objects/containers.py index 8c30e1b..bcc9103 100644 --- a/serpentTools/objects/containers.py +++ b/serpentTools/objects/containers.py @@ -35,8 +35,8 @@ for xsSpectrum, xsType in product({'INF', 'B1'}, for xx in range(SCATTER_ORDERS)}) HOMOG_VAR_TO_ATTR = { - 'MICRO_E': 'microGroups', 'MICRO_NG': '_numMicroGroups', - 'MACRO_E': 'groups', 'MACRO_NG': '_numGroups'} + 'MICRO_E': 'microGroups', 'MICRO_NG': 'numMicroGroups', + 'MACRO_E': 'groups', 'MACRO_NG': 'numGroups'} __all__ = ('DET_COLS', 'HomogUniv', 'BranchContainer', 'Detector', 'DetectorBase', 'SCATTER_MATS', 'SCATTER_ORDERS') @@ -147,12 +147,22 @@ class HomogUniv(NamedObject): self._numGroups = self.groups.size - 1 return self._numGroups + @numGroups.setter + def numGroups(self, value): + value = value if isinstance(value, int) else int(value) + self._numGroups = value + @property def numMicroGroups(self): if self._numMicroGroups is None and self.microGroups is not None: self._numMicroGroups = self.microGroups.size - 1 return self._numMicroGroups + @numMicroGroups.setter + def numMicroGroups(self, value): + value = value if isinstance(value, int) else int(value) + self._numMicroGroups = value + def __str__(self): extras = [] if self.bu is not None:
[BUG] number of groups stored as a float; causes reshape scatter matrices to fail ## Summary of issue The `addData` routine stores the number of energy groups as a float. This causes numpy to fail during the reshaping of scattering matrices. ## Code for reproducing the issue ``` import serpentTools from serpentTools.settings import rc rc['xs.reshapeScatter'] = True r = serpentTools.read('bwr_res.m') ``` ## Actual outcome including console output and error traceback if applicable ``` ~/.local/lib/python3.5/site-packages/serpentTools-0.4.0+9.g277cb89-py3.5.egg/serpentTools/objects/containers.py in addData(self, variableName, variableValue, uncertainty) 200 'should be boolean.'.format(type(uncertainty))) 201 --> 202 value = self._cleanData(variableName, variableValue) 203 if variableName in HOMOG_VAR_TO_ATTR: 204 value = value if variableValue.size > 1 else value[0] ~/.local/lib/python3.5/site-packages/serpentTools-0.4.0+9.g277cb89-py3.5.egg/serpentTools/objects/containers.py in _cleanData(self, name, value) 233 .format(name)) 234 else: --> 235 value = value.reshape(ng, ng) 236 return value 237 TypeError: 'numpy.float64' object cannot be interpreted as an integer ``` ## Expected outcome No error and scattering matrices are reshaped properly ## Versions * Version from ``serpentTools.__version__`` `0.4.0+9.g277cb89` * Python version - ``python --version`` `3.5` * IPython or Jupyter version if applicable - `ipython 6.2.1`
CORE-GATECH-GROUP/serpent-tools
diff --git a/serpentTools/tests/test_container.py b/serpentTools/tests/test_container.py index 721dd1d..ded8988 100644 --- a/serpentTools/tests/test_container.py +++ b/serpentTools/tests/test_container.py @@ -4,7 +4,7 @@ import unittest from itertools import product from six import iteritems -from numpy import array, arange, ndarray +from numpy import array, arange, ndarray, float64 from numpy.testing import assert_array_equal from serpentTools.settings import rc @@ -171,6 +171,37 @@ class UnivTruthTester(unittest.TestCase): self.assertTrue(univ.hasData, msg=msg) +class HomogUnivIntGroupsTester(unittest.TestCase): + """Class that ensures number of groups is stored as ints.""" + + def setUp(self): + self.univ = HomogUniv('intGroups', 0, 0, 0) + self.numGroups = 2 + self.numMicroGroups = 4 + + def test_univGroupsFromFloats(self): + """Vefify integer groups are stored when passed as floats.""" + self.setAs(float) + self._tester() + + def test_univGroupsFromNPFloats(self): + """Vefify integer groups are stored when passed as numpy floats.""" + self.setAs(float64) + self._tester() + + def _tester(self): + for attr in {'numGroups', 'numMicroGroups'}: + actual = getattr(self.univ, attr) + msg ='Attribute: {}'.format(attr) + self.assertIsInstance(actual, int, msg=msg) + expected = getattr(self, attr) + self.assertEqual(expected, actual, msg=msg) + + def setAs(self, func): + """Set the number of groups to be as specific type.""" + for attr in {'numGroups', 'numMicroGroups'}: + expected = getattr(self, attr) + setattr(self.univ, attr, func(expected)) if __name__ == '__main__': unittest.main()
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.11.1 matplotlib>=1.5.0 pyyaml>=3.08 scipy six", "pip_packages": [ "numpy>=1.11.1", "matplotlib>=1.5.0", "pyyaml>=3.08", "scipy", "six", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 cycler @ file:///tmp/build/80754af9/cycler_1637851556182/work importlib-metadata==4.8.3 iniconfig==1.1.1 kiwisolver @ file:///tmp/build/80754af9/kiwisolver_1612282412546/work matplotlib @ file:///tmp/build/80754af9/matplotlib-suite_1613407855456/work numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work packaging==21.3 Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work pluggy==1.0.0 py==1.11.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==7.0.1 python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work PyYAML==5.4.1 scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work -e git+https://github.com/CORE-GATECH-GROUP/serpent-tools.git@911894d67eb9677c4430a1aee91e9d1461ffc44b#egg=serpentTools six @ file:///tmp/build/80754af9/six_1644875935023/work tomli==1.2.3 tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work typing_extensions==4.1.1 zipp==3.6.0
name: serpent-tools channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - blas=1.0=openblas - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - cycler=0.11.0=pyhd3eb1b0_0 - dbus=1.13.18=hb2f20db_0 - expat=2.6.4=h6a678d5_0 - fontconfig=2.14.1=h52c9d5c_1 - freetype=2.12.1=h4a9f257_0 - giflib=5.2.2=h5eee18b_0 - glib=2.69.1=h4ff587b_1 - gst-plugins-base=1.14.1=h6a678d5_1 - gstreamer=1.14.1=h5eee18b_1 - icu=58.2=he6710b0_3 - jpeg=9e=h5eee18b_3 - kiwisolver=1.3.1=py36h2531618_0 - lcms2=2.16=hb9589c4_0 - ld_impl_linux-64=2.40=h12ee557_0 - lerc=4.0.0=h6a678d5_0 - libdeflate=1.22=h5eee18b_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=7.5.0=ha8ba4b0_17 - libgfortran4=7.5.0=ha8ba4b0_17 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.18=hf726d26_0 - libpng=1.6.39=h5eee18b_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtiff=4.5.1=hffd6297_1 - libuuid=1.41.5=h5eee18b_0 - libwebp=1.2.4=h11a3e52_1 - libwebp-base=1.2.4=h5eee18b_1 - libxcb=1.15=h7f8727e_0 - libxml2=2.9.14=h74e7548_0 - lz4-c=1.9.4=h6a678d5_1 - matplotlib=3.3.4=py36h06a4308_0 - matplotlib-base=3.3.4=py36h62a2d02_0 - ncurses=6.4=h6a678d5_0 - numpy=1.19.2=py36h6163131_0 - numpy-base=1.19.2=py36h75fe3a5_0 - olefile=0.46=pyhd3eb1b0_0 - openssl=1.1.1w=h7f8727e_0 - pcre=8.45=h295c915_0 - pillow=8.3.1=py36h5aabda8_0 - pip=21.2.2=py36h06a4308_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pyqt=5.9.2=py36h05f1152_2 - python=3.6.13=h12debd9_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pyyaml=5.4.1=py36h27cfd23_1 - qt=5.9.7=h5867ecd_1 - readline=8.2=h5eee18b_0 - scipy=1.5.2=py36habc2bb6_0 - setuptools=58.0.4=py36h06a4308_0 - sip=4.19.8=py36hf484d3e_0 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tornado=6.1=py36h27cfd23_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7b6447c_0 - zlib=1.2.13=h5eee18b_1 - zstd=1.5.6=hc292b87_0 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/serpent-tools
[ "serpentTools/tests/test_container.py::HomogUnivIntGroupsTester::test_univGroupsFromFloats", "serpentTools/tests/test_container.py::HomogUnivIntGroupsTester::test_univGroupsFromNPFloats" ]
[]
[ "serpentTools/tests/test_container.py::VectoredHomogUnivTester::test_attributes", "serpentTools/tests/test_container.py::VectoredHomogUnivTester::test_getB1Exp", "serpentTools/tests/test_container.py::VectoredHomogUnivTester::test_getB1Unc", "serpentTools/tests/test_container.py::VectoredHomogUnivTester::test_getBothInf", "serpentTools/tests/test_container.py::VectoredHomogUnivTester::test_getInfExp", "serpentTools/tests/test_container.py::VectoredHomogUnivTester::test_getInfUnc", "serpentTools/tests/test_container.py::ReshapedHomogUnivTester::test_attributes", "serpentTools/tests/test_container.py::ReshapedHomogUnivTester::test_getB1Exp", "serpentTools/tests/test_container.py::ReshapedHomogUnivTester::test_getB1Unc", "serpentTools/tests/test_container.py::ReshapedHomogUnivTester::test_getBothInf", "serpentTools/tests/test_container.py::ReshapedHomogUnivTester::test_getInfExp", "serpentTools/tests/test_container.py::ReshapedHomogUnivTester::test_getInfUnc", "serpentTools/tests/test_container.py::UnivTruthTester::test_loadedUnivTrue" ]
[]
MIT License
2,544
[ "serpentTools/objects/containers.py" ]
[ "serpentTools/objects/containers.py" ]
elastic__rally-507
1ceb4dbe3d5c925fbcc63bc4ec8426a653d7c6f3
2018-05-18 17:09:02
085e3d482717d88dfc2d41aa34502eb108abbfe9
dliappis: Thanks for the review! I addressed the comments can you take another pass please?
diff --git a/docs/telemetry.rst b/docs/telemetry.rst index b0cd9849..d24f0d22 100644 --- a/docs/telemetry.rst +++ b/docs/telemetry.rst @@ -93,5 +93,6 @@ Supported telemetry parameters: * ``node-stats-include-thread-pools`` (default: ``true``): A boolean indicating whether thread pool stats should be included. * ``node-stats-include-buffer-pools`` (default: ``true``): A boolean indicating whether buffer pool stats should be included. * ``node-stats-include-breakers`` (default: ``true``): A boolean indicating whether circuit breaker stats should be included. +* ``node-stats-include-mem`` (default: ``true``): A boolean indicating whether JVM heap stats should be included. * ``node-stats-include-network`` (default: ``true``): A boolean indicating whether network-related stats should be included. * ``node-stats-include-process`` (default: ``true``): A boolean indicating whether process cpu stats should be included. diff --git a/esrally/mechanic/launcher.py b/esrally/mechanic/launcher.py index b49adc02..aa567951 100644 --- a/esrally/mechanic/launcher.py +++ b/esrally/mechanic/launcher.py @@ -68,7 +68,9 @@ class ClusterLauncher: es = {} for cluster_name, cluster_hosts in all_hosts.items(): all_client_options = self.cfg.opts("client", "options").all_client_options - cluster_client_options = all_client_options[cluster_name] + cluster_client_options = dict(all_client_options[cluster_name]) + # Use retries to avoid aborts on long living connections for telemetry devices + cluster_client_options["retry-on-timeout"] = True es[cluster_name] = self.client_factory(cluster_hosts, cluster_client_options).create() es_default = es["default"] diff --git a/esrally/mechanic/telemetry.py b/esrally/mechanic/telemetry.py index 67b9e9a1..8c078ffc 100644 --- a/esrally/mechanic/telemetry.py +++ b/esrally/mechanic/telemetry.py @@ -319,6 +319,7 @@ class NodeStatsRecorder: self.include_breakers = telemetry_params.get("node-stats-include-breakers", True) self.include_network = telemetry_params.get("node-stats-include-network", True) self.include_process = telemetry_params.get("node-stats-include-process", True) + self.include_mem_stats = telemetry_params.get("node-stats-include-mem", True) self.client = client self.metrics_store = metrics_store @@ -339,6 +340,8 @@ class NodeStatsRecorder: self.record_circuit_breaker_stats(node_name, node_stats) if self.include_buffer_pools: self.record_jvm_buffer_pool_stats(node_name, node_stats) + if self.include_mem_stats: + self.record_jvm_mem_stats(node_name, node_stats) if self.include_network: self.record_network_stats(node_name, node_stats) if self.include_process: @@ -383,6 +386,15 @@ class NodeStatsRecorder: node_stats_metric_name=metric_name, metric_value=metric_value) + def record_jvm_mem_stats(self, node_name, node_stats): + mem_stats = node_stats["jvm"]["mem"] + if mem_stats: + for metric_name, metric_value in mem_stats.items(): + self.put_value(node_name, + metric_name="jvm_mem_{}".format(metric_name), + node_stats_metric_name=metric_name, + metric_value=metric_value) + def record_network_stats(self, node_name, node_stats): transport_stats = node_stats.get("transport") if transport_stats:
Set retry-on-timeout=true for telemetry device connections As noticed in https://discuss.elastic.co/t/rally-track-report-analysis-follow-up/127266/17 , there are occasions where firewalls drop connections when there is no traffic and for benchmarks that take a long time to finish, [GcTimesSummary](https://github.com/elastic/rally/blob/3bd432054f6ab592a4b83ce90fe009eeb28f9754/esrally/mechanic/telemetry.py#L807) can timeout since it creates a connection at the beginning of the benchmark and collects again at the end of the benchmark. After an internal discussion, we agreed that it makes sense to enable `retry-on-timeout=true` for the client connections used by telemetry devices. This will avoid an unnecessary duplication of requests performed through other connections, such as the ones created in [driver.py](https://github.com/elastic/rally/blob/3bd432054f6ab592a4b83ce90fe009eeb28f9754/esrally/driver/driver.py#L588), for example, used for bulking.
elastic/rally
diff --git a/tests/mechanic/launcher_test.py b/tests/mechanic/launcher_test.py index 0d7687ea..9b60004f 100644 --- a/tests/mechanic/launcher_test.py +++ b/tests/mechanic/launcher_test.py @@ -141,6 +141,19 @@ class ClusterLauncherTests(TestCase): self.assertEqual([{"host": "10.0.0.10", "port":9200}, {"host": "10.0.0.11", "port":9200}], cluster.hosts) self.assertIsNotNone(cluster.telemetry) + def test_launches_cluster_with_telemetry_client_timeout_enabled(self): + cfg = config.Config() + cfg.add(config.Scope.application, "client", "hosts", self.test_host) + cfg.add(config.Scope.application, "client", "options", self.client_options) + cfg.add(config.Scope.application, "mechanic", "telemetry.devices", []) + cfg.add(config.Scope.application, "mechanic", "telemetry.params", {}) + + cluster_launcher = launcher.ClusterLauncher(cfg, MockMetricsStore(), client_factory_class=MockClientFactory) + cluster = cluster_launcher.start() + + for telemetry_device in cluster.telemetry.devices: + self.assertDictEqual({"retry-on-timeout": True, "timeout": 60}, telemetry_device.client.client_options) + @mock.patch("time.sleep") def test_error_on_cluster_launch(self, sleep): on_post_launch = mock.Mock() diff --git a/tests/mechanic/telemetry_test.py b/tests/mechanic/telemetry_test.py index caa22c24..af714f70 100644 --- a/tests/mechanic/telemetry_test.py +++ b/tests/mechanic/telemetry_test.py @@ -304,6 +304,34 @@ class NodeStatsRecorderTests(TestCase): "current_loaded_count" : 9992, "total_loaded_count" : 9992, "total_unloaded_count" : 0 + }, + "mem": { + "heap_used_in_bytes": 119073552, + "heap_used_percent": 19, + "heap_committed_in_bytes": 626393088, + "heap_max_in_bytes": 626393088, + "non_heap_used_in_bytes": 110250424, + "non_heap_committed_in_bytes": 118108160, + "pools": { + "young": { + "used_in_bytes": 66378576, + "max_in_bytes": 139591680, + "peak_used_in_bytes": 139591680, + "peak_max_in_bytes": 139591680 + }, + "survivor": { + "used_in_bytes": 358496, + "max_in_bytes": 17432576, + "peak_used_in_bytes": 17432576, + "peak_max_in_bytes": 17432576 + }, + "old": { + "used_in_bytes": 52336480, + "max_in_bytes": 469368832, + "peak_used_in_bytes": 52336480, + "peak_max_in_bytes": 469368832 + } + } } }, "process": { @@ -467,6 +495,34 @@ class NodeStatsRecorderTests(TestCase): "current_loaded_count" : 9992, "total_loaded_count" : 9992, "total_unloaded_count" : 0 + }, + "mem": { + "heap_used_in_bytes": 119073552, + "heap_used_percent": 19, + "heap_committed_in_bytes": 626393088, + "heap_max_in_bytes": 626393088, + "non_heap_used_in_bytes": 110250424, + "non_heap_committed_in_bytes": 118108160, + "pools": { + "young": { + "used_in_bytes": 66378576, + "max_in_bytes": 139591680, + "peak_used_in_bytes": 139591680, + "peak_max_in_bytes": 139591680 + }, + "survivor": { + "used_in_bytes": 358496, + "max_in_bytes": 17432576, + "peak_used_in_bytes": 17432576, + "peak_max_in_bytes": 17432576 + }, + "old": { + "used_in_bytes": 52336480, + "max_in_bytes": 469368832, + "peak_used_in_bytes": 52336480, + "peak_max_in_bytes": 469368832 + } + } } }, "process": { @@ -556,6 +612,7 @@ class NodeStatsRecorderTests(TestCase): mock.call(node_name="rally0", name="breaker_parent_tripped", count=0), mock.call(node_name="rally0", name="jvm_buffer_pool_mapped_count", count=7), mock.call(node_name="rally0", name="jvm_buffer_pool_direct_count", count=6), + mock.call(node_name="rally0", name="jvm_mem_heap_used_percent", count=19), ], any_order=True) metrics_store_put_value.assert_has_calls([ @@ -578,6 +635,11 @@ class NodeStatsRecorderTests(TestCase): mock.call(node_name="rally0", name="jvm_buffer_pool_mapped_total_capacity_in_bytes", value=9999, unit="byte"), mock.call(node_name="rally0", name="jvm_buffer_pool_direct_used_in_bytes", value=73868, unit="byte"), mock.call(node_name="rally0", name="jvm_buffer_pool_direct_total_capacity_in_bytes", value=73867, unit="byte"), + mock.call(node_name="rally0", name="jvm_mem_heap_used_in_bytes", value=119073552, unit="byte"), + mock.call(node_name="rally0", name="jvm_mem_heap_committed_in_bytes", value=626393088, unit="byte"), + mock.call(node_name="rally0", name="jvm_mem_heap_max_in_bytes", value=626393088, unit="byte"), + mock.call(node_name="rally0", name="jvm_mem_non_heap_used_in_bytes", value=110250424, unit="byte"), + mock.call(node_name="rally0", name="jvm_mem_non_heap_committed_in_bytes", value=118108160, unit="byte"), ], any_order=True)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 3 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-benchmark" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 elasticsearch==6.2.0 -e git+https://github.com/elastic/rally.git@1ceb4dbe3d5c925fbcc63bc4ec8426a653d7c6f3#egg=esrally importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==2.9.5 jsonschema==2.5.1 MarkupSafe==2.0.1 packaging==21.3 pluggy==1.0.0 psutil==5.4.0 py==1.11.0 py-cpuinfo==3.2.0 pyparsing==3.1.4 pytest==7.0.1 pytest-benchmark==3.4.1 tabulate==0.8.1 thespian==3.9.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.22 zipp==3.6.0
name: rally channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - elasticsearch==6.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==2.9.5 - jsonschema==2.5.1 - markupsafe==2.0.1 - packaging==21.3 - pluggy==1.0.0 - psutil==5.4.0 - py==1.11.0 - py-cpuinfo==3.2.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-benchmark==3.4.1 - tabulate==0.8.1 - thespian==3.9.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.22 - zipp==3.6.0 prefix: /opt/conda/envs/rally
[ "tests/mechanic/launcher_test.py::ClusterLauncherTests::test_launches_cluster_with_telemetry_client_timeout_enabled", "tests/mechanic/telemetry_test.py::NodeStatsRecorderTests::test_stores_all_nodes_stats" ]
[]
[ "tests/mechanic/launcher_test.py::ExternalLauncherTests::test_setup_external_cluster_multiple_nodes", "tests/mechanic/launcher_test.py::ExternalLauncherTests::test_setup_external_cluster_single_node", "tests/mechanic/launcher_test.py::ClusterLauncherTests::test_error_on_cluster_launch", "tests/mechanic/launcher_test.py::ClusterLauncherTests::test_launches_cluster_with_post_launch_handler", "tests/mechanic/launcher_test.py::ClusterLauncherTests::test_launches_cluster_without_post_launch_handler", "tests/mechanic/telemetry_test.py::TelemetryTests::test_merges_options_set_by_different_devices", "tests/mechanic/telemetry_test.py::StartupTimeTests::test_store_calculated_metrics", "tests/mechanic/telemetry_test.py::MergePartsDeviceTests::test_store_calculated_metrics", "tests/mechanic/telemetry_test.py::MergePartsDeviceTests::test_store_nothing_if_no_metrics_present", "tests/mechanic/telemetry_test.py::JfrTests::test_sets_options_for_java_9_or_above_custom_recording_template", "tests/mechanic/telemetry_test.py::JfrTests::test_sets_options_for_java_9_or_above_default_recording_template", "tests/mechanic/telemetry_test.py::JfrTests::test_sets_options_for_pre_java_9_custom_recording_template", "tests/mechanic/telemetry_test.py::JfrTests::test_sets_options_for_pre_java_9_default_recording_template", "tests/mechanic/telemetry_test.py::GcTests::test_sets_options_for_java_9_or_above", "tests/mechanic/telemetry_test.py::GcTests::test_sets_options_for_pre_java_9", "tests/mechanic/telemetry_test.py::NodeStatsRecorderTests::test_negative_sample_interval_forbidden", "tests/mechanic/telemetry_test.py::NodeStatsRecorderTests::test_stores_default_nodes_stats", "tests/mechanic/telemetry_test.py::ClusterEnvironmentInfoTests::test_stores_cluster_level_metrics_on_attach", "tests/mechanic/telemetry_test.py::NodeEnvironmentInfoTests::test_stores_node_level_metrics_on_attach", "tests/mechanic/telemetry_test.py::ExternalEnvironmentInfoTests::test_fallback_when_host_not_available", "tests/mechanic/telemetry_test.py::ExternalEnvironmentInfoTests::test_stores_all_node_metrics_on_attach", "tests/mechanic/telemetry_test.py::ClusterMetaDataInfoTests::test_enriches_cluster_nodes_for_elasticsearch_1_x", "tests/mechanic/telemetry_test.py::ClusterMetaDataInfoTests::test_enriches_cluster_nodes_for_elasticsearch_after_1_x", "tests/mechanic/telemetry_test.py::GcTimesSummaryTests::test_stores_only_diff_of_gc_times", "tests/mechanic/telemetry_test.py::IndexStatsTests::test_index_stats_are_per_lap", "tests/mechanic/telemetry_test.py::IndexStatsTests::test_stores_available_index_stats", "tests/mechanic/telemetry_test.py::IndexSizeTests::test_stores_index_size_for_data_paths", "tests/mechanic/telemetry_test.py::IndexSizeTests::test_stores_nothing_if_no_data_path" ]
[]
Apache License 2.0
2,545
[ "esrally/mechanic/launcher.py", "docs/telemetry.rst", "esrally/mechanic/telemetry.py" ]
[ "esrally/mechanic/launcher.py", "docs/telemetry.rst", "esrally/mechanic/telemetry.py" ]
neogeny__TatSu-67
677e51bed96fd15ce689b76e6f60f7251975eff2
2018-05-18 17:59:52
4aa9636ab1a77a24a5b60eeb06575aee5cf20dd7
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 06fc6e4..94de2dd 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -14,6 +14,10 @@ The format of this *Change Log* is inspired by `keeapachangelog.org`_. --------------- .. _X.Y.Z: https://github.com/apalala/tatsu/compare/v4.2.6...master +* `#66`_ Fix multiline (`(?x)`) patterns not properly supported in grammar (`@pdw-mb`_) + +.. _#66: https://github.com/neogeny/TatSu/issues/56 + `4.2.6`_ @ 2018-0506 --------------------- .. _4.2.6: https://github.com/apalala/tatsu/compare/v4.2.5...v4.2.6 @@ -298,5 +302,6 @@ Added .. _gkimbar: https://bitbucket.org/gkimbar .. _nehz: https://bitbucket.org/nehz .. _neumond: https://bitbucket.org/neumond +.. _pdw-mb: https://bitbucket.org/pdw-mb .. _pgebhard: https://bitbucket.org/pgebhard .. _siemer: https://bitbucket.org/siemer diff --git a/docs/contributors.rst b/docs/contributors.rst index cafe69a..5e38e83 100644 --- a/docs/contributors.rst +++ b/docs/contributors.rst @@ -40,6 +40,7 @@ features, but reports, bug fixes, or suggestions: `gkimbar`_, `nehz`_ , `neumond`_, + `pdw-mb`_, `pgebhard`_, `siemer`_ @@ -83,5 +84,6 @@ Most of the contributions are recorded as **Grako** commits_ or issues_. .. _gkimbar: https://bitbucket.org/gkimbar .. _nehz: https://bitbucket.org/nehz .. _neumond: https://bitbucket.org/neumond +.. _pdw-mb: https://bitbucket.org/pdw-mb .. _pgebhard: https://bitbucket.org/pgebhard .. _siemer: https://bitbucket.org/siemer diff --git a/tatsu/codegen/python.py b/tatsu/codegen/python.py index 71d606a..2b06af3 100644 --- a/tatsu/codegen/python.py +++ b/tatsu/codegen/python.py @@ -98,7 +98,7 @@ class Constant(Base): class Pattern(Base): def render_fields(self, fields): - raw_repr = 'r' + urepr(self.node.pattern).replace("\\\\", '\\') + raw_repr = urepr(self.node.pattern) fields.update(pattern=raw_repr) template = 'self._pattern({pattern})'
Generated Python code doesn't cope with multi-line regexs Consider: ``` myrule = /(?x) foo bar / $ ; ``` This generates: ``` self._pattern(r'(?x) \n foo\n bar\n') ``` Which will look for literal newlines in the string, rather than being ignored.
neogeny/TatSu
diff --git a/test/grammar/pattern_test.py b/test/grammar/pattern_test.py index c2a214a..6dd7c0d 100644 --- a/test/grammar/pattern_test.py +++ b/test/grammar/pattern_test.py @@ -3,9 +3,10 @@ from __future__ import absolute_import, division, print_function, unicode_litera import unittest -from tatsu.util import trim +from tatsu.util import trim, urepr from tatsu.tool import compile from tatsu.exceptions import FailedParse +from tatsu.codegen import codegen class PatternTests(unittest.TestCase): @@ -103,3 +104,30 @@ class PatternTests(unittest.TestCase): model = compile(grammar=grammar) ast = model.parse('ABcD xYZ') self.assertEqual(['ABcD', 'xYZ'], ast) + + def test_multiline_pattern(self): + grammar = r''' + start = + /(?x) + foo + bar + / $ ; + ''' + model = compile(grammar=trim(grammar)) + print(codegen(model.rules[0].exp.sequence[0])) + self.assertEqual( + codegen(model.rules[0].exp.sequence[0]), + urepr("self._pattern('(?x)\nfoo\nbar\n')").strip('"\'') + ) + + grammar = r''' + start = + /(?x)foo\nbar + blort/ $ ; + ''' + model = compile(grammar=trim(grammar)) + print(codegen(model.rules[0].exp.sequence[0])) + self.assertEqual( + trim(codegen(model.rules[0].exp.sequence[0])), + urepr("self._pattern('(?x)foo\\nbar\nblort')").strip('"\.') + )
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 3 }
4.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-flake8", "pytest-mypy", "pytest-pylint" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 dill==0.3.9 exceptiongroup==1.2.2 filelock==3.18.0 flake8==7.2.0 iniconfig==2.1.0 isort==6.0.1 mccabe==0.7.0 mypy==1.15.0 mypy-extensions==1.0.0 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 pylint==3.3.6 pytest==8.3.5 pytest-flake8==1.3.0 pytest-mypy==1.0.0 pytest-pylint==0.21.0 -e git+https://github.com/neogeny/TatSu.git@677e51bed96fd15ce689b76e6f60f7251975eff2#egg=TatSu tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0
name: TatSu channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.3.9 - dill==0.3.9 - exceptiongroup==1.2.2 - filelock==3.18.0 - flake8==7.2.0 - iniconfig==2.1.0 - isort==6.0.1 - mccabe==0.7.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pylint==3.3.6 - pytest==8.3.5 - pytest-flake8==1.3.0 - pytest-mypy==1.0.0 - pytest-pylint==0.21.0 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 prefix: /opt/conda/envs/TatSu
[ "test/grammar/pattern_test.py::PatternTests::test_multiline_pattern" ]
[]
[ "test/grammar/pattern_test.py::PatternTests::test_ignorecase_not_for_pattern", "test/grammar/pattern_test.py::PatternTests::test_ignorecase_pattern", "test/grammar/pattern_test.py::PatternTests::test_pattern_concatenation", "test/grammar/pattern_test.py::PatternTests::test_patterns_with_newlines" ]
[]
BSD License
2,546
[ "CHANGELOG.rst", "tatsu/codegen/python.py", "docs/contributors.rst" ]
[ "CHANGELOG.rst", "tatsu/codegen/python.py", "docs/contributors.rst" ]
CartoDB__cartoframes-445
b45ab4800eef0ef114ad707887833fd028b54b5a
2018-05-18 20:56:43
d4d9f537db7677e369588fd3e035665566ec3fcd
diff --git a/README.rst b/README.rst index a5839a12..7f985b28 100644 --- a/README.rst +++ b/README.rst @@ -110,7 +110,7 @@ Get table from CARTO, make changes in pandas, sync updates with CARTO: .. code:: python import cartoframes - # `base_url`s are of the form `http://{username}.carto.com/` for most users + # `base_url`s are of the form `https://{username}.carto.com/` for most users cc = cartoframes.CartoContext(base_url='https://eschbacher.carto.com/', api_key=APIKEY) @@ -194,7 +194,7 @@ CARTO Credential Management Typical usage ^^^^^^^^^^^^^ -The most common way to input credentials into cartoframes is through the `CartoContext`, as below. Replace `{your_user_name}` with your CARTO username and `{your_api_key}` with your API key, which you can find at ``http://{your_user_name}.carto.com/your_apps``. +The most common way to input credentials into cartoframes is through the `CartoContext`, as below. Replace `{your_user_name}` with your CARTO username and `{your_api_key}` with your API key, which you can find at ``https://{your_user_name}.carto.com/your_apps``. .. code:: python diff --git a/cartoframes/context.py b/cartoframes/context.py index c4147ecb..12696c61 100644 --- a/cartoframes/context.py +++ b/cartoframes/context.py @@ -136,6 +136,7 @@ class CartoContext(object): def _is_authenticated(self): """Checks if credentials allow for authenticated carto access""" + # check if user is authenticated try: self.sql_client.send( 'select * from information_schema.tables limit 0') diff --git a/cartoframes/credentials.py b/cartoframes/credentials.py index 4feaecfb..00e7db5e 100644 --- a/cartoframes/credentials.py +++ b/cartoframes/credentials.py @@ -1,7 +1,12 @@ """Credentials management for cartoframes usage.""" import os import json +import sys import warnings +if sys.version_info >= (3, 0): + from urllib.parse import urlparse +else: + from urlparse import urlparse import appdirs _USER_CONFIG_DIR = appdirs.user_config_dir('cartoframes') @@ -46,26 +51,32 @@ class Credentials(object): """ def __init__(self, creds=None, key=None, username=None, base_url=None, cred_file=None): + self._key = None + self._username = None + self._base_url = None if creds and isinstance(creds, Credentials): - self._key = creds.key() - self._username = creds.username() - self._base_url = creds.base_url() + self.key(key=creds.key()) + self.username(username=creds.username()) + self.base_url(base_url=creds.base_url()) elif (key and username) or (key and base_url): - self._key = key - self._username = username + self.key(key=key) + self.username(username=username) if base_url: - self._base_url = base_url + self.base_url(base_url=base_url) else: - self._base_url = 'https://{}.carto.com/'.format(self._username) + self.base_url( + base_url='https://{}.carto.com/'.format(self._username) + ) elif cred_file: self._retrieve(cred_file) else: try: self._retrieve(_DEFAULT_PATH) except: - raise RuntimeError('Could not load CARTO credentials. Try ' - 'setting them with the `key` and ' - '`username` arguments.') + raise RuntimeError( + 'Could not load CARTO credentials. Try setting them with ' + 'the `key` and `username` arguments.' + ) self._norm_creds() def __repr__(self): @@ -77,7 +88,8 @@ class Credentials(object): def _norm_creds(self): """Standardize credentials""" - self._base_url = self._base_url.strip('/') + if self._base_url: + self._base_url = self._base_url.strip('/') def save(self, config_loc=None): """Saves current user credentials to user directory. @@ -256,6 +268,12 @@ class Credentials(object): >>> creds.base_url('new_base_url') """ if base_url: + # POSTs need to be over HTTPS (e.g., Import API reverts to a GET) + if urlparse(base_url).scheme != 'https': + raise ValueError( + '`base_url`s need to be over `https`. Update your ' + '`base_url`.' + ) self._base_url = base_url else: return self._base_url
add base url validation on `https` to ensure all requests occur as expected `POST api/v1/imports` forwards to `GET api/v1/imports` if the base url is not `https`. This causes some unexpected behaviors and perplexing errors, so we need to add base url validation to ensure all the services work as expected. We can bundle this into the `is_authenticated` method in CartoContext.
CartoDB/cartoframes
diff --git a/test/test_context.py b/test/test_context.py index dd04ed4c..a8185971 100644 --- a/test/test_context.py +++ b/test/test_context.py @@ -167,6 +167,14 @@ class TestCartoContext(unittest.TestCase, _UserUrlLoader): cc_saved = cartoframes.CartoContext() self.assertEqual(cc_saved.creds.key(), self.apikey) + @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test') + def test_cartocontext_authenticated(self): + """context.CartoContext._is_authenticated""" + with self.assertRaises(ValueError): + cc = cartoframes.CartoContext( + base_url=self.baseurl.replace('https', 'http'), + api_key=self.apikey) + @unittest.skipIf(WILL_SKIP, 'no carto credentials, skipping this test') def test_cartocontext_isorguser(self): """context.CartoContext._is_org_user""" diff --git a/test/test_credentials.py b/test/test_credentials.py index 5b6f6735..0aeb9ba2 100644 --- a/test/test_credentials.py +++ b/test/test_credentials.py @@ -22,10 +22,10 @@ class TestCredentials(unittest.TestCase): self.onprem_base_url = 'https://turtleland.com/user/{}'.format( self.username) self.default = { - 'key': 'default_key', - 'username': 'default_username', - 'base_url': 'https://default_username.carto.com/' - } + 'key': 'default_key', + 'username': 'default_username', + 'base_url': 'https://default_username.carto.com/' + } self.default_cred = Credentials(**self.default) self.default_cred.save() @@ -61,6 +61,12 @@ class TestCredentials(unittest.TestCase): self.assertEqual(creds.username(), None) self.assertEqual(creds.base_url(), self.base_url.strip('/')) + with self.assertRaises(ValueError): + creds = Credentials( + key=self.key, + base_url=self.base_url.replace('https', 'http') + ) + def test_credentials_onprem_baseurl(self): """credentials.Credentials on-prem-style base_url""" creds = Credentials(key=self.key,
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 3 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "geopandas" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
appdirs==1.4.4 attrs==22.2.0 backcall==0.2.0 carto==1.11.3 -e git+https://github.com/CartoDB/cartoframes.git@b45ab4800eef0ef114ad707887833fd028b54b5a#egg=cartoframes certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 click-plugins==1.1.1 cligj==0.7.2 decorator==5.1.1 Fiona==1.8.22 future==1.0.0 geopandas==0.9.0 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 munch==4.0.0 numpy==1.19.5 packaging==21.3 pandas==1.1.5 parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pyproj==3.0.1 pyrestcli==0.6.11 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.27.1 Shapely==1.8.5.post1 six==1.17.0 tomli==1.2.3 tqdm==4.64.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 wcwidth==0.2.13 webcolors==1.7 zipp==3.6.0
name: cartoframes channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - appdirs==1.4.4 - attrs==22.2.0 - backcall==0.2.0 - carto==1.11.3 - charset-normalizer==2.0.12 - click==8.0.4 - click-plugins==1.1.1 - cligj==0.7.2 - decorator==5.1.1 - fiona==1.8.22 - future==1.0.0 - geopandas==0.9.0 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - munch==4.0.0 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pyproj==3.0.1 - pyrestcli==0.6.11 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.27.1 - shapely==1.8.5.post1 - six==1.17.0 - tomli==1.2.3 - tqdm==4.64.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - wcwidth==0.2.13 - webcolors==1.7 - zipp==3.6.0 prefix: /opt/conda/envs/cartoframes
[ "test/test_credentials.py::TestCredentials::test_credentials_baseurl" ]
[ "test/test_context.py::TestCartoContext::test_add_encoded_geom", "test/test_context.py::TestCartoContext::test_cartocontext", "test/test_context.py::TestCartoContext::test_cartocontext_authenticated", "test/test_context.py::TestCartoContext::test_cartocontext_check_query", "test/test_context.py::TestCartoContext::test_cartocontext_credentials", "test/test_context.py::TestCartoContext::test_cartocontext_delete", "test/test_context.py::TestCartoContext::test_cartocontext_handle_import", "test/test_context.py::TestCartoContext::test_cartocontext_isorguser", "test/test_context.py::TestCartoContext::test_cartocontext_map", "test/test_context.py::TestCartoContext::test_cartocontext_map_geom_type", "test/test_context.py::TestCartoContext::test_cartocontext_map_time", "test/test_context.py::TestCartoContext::test_cartocontext_mixed_case", "test/test_context.py::TestCartoContext::test_cartocontext_read", "test/test_context.py::TestCartoContext::test_cartocontext_table_exists", "test/test_context.py::TestCartoContext::test_cartocontext_write", "test/test_context.py::TestCartoContext::test_cartocontext_write_index", "test/test_context.py::TestCartoContext::test_cartoframes_query", "test/test_context.py::TestCartoContext::test_cartoframes_sync", "test/test_context.py::TestCartoContext::test_column_name_collision_do_enrichement", "test/test_context.py::TestCartoContext::test_data", "test/test_context.py::TestCartoContext::test_data_boundaries", "test/test_context.py::TestCartoContext::test_data_discovery", "test/test_context.py::TestCartoContext::test_debug_print", "test/test_context.py::TestCartoContext::test_get_bounds", "test/test_context.py::TestCartoContext::test_write_privacy", "test/test_context.py::TestBatchJobStatus::test_batchjobstatus", "test/test_context.py::TestBatchJobStatus::test_batchjobstatus_methods", "test/test_context.py::TestBatchJobStatus::test_batchjobstatus_repr" ]
[ "test/test_context.py::TestCartoContext::test_cartocontext_send_dataframe", "test/test_context.py::TestCartoContext::test_decode_geom", "test/test_context.py::TestCartoContext::test_df2pg_schema", "test/test_context.py::TestCartoContext::test_dtypes2pg", "test/test_context.py::TestCartoContext::test_encode_geom", "test/test_context.py::TestCartoContext::test_pg2dtypes", "test/test_credentials.py::TestCredentials::test_credentials", "test/test_credentials.py::TestCredentials::test_credentials_base_url", "test/test_credentials.py::TestCredentials::test_credentials_constructor", "test/test_credentials.py::TestCredentials::test_credentials_cred_file", "test/test_credentials.py::TestCredentials::test_credentials_delete", "test/test_credentials.py::TestCredentials::test_credentials_invalid_key", "test/test_credentials.py::TestCredentials::test_credentials_key", "test/test_credentials.py::TestCredentials::test_credentials_no_args", "test/test_credentials.py::TestCredentials::test_credentials_onprem_baseurl", "test/test_credentials.py::TestCredentials::test_credentials_repr", "test/test_credentials.py::TestCredentials::test_credentials_retrieve", "test/test_credentials.py::TestCredentials::test_credentials_set", "test/test_credentials.py::TestCredentials::test_credentials_username" ]
[]
BSD 3-Clause "New" or "Revised" License
2,547
[ "README.rst", "cartoframes/context.py", "cartoframes/credentials.py" ]
[ "README.rst", "cartoframes/context.py", "cartoframes/credentials.py" ]
fniessink__next-action-56
663a557773123886a51e1657a6f8fe81550006dd
2018-05-19 11:58:35
663a557773123886a51e1657a6f8fe81550006dd
diff --git a/CHANGELOG.md b/CHANGELOG.md index cae04b8..aba1ba2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Changed + +- If no file is specified, *Next-action* tries to read the todo.txt in the user's home folder. Closes #4. + ## [0.3.0] - 2018-05-19 ### Added diff --git a/README.md b/README.md index 8e9e88d..4a0f179 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ optional arguments: --version show program's version number and exit -f <filename>, --file <filename> filename of todo.txt file to read; can be - to read from standard input; argument can be - repeated to read tasks from multiple todo.txt files (default: ['todo.txt']) + repeated to read tasks from multiple todo.txt files (default: ['~/todo.txt']) -n <number>, --number <number> number of next actions to show (default: 1) -a, --all show all next actions (default: False) @@ -49,7 +49,7 @@ optional context and project arguments; these can be repeated: -+<project> project the next action must not be part of ``` -Assuming your todo.txt file is in the current folder, running *Next-action* without arguments will show the next action you should do. Given this [todo.txt](todo.txt), calling mom would be the next action: +Assuming your todo.txt file is your home folder, running *Next-action* without arguments will show the next action you should do. Given this [todo.txt](todo.txt), calling mom would be the next action: ```console $ next-action diff --git a/next_action/arguments/__init__.py b/next_action/arguments/__init__.py index 45faa29..2389d2f 100644 --- a/next_action/arguments/__init__.py +++ b/next_action/arguments/__init__.py @@ -14,7 +14,7 @@ def parse_arguments() -> Arguments: """ Build the argument parser, paerse the command line arguments, and post-process them. """ # Ensure that the help info is printed using all columns available os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns) - default_filenames = ["todo.txt"] + default_filenames = ["~/todo.txt"] parser = build_parser(default_filenames) arguments = Arguments(parser, default_filenames) namespace, remaining = parser.parse_known_args() diff --git a/next_action/arguments/arguments.py b/next_action/arguments/arguments.py index afbe5ac..384e841 100644 --- a/next_action/arguments/arguments.py +++ b/next_action/arguments/arguments.py @@ -1,6 +1,7 @@ """ Argument data class for transfering command line arguments. """ import argparse +import os.path import sys from typing import List, Set @@ -28,7 +29,7 @@ class Arguments(object): for default_filename in self.__default_filenames: filenames.remove(default_filename) # Remove duplicate filenames while maintaining order. - self.__filenames = list(dict.fromkeys(filenames)) + self.__filenames = [os.path.expanduser(filename) for filename in list(dict.fromkeys(filenames))] def show_all(self, show_all: bool) -> None: """ If the user wants to see all next actions, set the number to something big. """ diff --git a/update_readme.py b/update_readme.py index c86bcb1..96b8da3 100644 --- a/update_readme.py +++ b/update_readme.py @@ -18,7 +18,7 @@ def update_readme(): in_console_section = False elif line.startswith("$ "): print(line) - command = line[2:].split(" ") + command = line[2:].split(" ") + ["--file", "todo.txt"] command_output = subprocess.run(command, stdout=subprocess.PIPE, universal_newlines=True) print(command_output.stdout.rstrip()) elif not in_console_section:
Make the "todo.txt" in the user's home folder the default todo.txt to read
fniessink/next-action
diff --git a/tests/unittests/test_arguments.py b/tests/unittests/test_arguments.py index 7dc6ce6..4c7bbf9 100644 --- a/tests/unittests/test_arguments.py +++ b/tests/unittests/test_arguments.py @@ -22,7 +22,7 @@ class NoArgumentTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action"]) def test_filename(self): """ Test that the argument parser returns the default filename if the user doesn't pass one. """ - self.assertEqual(["todo.txt"], parse_arguments().filenames) + self.assertEqual([os.path.expanduser("~/todo.txt")], parse_arguments().filenames) class FilenameTest(unittest.TestCase): diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index 99da454..0cabed3 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -73,7 +73,7 @@ optional arguments: --version show program's version number and exit -f <filename>, --file <filename> filename of todo.txt file to read; can be - to read from standard input; argument can be - repeated to read tasks from multiple todo.txt files (default: ['todo.txt']) + repeated to read tasks from multiple todo.txt files (default: ['~/todo.txt']) -n <number>, --number <number> number of next actions to show (default: 1) -a, --all show all next actions (default: False) diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py index 82cbc42..8fec9cc 100644 --- a/tests/unittests/test_pick_action.py +++ b/tests/unittests/test_pick_action.py @@ -145,4 +145,4 @@ class IgnoredTasksTest(unittest.TestCase): completed_task1 = todotxt.Task("x Completed") completed_task2 = todotxt.Task("x Completed too") future_task = todotxt.Task("(A) 9999-01-01 Start preparing for five-digit years") - self.assertEqual([], pick_action.next_actions([completed_task1, completed_task2, future_task])) \ No newline at end of file + self.assertEqual([], pick_action.next_actions([completed_task1, completed_task2, future_task]))
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 5 }
0.3
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "pylint", "pycodestyle", "bandit", "pytest" ], "pre_install": [], "python": "3.6", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==1.6.6 attrs==22.2.0 bandit==1.4.0 certifi==2021.5.30 charset-normalizer==2.0.12 codacy-coverage==1.3.11 coverage==4.5.1 gitdb==4.0.9 GitPython==3.1.18 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 -e git+https://github.com/fniessink/next-action.git@663a557773123886a51e1657a6f8fe81550006dd#egg=next_action packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pycodestyle==2.4.0 pylint==1.9.1 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 smmap==5.0.0 stevedore==3.5.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 wrapt==1.16.0 zipp==3.6.0
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==1.6.6 - attrs==22.2.0 - bandit==1.4.0 - charset-normalizer==2.0.12 - codacy-coverage==1.3.11 - coverage==4.5.1 - gitdb==4.0.9 - gitpython==3.1.18 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.4.0 - pylint==1.9.1 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - requests==2.27.1 - setuptools==39.1.0 - six==1.17.0 - smmap==5.0.0 - stevedore==3.5.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/next-action
[ "tests/unittests/test_arguments.py::NoArgumentTest::test_filename", "tests/unittests/test_cli.py::CLITest::test_help" ]
[]
[ "tests/unittests/test_arguments.py::NoArgumentTest::test_filters", "tests/unittests/test_arguments.py::FilenameTest::test__add_filename_twice", "tests/unittests/test_arguments.py::FilenameTest::test_add_default_filename", "tests/unittests/test_arguments.py::FilenameTest::test_default_and_non_default", "tests/unittests/test_arguments.py::FilenameTest::test_filename_argument", "tests/unittests/test_arguments.py::FilenameTest::test_long_filename_argument", "tests/unittests/test_arguments.py::FilterArgumentTest::test_contexts_and_projects", "tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_context", "tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_excluded_project", "tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_project", "tests/unittests/test_arguments.py::FilterArgumentTest::test_exclude_context", "tests/unittests/test_arguments.py::FilterArgumentTest::test_exclude_project", "tests/unittests/test_arguments.py::FilterArgumentTest::test_faulty_option", "tests/unittests/test_arguments.py::FilterArgumentTest::test_include_exclude_context", "tests/unittests/test_arguments.py::FilterArgumentTest::test_include_exclude_project", "tests/unittests/test_arguments.py::FilterArgumentTest::test_invalid_extra_argument", "tests/unittests/test_arguments.py::FilterArgumentTest::test_multiple_contexts", "tests/unittests/test_arguments.py::FilterArgumentTest::test_multiple_projects", "tests/unittests/test_arguments.py::FilterArgumentTest::test_one_context", "tests/unittests/test_arguments.py::FilterArgumentTest::test_one_project", "tests/unittests/test_arguments.py::NumberTest::test_all_actions", "tests/unittests/test_arguments.py::NumberTest::test_all_and_number", "tests/unittests/test_arguments.py::NumberTest::test_default_number", "tests/unittests/test_arguments.py::NumberTest::test_faulty_number", "tests/unittests/test_arguments.py::NumberTest::test_number", "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_missing_file", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_version", "tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_due_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first", "tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks", "tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks", "tests/unittests/test_pick_action.py::PickActionTest::test_one_task", "tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date", "tests/unittests/test_pick_action.py::FilterTasksTest::test_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_contexts", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_contexts", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_projects", "tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_project_and_context", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_completed_task", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_future_task", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_these_tasks" ]
[]
Apache License 2.0
2,548
[ "update_readme.py", "next_action/arguments/arguments.py", "CHANGELOG.md", "next_action/arguments/__init__.py", "README.md" ]
[ "update_readme.py", "next_action/arguments/arguments.py", "CHANGELOG.md", "next_action/arguments/__init__.py", "README.md" ]
spencerahill__aospy-273
7162010ef9cdc1b7a69146dd7feba91933af99ef
2018-05-19 15:24:22
f8af04e7e9deec9fccd0337a074e9da174e83504
spencerahill: Awesome! I wanted to give you a quick response on a few things, but then unfortunately this next week is really crazy for me. So it's unlikely that I'll be able to give a proper review until the week of the 27th. Sorry about that. Don't forget to pin xarray version to >=0.10.4 >Win-64 platform rather than Win-32; do you agree? Yes, agreed. >Eventually it would be good to accept strings as inputs (i.e. for partial datetime string indexing), but I think we should save that for a future PR. Do you have a sense of how difficult this will be to implement? I don't want to blow up the scope of this PR, which is already necessarily pretty large. But this would be a great feature and would be nice to go straight to there instead of requiring switching from Python's datetime objects to numpy's and/or cftime's. Or, conversely, would it be possible to still accept `datetime.datetime` in cases with standard calendars? I haven't kept up with the technical details of the calendars. >We do use resample when computing transient eddy quantities (to downsample to a monthly mean time series). In the meantime though, we might think about creating a one-off function for that purpose (i.e. not worry about supporting general frequency resampling and only handle the monthly case). Given our intention of generalizing our time reduction functionality soon (#208), how does that modify this picture? Conversely, what are the prospects for getting resample support added to CFTimeIndex? --- One last thought: we're probably due for a new release, v0.3, once we get this in...even without it we've already done quite a bit since 0.2. So probably in June or July. spencerkclark: > next week is really crazy for me. So it's unlikely that I'll be able to give a proper review until the week of the 27th. Sorry about that. Totally fine! > Do you have a sense of how difficult this will be to implement? I don't want to blow up the scope of this PR, which is already necessarily pretty large. But this would be a great feature and would be nice to go straight to there instead of requiring switching from Python's datetime objects to numpy's and/or cftime's. For the most part adding string support hopefully shouldn't be too hard. The one place I'm a little unsure of is how to handle things in `assert_has_data_for_time` (our check to make sure that data exists for the full range specified by the user). To handle string inputs there I would need something akin to [`xarray.coding.cftimeindex._parsed_string_to_bounds`](https://github.com/pydata/xarray/blob/master/xarray/coding/cftimeindex.py#L69) to convert those partial strings to `cftime.datetime` or `np.datetime64` date bounds. One simple option would be to just disable that check for string inputs. > Or, conversely, would it be possible to still accept datetime.datetime in cases with standard calendars? I haven't kept up with the technical details of the calendars. I think this is reasonably straightforward. We can support all three types; if a `datetime.datetime` is provided, we will convert it to the type that the dates from the underlying dataset are converted to. If you need to specify dates that cannot be represented as `datetime.datetime` objects (which admittedly is rare) you'll just need to use `cftime.datetime` objects. > Given our intention of generalizing our time reduction functionality soon (#208), how does that modify this picture? Conversely, what are the prospects for getting resample support added to CFTimeIndex? I think generalizing the time reduction functionality is somewhat orthogonal to this. If we wanted to support eddy calculations we would need support of monthly resampling in some fashion. Getting general resample support added for CFTimeIndex in xarray is doable. Stephan has outlined roughly how this might look in https://github.com/pydata/xarray/pull/1252#issuecomment-380593243. > One last thought: we're probably due for a new release, v0.3, once we get this in...even without it we've already done quite a bit since 0.2. So probably in June or July. I agree! spencerahill: Thanks for going ahead with the `datetime.datetime` and string implementations! Full review to come; for now a few top-level thoughts: >I think generalizing the time reduction functionality is somewhat orthogonal to this. If we wanted to support eddy calculations we would need support of monthly resampling in some fashion. OK. In that case I am receptive to your initial idea of "creating a one-off function for that purpose" In thinking about this, it occurs to me that the eddy functionality is one of the uglier bits of `Calc`. We should decide what to do with it regardless of this PR. I opened #274 to track that. But we shouldn't let that hold up this PR --- maybe the wisest move is to just replace the resample call there with a `NotImplementedError`. > Getting general resample support added for CFTimeIndex in xarray is doable. Stephan has outlined roughly how this might look in pydata/xarray#1252 (comment). OK. I opened https://github.com/pydata/xarray/issues/2191 to keep tabs on that endeavor. spencerkclark: @spencerahill thanks for opening those issues! I'm currently cleaning up the tests here (moving `test_calc_basic.py` and `test_data_loader.py` away from unit test classes). Once I'm done with that, I'll ping you for a full review. spencerkclark: @spencerahill I've finished up cleaning up the tests; the main motivation for the refactor was so that I could parametrize the tests using different types of dates. > In thinking about this, it occurs to me that the eddy functionality is one of the uglier bits of Calc. We should decide what to do with it regardless of this PR. I opened #274 to track that. But we shouldn't let that hold up this PR --- maybe the wisest move is to just replace the resample call there with a NotImplementedError. Sounds good -- I've left things alone with that logic in this PR for now. I was not using that functionality either. Whatever worked with data indexed by a DatetimeIndex will still work here, and it will just error if a CFTimeIndex is used. spencerkclark: Thanks for the helpful comments @spencerahill! When you get a chance, this should be ready for another review. spencerahill: Thanks @spencerkclark for the new commits...everything looks good, but still do want to make sure I understand the design decisions c.f. my in-line comment above before merging. spencerkclark: @spencerahill thanks for opening the issue in cftime! I couldn't think of a simple solution, so I went ahead with the warning and docs note. This should be ready for a final review. spencerahill: Awesome. Thanks much @spencerkclark! Great to finally have this in.
diff --git a/aospy/calc.py b/aospy/calc.py index e8f4e6c..aa23eb6 100644 --- a/aospy/calc.py +++ b/aospy/calc.py @@ -82,7 +82,9 @@ class Calc(object): dtype_vert=self.dtype_out_vert) in_lbl = utils.io.data_in_label(self.intvl_in, self.dtype_in_time, self.dtype_in_vert) - yr_lbl = utils.io.yr_label((self.start_date.year, self.end_date.year)) + start_year = utils.times.infer_year(self.start_date) + end_year = utils.times.infer_year(self.end_date) + yr_lbl = utils.io.yr_label((start_year, end_year)) return '.'.join( [self.name, out_lbl, in_lbl, self.model.name, self.run.name, yr_lbl, extension] diff --git a/aospy/data_loader.py b/aospy/data_loader.py index 3962eb9..719214d 100644 --- a/aospy/data_loader.py +++ b/aospy/data_loader.py @@ -1,7 +1,6 @@ """aospy DataLoader objects""" import logging import os -import warnings import numpy as np import xarray as xr @@ -16,7 +15,7 @@ from .utils import times, io def _preprocess_and_rename_grid_attrs(func, **kwargs): - """Call a custom preprocessing method first then rename grid attrs + """Call a custom preprocessing method first then rename grid attrs. This wrapper is needed to generate a single function to pass to the ``preprocesss`` of xr.open_mfdataset. It makes sure that the @@ -100,7 +99,7 @@ def set_grid_attrs_as_coords(ds): def _maybe_cast_to_float64(da): - """Cast DataArrays to np.float64 if they are of type np.float32 + """Cast DataArrays to np.float64 if they are of type np.float32. Parameters ---------- @@ -157,16 +156,14 @@ def _sel_var(ds, var, upcast_float32=True): def _prep_time_data(ds): - """Prepare time coord. information in Dataset for use in aospy. + """Prepare time coordinate information in Dataset for use in aospy. - 1. Edit units attribute of time variable if it contains a Timestamp invalid - date - 2. If the Dataset contains a time bounds coordinate, add attributes + 1. If the Dataset contains a time bounds coordinate, add attributes representing the true beginning and end dates of the time interval used to construct the Dataset - 3. If the Dataset contains a time bounds coordinate, overwrite the time + 2. If the Dataset contains a time bounds coordinate, overwrite the time coordinate values with the averages of the time bounds at each timestep - 4. Decode the times into np.datetime64 objects for time indexing + 3. Decode the times into np.datetime64 objects for time indexing Parameters ---------- @@ -176,11 +173,10 @@ def _prep_time_data(ds): Returns ------- - Dataset, int, int - The processed Dataset and minimum and maximum years in the loaded data + Dataset + The processed Dataset """ ds = times.ensure_time_as_index(ds) - ds, min_year, max_year = times.numpy_datetime_workaround_encode_cf(ds) if TIME_BOUNDS_STR in ds: ds = times.ensure_time_avg_has_cf_metadata(ds) ds[TIME_STR] = times.average_time_bounds(ds) @@ -189,10 +185,10 @@ def _prep_time_data(ds): "values in time, even though this may not be " "the case") ds = times.add_uniform_time_weights(ds) - with warnings.catch_warnings(record=True): + with xr.set_options(enable_cftimeindex=True): ds = xr.decode_cf(ds, decode_times=True, decode_coords=False, mask_and_scale=True) - return ds, min_year, max_year + return ds def _load_data_from_disk(file_set, preprocess_func=lambda ds: ds, @@ -239,7 +235,7 @@ def apply_preload_user_commands(file_set, cmd=io.dmget): def _setattr_default(obj, attr, value, default): - """Set an attribute of an object to a value or default value""" + """Set an attribute of an object to a value or default value.""" if value is None: setattr(obj, attr, default) else: @@ -247,7 +243,7 @@ def _setattr_default(obj, attr, value, default): class DataLoader(object): - """A fundamental DataLoader object""" + """A fundamental DataLoader object.""" def load_variable(self, var=None, start_date=None, end_date=None, time_offset=None, **DataAttrs): """Load a DataArray for requested variable and time range. @@ -280,21 +276,19 @@ class DataLoader(object): coords=self.coords, start_date=start_date, end_date=end_date, time_offset=time_offset, **DataAttrs ) - - ds, min_year, max_year = _prep_time_data(ds) + ds = _prep_time_data(ds) + start_date = times.maybe_convert_to_index_date_type( + ds.indexes[TIME_STR], start_date) + end_date = times.maybe_convert_to_index_date_type( + ds.indexes[TIME_STR], end_date) ds = set_grid_attrs_as_coords(ds) da = _sel_var(ds, var, self.upcast_float32) da = self._maybe_apply_time_shift(da, time_offset, **DataAttrs) - - start_date_xarray = times.numpy_datetime_range_workaround( - start_date, min_year, max_year) - end_date_xarray = start_date_xarray + (end_date - start_date) - return times.sel_time(da, np.datetime64(start_date_xarray), - np.datetime64(end_date_xarray)).load() + return times.sel_time(da, start_date, end_date).load() def recursively_compute_variable(self, var, start_date=None, end_date=None, time_offset=None, **DataAttrs): - """Compute a variable recursively, loading data where needed + """Compute a variable recursively, loading data where needed. An obvious requirement here is that the variable must eventually be able to be expressed in terms of model-native quantities; otherwise the @@ -344,7 +338,7 @@ class DataLoader(object): class DictDataLoader(DataLoader): - """A DataLoader that uses a dict mapping lists of files to string tags + """A DataLoader that uses a dict mapping lists of files to string tags. This is the simplest DataLoader; it is useful for instance if one is dealing with raw model history files, which tend to group all variables @@ -393,7 +387,7 @@ class DictDataLoader(DataLoader): """ def __init__(self, file_map=None, upcast_float32=True, data_vars='minimal', coords='minimal', preprocess_func=lambda ds, **kwargs: ds): - """Create a new DictDataLoader""" + """Create a new DictDataLoader.""" self.file_map = file_map self.upcast_float32 = upcast_float32 self.data_vars = data_vars @@ -412,7 +406,7 @@ class DictDataLoader(DataLoader): class NestedDictDataLoader(DataLoader): - """DataLoader that uses a nested dictionary mapping to load files + """DataLoader that uses a nested dictionary mapping to load files. This is the most flexible existing type of DataLoader; it allows for the specification of different sets of files for different variables. The @@ -474,7 +468,7 @@ class NestedDictDataLoader(DataLoader): class GFDLDataLoader(DataLoader): - """DataLoader for NOAA GFDL model output + """DataLoader for NOAA GFDL model output. This is an example of a domain-specific custom DataLoader, designed specifically for finding files output by the Geophysical Fluid Dynamics @@ -609,10 +603,13 @@ class GFDLDataLoader(DataLoader): else: subdir = os.path.join(intvl_in, dur_str) direc = os.path.join(self.data_direc, domain, dtype_lbl, subdir) + data_start_year = times.infer_year(self.data_start_date) + start_year = times.infer_year(start_date) + end_year = times.infer_year(end_date) files = [os.path.join(direc, io.data_name_gfdl( name, domain, dtype, intvl_in, year, intvl_out, - self.data_start_date.year, self.data_dur)) - for year in range(start_date.year, end_date.year + 1)] + data_start_year, self.data_dur)) + for year in range(start_year, end_year + 1)] files = list(set(files)) files.sort() return files diff --git a/aospy/examples/example_obj_lib.py b/aospy/examples/example_obj_lib.py index a71f934..91d3f6d 100644 --- a/aospy/examples/example_obj_lib.py +++ b/aospy/examples/example_obj_lib.py @@ -1,5 +1,5 @@ """Sample aospy object library using the included example data.""" -import datetime +from datetime import datetime import os import aospy @@ -17,8 +17,8 @@ example_run = Run( description=( 'Control simulation of the idealized moist model' ), - default_start_date=datetime.datetime(4, 1, 1), - default_end_date=datetime.datetime(6, 12, 31), + default_start_date=datetime(4, 1, 1), + default_end_date=datetime(6, 12, 31), data_loader=DictDataLoader(_file_map) ) diff --git a/aospy/examples/tutorial.ipynb b/aospy/examples/tutorial.ipynb index 6d234ce..c703873 100644 --- a/aospy/examples/tutorial.ipynb +++ b/aospy/examples/tutorial.ipynb @@ -21,9 +21,7 @@ { "cell_type": "code", "execution_count": 1, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "import os # Python built-in package for working with the operating system\n", @@ -56,10 +54,11 @@ " * nv (nv) float64 1.0 2.0\n", " * time (time) float64 1.111e+03 1.139e+03 1.17e+03 1.2e+03 ...\n", "Data variables:\n", - " condensation_rain (time, lat, lon) float64 5.768e-06 5.784e-06 ...\n", - " convection_rain (time, lat, lon) float64 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...\n", - " time_bounds (time, nv) float64 1.095e+03 1.126e+03 1.126e+03 ...\n", - " average_DT (time) float64 31.0 28.0 31.0 30.0 31.0 30.0 31.0 ..." + " condensation_rain (time, lat, lon) float32 dask.array<shape=(36, 64, 128), chunksize=(12, 64, 128)>\n", + " convection_rain (time, lat, lon) float32 dask.array<shape=(36, 64, 128), chunksize=(12, 64, 128)>\n", + " time_bounds (time, nv) float64 dask.array<shape=(36, 2), chunksize=(12, 2)>\n", + " average_DT (time) float64 dask.array<shape=(36,), chunksize=(12,)>\n", + " zsurf (time, lat, lon) float32 dask.array<shape=(36, 64, 128), chunksize=(12, 64, 128)>" ] }, "execution_count": 2, @@ -107,9 +106,7 @@ { "cell_type": "code", "execution_count": 3, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "from aospy.data_loader import DictDataLoader\n", @@ -129,9 +126,7 @@ { "cell_type": "code", "execution_count": 4, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "from aospy import Run\n", @@ -159,9 +154,7 @@ { "cell_type": "code", "execution_count": 5, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "from aospy import Model\n", @@ -188,9 +181,7 @@ { "cell_type": "code", "execution_count": 6, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "from aospy import Proj\n", @@ -227,9 +218,7 @@ { "cell_type": "code", "execution_count": 7, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "from aospy import Var\n", @@ -262,9 +251,7 @@ { "cell_type": "code", "execution_count": 8, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "def total_precip(condensation_rain, convection_rain):\n", @@ -315,9 +302,7 @@ { "cell_type": "code", "execution_count": 9, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "from aospy import Region\n", @@ -363,9 +348,7 @@ { "cell_type": "code", "execution_count": 10, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "from aospy.examples import example_obj_lib as lib\n", @@ -401,9 +384,7 @@ { "cell_type": "code", "execution_count": 11, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "calc_exec_options = dict(prompt_verify=False, parallelize=False,\n", @@ -426,56 +407,46 @@ "name": "stderr", "output_type": "stream", "text": [ - "INFO:root:Getting input data: Var instance \"precip_largescale\" (Thu Mar 30 08:49:11 2017)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:389: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " result = decode_cf_datetime(example_value, units, calendar)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:408: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " calendar=self.calendar)\n", - "INFO:root:Getting input data: Var instance \"precip_convective\" (Thu Mar 30 08:49:11 2017)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:389: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " result = decode_cf_datetime(example_value, units, calendar)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:408: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " calendar=self.calendar)\n", - "INFO:root:Computing timeseries for 0004-01-01 00:00:00 -- 0006-12-31 00:00:00.\n", - "INFO:root:Applying desired time-reduction methods. (Thu Mar 30 08:49:11 2017)\n", - "INFO:root:Writing desired gridded outputs to disk.\n", - "INFO:root:\texample-output/example_proj/example_model/example_run/precip_conv_frac/precip_conv_frac.ann.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", - "INFO:root:\texample-output/example_proj/example_model/example_run/precip_conv_frac/precip_conv_frac.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", - "INFO:root:Getting input data: Var instance \"precip_largescale\" (Thu Mar 30 08:49:12 2017)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:389: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " result = decode_cf_datetime(example_value, units, calendar)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:408: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " calendar=self.calendar)\n", - "INFO:root:Getting input data: Var instance \"precip_convective\" (Thu Mar 30 08:49:12 2017)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:389: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " result = decode_cf_datetime(example_value, units, calendar)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:408: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " calendar=self.calendar)\n", + "INFO:root:Getting input data: Var instance \"precip_largescale\" (Sun May 20 09:40:28 2018)\n", + "WARNING:root:Datapoints were stored using the np.float32 datatype.For accurate reduction operations using bottleneck, datapoints are being cast to the np.float64 datatype. For more information see: https://github.com/pydata/xarray/issues/1346\n", + "INFO:root:Getting input data: Var instance \"precip_convective\" (Sun May 20 09:40:28 2018)\n", + "WARNING:root:Datapoints were stored using the np.float32 datatype.For accurate reduction operations using bottleneck, datapoints are being cast to the np.float64 datatype. For more information see: https://github.com/pydata/xarray/issues/1346\n", "INFO:root:Computing timeseries for 0004-01-01 00:00:00 -- 0006-12-31 00:00:00.\n", - "INFO:root:Applying desired time-reduction methods. (Thu Mar 30 08:49:13 2017)\n", + "INFO:root:Applying desired time-reduction methods. (Sun May 20 09:40:29 2018)\n", "INFO:root:Writing desired gridded outputs to disk.\n", "INFO:root:\texample-output/example_proj/example_model/example_run/precip_total/precip_total.ann.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", + "//anaconda/envs/aospy_dev/lib/python3.6/_collections_abc.py:743: FutureWarning: iteration over an xarray.Dataset will change in xarray v0.11 to only include data variables, not coordinates. Iterate over the Dataset.variables property instead to preserve existing behavior in a forwards compatible manner.\n", + " for key in self._mapping:\n", "INFO:root:\texample-output/example_proj/example_model/example_run/precip_total/precip_total.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", - "INFO:root:Getting input data: Var instance \"precip_convective\" (Thu Mar 30 08:49:13 2017)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:389: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " result = decode_cf_datetime(example_value, units, calendar)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:408: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " calendar=self.calendar)\n", + "INFO:root:Getting input data: Var instance \"precip_largescale\" (Sun May 20 09:40:29 2018)\n", + "WARNING:root:Datapoints were stored using the np.float32 datatype.For accurate reduction operations using bottleneck, datapoints are being cast to the np.float64 datatype. For more information see: https://github.com/pydata/xarray/issues/1346\n", + "INFO:root:Getting input data: Var instance \"precip_convective\" (Sun May 20 09:40:29 2018)\n", + "WARNING:root:Datapoints were stored using the np.float32 datatype.For accurate reduction operations using bottleneck, datapoints are being cast to the np.float64 datatype. For more information see: https://github.com/pydata/xarray/issues/1346\n", "INFO:root:Computing timeseries for 0004-01-01 00:00:00 -- 0006-12-31 00:00:00.\n", - "INFO:root:Applying desired time-reduction methods. (Thu Mar 30 08:49:13 2017)\n", + "INFO:root:Applying desired time-reduction methods. (Sun May 20 09:40:29 2018)\n", "INFO:root:Writing desired gridded outputs to disk.\n", - "INFO:root:\texample-output/example_proj/example_model/example_run/precip_convective/precip_convective.ann.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", - "INFO:root:\texample-output/example_proj/example_model/example_run/precip_convective/precip_convective.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", - "INFO:root:Getting input data: Var instance \"precip_largescale\" (Thu Mar 30 08:49:13 2017)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:389: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " result = decode_cf_datetime(example_value, units, calendar)\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/xarray/conventions.py:408: RuntimeWarning: Unable to decode time axis into full numpy.datetime64 objects, continuing using dummy netCDF4.datetime objects instead, reason: dates out of range\n", - " calendar=self.calendar)\n", + "INFO:root:\texample-output/example_proj/example_model/example_run/precip_conv_frac/precip_conv_frac.ann.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", + "//anaconda/envs/aospy_dev/lib/python3.6/_collections_abc.py:743: FutureWarning: iteration over an xarray.Dataset will change in xarray v0.11 to only include data variables, not coordinates. Iterate over the Dataset.variables property instead to preserve existing behavior in a forwards compatible manner.\n", + " for key in self._mapping:\n", + "INFO:root:\texample-output/example_proj/example_model/example_run/precip_conv_frac/precip_conv_frac.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", + "INFO:root:Getting input data: Var instance \"precip_largescale\" (Sun May 20 09:40:29 2018)\n", + "WARNING:root:Datapoints were stored using the np.float32 datatype.For accurate reduction operations using bottleneck, datapoints are being cast to the np.float64 datatype. For more information see: https://github.com/pydata/xarray/issues/1346\n", "INFO:root:Computing timeseries for 0004-01-01 00:00:00 -- 0006-12-31 00:00:00.\n", - "INFO:root:Applying desired time-reduction methods. (Thu Mar 30 08:49:13 2017)\n", + "INFO:root:Applying desired time-reduction methods. (Sun May 20 09:40:29 2018)\n", "INFO:root:Writing desired gridded outputs to disk.\n", "INFO:root:\texample-output/example_proj/example_model/example_run/precip_largescale/precip_largescale.ann.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", - "INFO:root:\texample-output/example_proj/example_model/example_run/precip_largescale/precip_largescale.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n" + "//anaconda/envs/aospy_dev/lib/python3.6/_collections_abc.py:743: FutureWarning: iteration over an xarray.Dataset will change in xarray v0.11 to only include data variables, not coordinates. Iterate over the Dataset.variables property instead to preserve existing behavior in a forwards compatible manner.\n", + " for key in self._mapping:\n", + "INFO:root:\texample-output/example_proj/example_model/example_run/precip_largescale/precip_largescale.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", + "INFO:root:Getting input data: Var instance \"precip_convective\" (Sun May 20 09:40:29 2018)\n", + "WARNING:root:Datapoints were stored using the np.float32 datatype.For accurate reduction operations using bottleneck, datapoints are being cast to the np.float64 datatype. For more information see: https://github.com/pydata/xarray/issues/1346\n", + "INFO:root:Computing timeseries for 0004-01-01 00:00:00 -- 0006-12-31 00:00:00.\n", + "INFO:root:Applying desired time-reduction methods. (Sun May 20 09:40:30 2018)\n", + "INFO:root:Writing desired gridded outputs to disk.\n", + "INFO:root:\texample-output/example_proj/example_model/example_run/precip_convective/precip_convective.ann.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n", + "//anaconda/envs/aospy_dev/lib/python3.6/_collections_abc.py:743: FutureWarning: iteration over an xarray.Dataset will change in xarray v0.11 to only include data variables, not coordinates. Iterate over the Dataset.variables property instead to preserve existing behavior in a forwards compatible manner.\n", + " for key in self._mapping:\n", + "INFO:root:\texample-output/example_proj/example_model/example_run/precip_convective/precip_convective.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc\n" ] } ], @@ -511,10 +482,10 @@ { "data": { "text/plain": [ - "[Calc object: precip_conv_frac, example_proj, example_model, example_run,\n", - " Calc object: precip_total, example_proj, example_model, example_run,\n", - " Calc object: precip_convective, example_proj, example_model, example_run,\n", - " Calc object: precip_largescale, example_proj, example_model, example_run]" + "[<aospy.Calc instance: precip_total, example_proj, example_model, example_run>,\n", + " <aospy.Calc instance: precip_conv_frac, example_proj, example_model, example_run>,\n", + " <aospy.Calc instance: precip_largescale, example_proj, example_model, example_run>,\n", + " <aospy.Calc instance: precip_convective, example_proj, example_model, example_run>]" ] }, "execution_count": 13, @@ -541,8 +512,8 @@ { "data": { "text/plain": [ - "{'av': 'example-output/example_proj/example_model/example_run/precip_conv_frac/precip_conv_frac.ann.av.from_monthly_ts.example_model.example_run.0004-0006.nc',\n", - " 'reg.av': 'example-output/example_proj/example_model/example_run/precip_conv_frac/precip_conv_frac.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc'}" + "{'av': 'example-output/example_proj/example_model/example_run/precip_total/precip_total.ann.av.from_monthly_ts.example_model.example_run.0004-0006.nc',\n", + " 'reg.av': 'example-output/example_proj/example_model/example_run/precip_total/precip_total.ann.reg.av.from_monthly_ts.example_model.example_run.0004-0006.nc'}" ] }, "execution_count": 14, @@ -570,42 +541,42 @@ "data": { "text/plain": [ "{'av': <xarray.DataArray (lat: 64, lon: 128)>\n", - " array([[ 5.825489e-11, 5.568656e-06, 3.746100e-05, ..., 0.000000e+00,\n", - " 1.773260e-11, 2.142449e-11],\n", - " [ 1.718738e-03, 1.864318e-03, 1.876380e-03, ..., 1.584265e-03,\n", - " 1.650416e-03, 1.634984e-03],\n", - " [ 4.336546e-03, 3.980294e-03, 3.332168e-03, ..., 5.023761e-03,\n", - " 4.934178e-03, 4.846593e-03],\n", + " array([[ 5.158033e-06, 5.146671e-06, 5.135556e-06, ..., 5.176134e-06,\n", + " 5.170886e-06, 5.165684e-06],\n", + " [ 4.978642e-06, 5.003572e-06, 5.029685e-06, ..., 4.947511e-06,\n", + " 4.960262e-06, 4.970894e-06],\n", + " [ 5.608857e-06, 5.626041e-06, 5.659296e-06, ..., 5.449484e-06,\n", + " 5.514129e-06, 5.578681e-06],\n", " ..., \n", - " [ 4.826577e-03, 5.116871e-03, 5.306013e-03, ..., 3.952671e-03,\n", - " 3.857220e-03, 4.159514e-03],\n", - " [ 3.559006e-04, 4.071099e-04, 4.688400e-04, ..., 3.086923e-04,\n", - " 3.293162e-04, 3.424217e-04],\n", - " [ 2.896832e-11, 4.326204e-11, 2.680294e-11, ..., 4.254056e-11,\n", - " 7.040103e-11, 9.109586e-11]])\n", + " [ 5.284707e-06, 5.260350e-06, 5.241916e-06, ..., 5.429388e-06,\n", + " 5.373469e-06, 5.316535e-06],\n", + " [ 4.975340e-06, 4.982203e-06, 4.983765e-06, ..., 4.975950e-06,\n", + " 4.970845e-06, 4.972452e-06],\n", + " [ 5.357783e-06, 5.319537e-06, 5.285620e-06, ..., 5.450081e-06,\n", + " 5.420615e-06, 5.394608e-06]])\n", " Coordinates:\n", " * lon (lon) float64 0.0 2.812 5.625 8.438 11.25 14.06 ...\n", " * lat (lat) float64 -87.86 -85.1 -82.31 -79.53 -76.74 ...\n", - " raw_data_start_date datetime64[ns] 1678-01-01\n", - " raw_data_end_date datetime64[ns] 1681-01-01\n", - " subset_start_date datetime64[ns] 1678-01-01\n", - " subset_end_date datetime64[ns] 1680-12-31\n", + " zsurf (lat, lon) float32 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...\n", + " raw_data_start_date object 0004-01-01 00:00:00\n", + " raw_data_end_date object 0007-01-01 00:00:00\n", + " subset_start_date object 0004-01-01 00:00:00\n", + " subset_end_date object 0006-12-31 00:00:00\n", " sfc_area (lat, lon) float64 3.553e+09 3.553e+09 3.553e+09 ...\n", - " land_mask (lat, lon) float64 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...,\n", - " 'reg.av': OrderedDict([('globe', <xarray.DataArray ()>\n", - " array(0.5979886366730033)\n", - " Coordinates:\n", - " raw_data_start_date datetime64[ns] 1678-01-01\n", - " raw_data_end_date datetime64[ns] 1681-01-01\n", - " subset_start_date datetime64[ns] 1678-01-01\n", - " subset_end_date datetime64[ns] 1680-12-31),\n", - " ('tropics', <xarray.DataArray ()>\n", - " array(0.8080250991579639)\n", - " Coordinates:\n", - " raw_data_start_date datetime64[ns] 1678-01-01\n", - " raw_data_end_date datetime64[ns] 1681-01-01\n", - " subset_start_date datetime64[ns] 1678-01-01\n", - " subset_end_date datetime64[ns] 1680-12-31)])}" + " land_mask (lat, lon) float64 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...\n", + " Attributes:\n", + " units: \n", + " description: Sum of convective and large-scale precipitation.\\n\\n Par...,\n", + " 'reg.av': <xarray.Dataset>\n", + " Dimensions: ()\n", + " Coordinates:\n", + " raw_data_start_date object 0004-01-01 00:00:00\n", + " raw_data_end_date object 0007-01-01 00:00:00\n", + " subset_start_date object 0004-01-01 00:00:00\n", + " subset_end_date object 0006-12-31 00:00:00\n", + " Data variables:\n", + " tropics float64 4.062e-05\n", + " globe float64 3.501e-05}" ] }, "execution_count": 15, @@ -636,21 +607,11 @@ "execution_count": 16, "metadata": {}, "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.\n", - " warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')\n", - "/home/skc/miniconda/envs/research/lib/python3.6/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.\n", - " warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')\n" - ] - }, { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAagAAAEYCAYAAAAJeGK1AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsvXm8bElV5/tdEXtn5jn33LpDFVUgVSBUAfrAAezWwlYR\nh1Z4Cu+1Q6uvFbAdWlFop6d229JO7dAqNiJKq83DVgaV14gTIoKACigIIgiIBZZVDAU13emczNw7\nYvUfMezYeTLP2Xeoe+6tyt/ncz4nc+/YESsid8SKtWINoqqsscYaa6yxxqUGc9AErLHGGmusscYy\nrBnUGmusscYalyTWDGqNNdZYY41LEmsGtcYaa6yxxiWJNYNaY4011ljjksSaQa2xxhprrHFJYs2g\nLiBE5GtE5JUHTceFgog8XET+WkROiMi3HTQ9a6wxBJfDPBSRB4uIF5H1GrwHZO0HtcYqiMivACdU\n9bsOmpY11riYEJGnAN+gqp99D5V/MPB+oFZVf+6U3rux5t4LEBF70DRcQngw8K5VN9e7vzXuKVwC\n81CAs9m9n235NQbgPrPAiMgHROT7RORdInKHiPyqiIxE5HEicouI/L8i8mHgf8TyXyIibxORu0Tk\nz0Tkk4q6rhWRl4nIR0XkYyLynHj9KSLyhqKcF5FvF5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text/plain": [ - "<matplotlib.figure.Figure at 0x7f5432d25780>" + "<matplotlib.figure.Figure at 0x11791dc18>" ] }, "metadata": {}, @@ -699,51 +660,59 @@ "name": "stdout", "output_type": "stream", "text": [ - "precip_conv_frac <xarray.Dataset>\n", + "precip_total <xarray.Dataset>\n", "Dimensions: ()\n", "Coordinates:\n", - " raw_data_start_date datetime64[ns] 1678-01-01\n", - " raw_data_end_date datetime64[ns] 1681-01-01\n", - " subset_start_date datetime64[ns] 1678-01-01\n", - " subset_end_date datetime64[ns] 1680-12-31\n", + " raw_data_start_date object 0004-01-01 00:00:00\n", + " subset_start_date object 0004-01-01 00:00:00\n", + " raw_data_end_date object 0007-01-01 00:00:00\n", + " subset_end_date object 0006-12-31 00:00:00\n", "Data variables:\n", - " globe float64 0.598\n", - " tropics float64 0.808 \n", + " tropics float64 3.51\n", + " globe float64 3.025 \n", "\n", - "precip_total <xarray.Dataset>\n", + "precip_conv_frac <xarray.Dataset>\n", "Dimensions: ()\n", "Coordinates:\n", - " raw_data_end_date datetime64[ns] 1681-01-01\n", - " subset_start_date datetime64[ns] 1678-01-01\n", - " subset_end_date datetime64[ns] 1680-12-31\n", - " raw_data_start_date datetime64[ns] 1678-01-01\n", + " raw_data_start_date object 0004-01-01 00:00:00\n", + " raw_data_end_date object 0007-01-01 00:00:00\n", + " subset_start_date object 0004-01-01 00:00:00\n", + " subset_end_date object 0006-12-31 00:00:00\n", "Data variables:\n", - " globe float64 3.025\n", - " tropics float64 3.51 \n", + " tropics float64 0.808\n", + " globe float64 0.598 \n", "\n", - "precip_convective <xarray.Dataset>\n", + "precip_largescale <xarray.Dataset>\n", "Dimensions: ()\n", "Coordinates:\n", - " raw_data_end_date datetime64[ns] 1681-01-01\n", - " subset_start_date datetime64[ns] 1678-01-01\n", - " subset_end_date datetime64[ns] 1680-12-31\n", - " raw_data_start_date datetime64[ns] 1678-01-01\n", + " raw_data_start_date object 0004-01-01 00:00:00\n", + " subset_start_date object 0004-01-01 00:00:00\n", + " raw_data_end_date object 0007-01-01 00:00:00\n", + " subset_end_date object 0006-12-31 00:00:00\n", "Data variables:\n", - " globe float64 2.11\n", - " tropics float64 3.055 \n", + " tropics float64 0.4551\n", + " globe float64 0.9149 \n", "\n", - "precip_largescale <xarray.Dataset>\n", + "precip_convective <xarray.Dataset>\n", "Dimensions: ()\n", "Coordinates:\n", - " raw_data_end_date datetime64[ns] 1681-01-01\n", - " subset_start_date datetime64[ns] 1678-01-01\n", - " subset_end_date datetime64[ns] 1680-12-31\n", - " raw_data_start_date datetime64[ns] 1678-01-01\n", + " raw_data_start_date object 0004-01-01 00:00:00\n", + " subset_start_date object 0004-01-01 00:00:00\n", + " raw_data_end_date object 0007-01-01 00:00:00\n", + " subset_end_date object 0006-12-31 00:00:00\n", "Data variables:\n", - " globe float64 0.9149\n", - " tropics float64 0.4551 \n", + " tropics float64 3.055\n", + " globe float64 2.11 \n", "\n" ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "//anaconda/envs/aospy_dev/lib/python3.6/site-packages/xarray/core/dataset.py:374: FutureWarning: iteration over an xarray.Dataset will change in xarray v0.11 to only include data variables, not coordinates. Iterate over the Dataset.variables property instead to preserve existing behavior in a forwards compatible manner.\n", + " both_data_and_coords = [k for k in data_vars if k in coords]\n" + ] } ], "source": [ @@ -804,6 +773,13 @@ "import shutil\n", "shutil.rmtree(example_proj.direc_out)" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { @@ -822,7 +798,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.3" + "version": "3.6.1" }, "latex_envs": { "LaTeX_envs_menu_present": true, diff --git a/aospy/utils/times.py b/aospy/utils/times.py index 08b0c89..9f8e7bd 100644 --- a/aospy/utils/times.py +++ b/aospy/utils/times.py @@ -1,11 +1,15 @@ """Utility functions for handling times, dates, etc.""" import datetime -import warnings +import logging +import re +import cftime import numpy as np import pandas as pd import xarray as xr +from pandas.errors import OutOfBoundsDatetime + from ..internal_names import ( BOUNDS_STR, GRID_ATTRS_NO_TIMES, RAW_END_DATE_STR, RAW_START_DATE_STR, SUBSET_END_DATE_STR, SUBSET_START_DATE_STR, TIME_BOUNDS_STR, TIME_STR, @@ -173,7 +177,7 @@ def yearly_average(arr, dt): def ensure_datetime(obj): - """Return the object if it is of type datetime.datetime; else raise. + """Return the object if it is a datetime-like object Parameters ---------- @@ -181,24 +185,24 @@ def ensure_datetime(obj): Returns ------- - The original object if it is a datetime.datetime object. + The original object if it is a datetime-like object Raises ------ - TypeError if `obj` is not of type `datetime.datetime`. + TypeError if `obj` is not datetime-like """ - if isinstance(obj, datetime.datetime): + if isinstance(obj, (str, datetime.datetime, cftime.datetime, np.datetime64)): return obj - raise TypeError("`datetime.datetime` object required. " + raise TypeError("datetime-like object required. " "Type given: {}".format(type(obj))) def datetime_or_default(date, default): - """Return a datetime.datetime object or a default. + """Return a datetime-like object or a default. Parameters ---------- - date : `None` or datetime-like object + date : `None` or datetime-like object or str default : The value to return if `date` is `None` Returns @@ -213,85 +217,6 @@ def datetime_or_default(date, default): return ensure_datetime(date) -def numpy_datetime_range_workaround(date, min_year, max_year): - """Reset a date to earliest allowable year if outside of valid range. - - Hack to address np.datetime64, and therefore pandas and xarray, not - supporting dates outside the range 1677-09-21 and 2262-04-11 due to - nanosecond precision. See e.g. - https://github.com/spencerahill/aospy/issues/96. - - - Parameters - ---------- - date : datetime.datetime object - min_year : int - Minimum year in the raw decoded dataset - max_year : int - Maximum year in the raw decoded dataset - - Returns - ------- - datetime.datetime object - Original datetime.datetime object if the original date is within the - permissible dates, otherwise a datetime.datetime object with the year - offset to the earliest allowable year. - """ - min_yr_in_range = pd.Timestamp.min.year < min_year < pd.Timestamp.max.year - max_yr_in_range = pd.Timestamp.min.year < max_year < pd.Timestamp.max.year - if not (min_yr_in_range and max_yr_in_range): - return datetime.datetime( - date.year - min_year + pd.Timestamp.min.year + 1, - date.month, date.day) - return date - - -def numpy_datetime_workaround_encode_cf(ds): - """Generate CF-compliant units for out-of-range dates. - - Hack to address np.datetime64, and therefore pandas and xarray, not - supporting dates outside the range 1677-09-21 and 2262-04-11 due to - nanosecond precision. See e.g. - https://github.com/spencerahill/aospy/issues/96. - - Specifically, we coerce the data such that, when decoded, the earliest - value starts in 1678 but with its month, day, and shorter timescales - (hours, minutes, seconds, etc.) intact and with the time-spacing between - values intact. - - Parameters - ---------- - ds : xarray.Dataset - - Returns - ------- - xarray.Dataset, int, int - Dataset with time units adjusted as needed, minimum year - in loaded data, and maximum year in loaded data. - """ - time = ds[TIME_STR] - units = time.attrs['units'] - units_yr = units.split(' since ')[1].split('-')[0] - with warnings.catch_warnings(record=True): - min_yr_decoded = xr.decode_cf(time.to_dataset(name='dummy')) - min_date = min_yr_decoded[TIME_STR].values[0] - max_date = min_yr_decoded[TIME_STR].values[-1] - if all(isinstance(date, np.datetime64) for date in [min_date, max_date]): - return ds, pd.Timestamp(min_date).year, pd.Timestamp(max_date).year - else: - min_yr = min_date.year - max_yr = max_date.year - offset = int(units_yr) - min_yr + 1 - new_units_yr = pd.Timestamp.min.year + offset - new_units = units.replace(units_yr, str(new_units_yr)) - - for VAR_STR in TIME_VAR_STRS: - if VAR_STR in ds: - var = ds[VAR_STR] - var.attrs['units'] = new_units - return ds, min_yr, max_yr - - def month_indices(months): """Convert string labels for months to integer indices. @@ -462,9 +387,9 @@ def _assert_has_data_for_time(da, start_date, end_date): ---------- da : DataArray DataArray with a time variable - start_date : netCDF4.netcdftime or np.datetime64 + start_date : datetime-like object or str start date - end_date : netCDF4.netcdftime or np.datetime64 + end_date : datetime-like object or str end date Raises @@ -472,6 +397,16 @@ def _assert_has_data_for_time(da, start_date, end_date): AssertionError if the time range is not within the time range of the DataArray """ + if isinstance(start_date, str) and isinstance(end_date, str): + logging.warning( + 'When using strings to specify start and end dates, the check ' + 'to determine if data exists for the full extent of the desired ' + 'interval is not implemented. Therefore it is possible that ' + 'you are doing a calculation for a lesser interval than you ' + 'specified. If you would like this check to occur, use explicit ' + 'datetime-like objects for bounds instead.') + return + if RAW_START_DATE_STR in da.coords: da_start = da[RAW_START_DATE_STR].values da_end = da[RAW_END_DATE_STR].values @@ -480,7 +415,11 @@ def _assert_has_data_for_time(da, start_date, end_date): da_start, da_end = times.values message = ('Data does not exist for requested time range: {0} to {1};' ' found data from time range: {2} to {3}.') - range_exists = start_date >= da_start and end_date <= da_end + # Add tolerance of one second, due to precision of cftime.datetimes + tol = datetime.timedelta(seconds=1) + if isinstance(da_start, np.datetime64): + tol = np.timedelta64(tol, 'ns') + range_exists = (da_start - tol) <= start_date and (da_end + tol) >= end_date assert (range_exists), message.format(start_date, end_date, da_start, da_end) @@ -571,3 +510,95 @@ def ensure_time_as_index(ds): da[TIME_STR] = ds[TIME_STR] ds[name] = da return ds + + +def infer_year(date): + """Given a datetime-like object or string infer the year. + + Parameters + ---------- + date : datetime-like object or str + Input date + + Returns + ------- + int + + Examples + -------- + >>> infer_year('2000') + 2000 + >>> infer_year('2000-01') + 2000 + >>> infer_year('2000-01-31') + 2000 + >>> infer_year(datetime.datetime(2000, 1, 1)) + 2000 + >>> infer_year(np.datetime64('2000-01-01')) + 2000 + >>> infer_year(DatetimeNoLeap(2000, 1, 1)) + 2000 + >>> + """ + if isinstance(date, str): + # Look for a string that begins with four numbers; the first four + # numbers found are the year. + pattern = '(?P<year>\d{4})' + result = re.match(pattern, date) + if result: + return int(result.groupdict()['year']) + else: + raise ValueError('Invalid date string provided: {}'.format(date)) + elif isinstance(date, np.datetime64): + return date.item().year + else: + return date.year + + +def maybe_convert_to_index_date_type(index, date): + """Convert a datetime-like object to the index's date type. + + Datetime indexing in xarray can be done using either a pandas + DatetimeIndex or a CFTimeIndex. Both support partial-datetime string + indexing regardless of the calendar type of the underlying data; + therefore if a string is passed as a date, we return it unchanged. If a + datetime-like object is provided, it will be converted to the underlying + date type of the index. For a DatetimeIndex that is np.datetime64; for a + CFTimeIndex that is an object of type cftime.datetime specific to the + calendar used. + + Parameters + ---------- + index : pd.Index + Input time index + date : datetime-like object or str + Input datetime + + Returns + ------- + date of the type appropriate for the time index of the Dataset + """ + if isinstance(date, str): + return date + + if isinstance(index, pd.DatetimeIndex): + if isinstance(date, np.datetime64): + return date + else: + return np.datetime64(str(date)) + else: + date_type = index.date_type + if isinstance(date, date_type): + return date + else: + if isinstance(date, np.datetime64): + # Convert to datetime.date or datetime.datetime object + date = date.item() + + if isinstance(date, datetime.date): + # Convert to a datetime.datetime object + date = datetime.datetime.combine( + date, datetime.datetime.min.time()) + + return date_type(date.year, date.month, date.day, date.hour, + date.minute, date.second, date.microsecond) diff --git a/appveyor.yml b/appveyor.yml index 5ee68d9..b377849 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -5,9 +5,9 @@ environment: matrix: - - PYTHON: "C:\\Python27-conda32" + - PYTHON: "C:\\Python27-conda64" PYTHON_VERSION: "2.7" - PYTHON_ARCH: "32" + PYTHON_ARCH: "64" CONDA_ENV: "py27" - PYTHON: "C:\\Python35-conda64" @@ -41,4 +41,4 @@ install: build: false test_script: - - "py.test aospy --verbose" \ No newline at end of file + - "py.test aospy --verbose" diff --git a/docs/examples.rst b/docs/examples.rst index 6402eba..a988850 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -97,9 +97,28 @@ a name for the run and an optional description. example_run = Run( name='example_run', description='Control simulation of the idealized moist model', - data_loader=data_loader + data_loader=data_loader, + default_start_date='0004', + default_end_date='0006' ) +.. note:: + + Throughout aospy, date slice bounds can be specified with dates of any of + the following types: + + - ``str``, for partial-datetime string indexing + - ``np.datetime64`` + - ``datetime.datetime`` + - ``cftime.datetime`` + + If possible, aospy will automatically convert the latter three to the + appropriate date type used for indexing the data read in; otherwise it will + raise an error. Therefore the arguments ``default_start_date`` and + ``default_end_date`` in the ``Run`` constructor are calendar-agnostic (as + are the ``date_ranges`` specified :ref:`when submitting + calculations<Submitting calculations>`). + .. note:: See the :ref:`API reference <api-ref>` for other optional arguments @@ -189,18 +208,18 @@ that we saw are directly available as model output: from aospy import Var - precip_largescale = Var( - name='precip_largescale', # name used by aospy - alt_names=('condensation_rain',), # its possible name(s) in your data - def_time=True, # whether or not it is defined in time - description='Precipitation generated via grid-scale condensation', - ) - precip_convective = Var( - name='precip_convective', - alt_names=('convection_rain', 'prec_conv'), - def_time=True, - description='Precipitation generated by convective parameterization', - ) + precip_largescale = Var( + name='precip_largescale', # name used by aospy + alt_names=('condensation_rain',), # its possible name(s) in your data + def_time=True, # whether or not it is defined in time + description='Precipitation generated via grid-scale condensation', + ) + precip_convective = Var( + name='precip_convective', + alt_names=('convection_rain', 'prec_conv'), + def_time=True, + description='Precipitation generated by convective parameterization', + ) When it comes time to load data corresponding to either of these from one or more particular netCDF files, aospy will search for variables @@ -338,6 +357,8 @@ Submitting calculations Using :py:func:`aospy.submit_mult_calcs` ======================================== +.. _Submitting calculations: + Having put in the legwork above of describing our data and the physical quantities we wish to compute, we can submit our desired calculations for execution using :py:func:`aospy.submit_mult_calcs`. @@ -402,6 +423,17 @@ Although we do not show it here, this also prints logging information to the terminal at various steps during each calculation, including the filepaths to the netCDF files written to disk of the results. +.. warning:: + + For date ranges specified using tuples of datetime-like objects, + ``aospy`` will check to make sure that datapoints exist for the full extent + of the time ranges specified. For date ranges specified as tuples of + strings, however, this check is currently not implemented. This is mostly + harmless (i.e. it will not change the results of calculations); however, it + can result in files whose labels do not accurately represent the actual + time bounds of the calculation if you specify string date ranges that span + more than the interval of the input data. + Results ======= @@ -432,19 +464,6 @@ and the results of each output type quantity is, even if you don't have the original ``Var`` definition on hand. -.. note:: - - You may have noticed that ``subset_...`` and ``raw_...`` - coordinates have years 1678 and later, when our data was from model - years 4 through 6. This is because `technical details upstream - <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#timestamp-limitations>`_ limit the range of supported whole years to 1678-2262. - - As a workaround, aospy pretends that any timeseries that starts - before the beginning of this range actually starts at 1678. An - upstream fix is `currently under way - <https://github.com/pydata/xarray/issues/1084>`_, at which point - all dates will be supported without this workaround. - Gridpoint-by-gridpoint ~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/whats-new.rst b/docs/whats-new.rst index 66af034..3a42699 100644 --- a/docs/whats-new.rst +++ b/docs/whats-new.rst @@ -44,6 +44,11 @@ Documentation Enhancements ~~~~~~~~~~~~ +- Use an ``xarray.CFTimeIndex`` for dates from non-standard calendars and + outside the Timestamp-valid range. This eliminates the need for the prior + workaround, which shifted dates to within the range 1678 to 2262 prior to + indexing (closes :issue:`98` via :pull:`273`). By + `Spencer Clark <https://github.com/spencerkclark>`_. - Create ``utils.longitude`` module and ``Longitude`` class for representing and comparing longitudes. Used internally by ``aospy.Region`` to construct masks, but could also be useful for @@ -137,9 +142,9 @@ Dependencies - ``aospy`` now requires a minimum version of ``distributed`` of 1.17.1 (fixes :issue:`210` via :pull:`211`). -- ``aospy`` now requires a minimum version of ``xarray`` of 0.10.3. - See discussion in :issue:`199`, :pull:`240`, :issue:`268`, and - :pull:`269` for more details. +- ``aospy`` now requires a minimum version of ``xarray`` of 0.10.4. + See discussion in :issue:`199`, :pull:`240`, :issue:`268`, + :pull:`269`, and :pull:`273` for more details. .. _whats-new.0.2: diff --git a/setup.py b/setup.py index bb659f5..9c1537b 100644 --- a/setup.py +++ b/setup.py @@ -33,8 +33,9 @@ setuptools.setup( 'toolz >= 0.7.2', 'dask >= 0.14', 'distributed >= 1.17.1', - 'xarray >= 0.10.3', - 'cloudpickle >= 0.2.1'], + 'xarray >= 0.10.4', + 'cloudpickle >= 0.2.1', + 'cftime >= 1.0.0'], tests_require=['pytest >= 2.7.1', 'pytest-catchlog >= 1.0'], package_data={'aospy': ['test/data/netcdf/*.nc']},
Restore original datetime metadata upon saving output Currently, if we encounter time dimensions referenced to a date prior to 1678-01-01, we automatically offset things internally such that the dates aospy sees all begin at 1900-01-01 (this is to account for restrictions in `pandas`). When we save computational results to netCDF files, however, we do not currently restore datetime metadata to match the way things were in the initial run (so output netCDF files look as though things started in 1900 as well). This may amount to simply saving the initial units attribute of the time variable when reading in the file, and resetting it to the initial value when we save data. In addressing this issue I think we should also consider changing the offset reference date to 1678-01-01 to allow the maximum available `pandas` / `np.datetime64` compatible time range.
spencerahill/aospy
diff --git a/aospy/test/data/objects/examples.py b/aospy/test/data/objects/examples.py index 7ddb311..6087f9a 100644 --- a/aospy/test/data/objects/examples.py +++ b/aospy/test/data/objects/examples.py @@ -1,6 +1,7 @@ -from datetime import datetime import os +from cftime import DatetimeNoLeap + from aospy import Proj, Model, Run, Var, Region from aospy.data_loader import NestedDictDataLoader @@ -25,8 +26,8 @@ example_run = Run( 'Control simulation of the idealized moist model' ), data_loader=NestedDictDataLoader(file_map), - default_start_date=datetime(4, 1, 1), - default_end_date=datetime(6, 12, 31) + default_start_date=DatetimeNoLeap(4, 1, 1), + default_end_date=DatetimeNoLeap(6, 12, 31) ) example_model = Model( diff --git a/aospy/test/test_calc_basic.py b/aospy/test/test_calc_basic.py index b36e0aa..b36a530 100755 --- a/aospy/test/test_calc_basic.py +++ b/aospy/test/test_calc_basic.py @@ -7,6 +7,8 @@ import unittest import pytest import itertools +import cftime +import numpy as np import xarray as xr from aospy import Var @@ -18,19 +20,20 @@ from .data.objects.examples import ( def _test_output_attrs(calc, dtype_out): - with xr.open_dataset(calc.path_out[dtype_out]) as data: - expected_units = calc.var.units - if calc.dtype_out_vert == 'vert_int': - if expected_units != '': - expected_units = ("(vertical integral of {0}):" - " {0} m)").format(expected_units) - else: - expected_units = ("(vertical integral of quantity" - " with unspecified units)") - expected_description = calc.var.description - for name, arr in data.data_vars.items(): - assert expected_units == arr.attrs['units'] - assert expected_description == arr.attrs['description'] + with xr.set_options(enable_cftimeindex=True): + with xr.open_dataset(calc.path_out[dtype_out]) as data: + expected_units = calc.var.units + if calc.dtype_out_vert == 'vert_int': + if expected_units != '': + expected_units = ("(vertical integral of {0}):" + " {0} m)").format(expected_units) + else: + expected_units = ("(vertical integral of quantity" + " with unspecified units)") + expected_description = calc.var.description + for name, arr in data.data_vars.items(): + assert expected_units == arr.attrs['units'] + assert expected_description == arr.attrs['description'] def _test_files_and_attrs(calc, dtype_out): @@ -39,109 +42,122 @@ def _test_files_and_attrs(calc, dtype_out): _test_output_attrs(calc, dtype_out) -_BASIC_TEST_PARAMS = { - 'proj': example_proj, - 'model': example_model, - 'run': example_run, - 'var': condensation_rain, - 'date_range': (datetime.datetime(4, 1, 1), - datetime.datetime(6, 12, 31)), - 'intvl_in': 'monthly', - 'dtype_in_time': 'ts' +_2D_DATE_RANGES = { + 'datetime': (datetime.datetime(4, 1, 1), datetime.datetime(6, 12, 31)), + 'datetime64': (np.datetime64('0004-01-01'), np.datetime64('0006-12-31')), + 'cftime': (cftime.DatetimeNoLeap(4, 1, 1), + cftime.DatetimeNoLeap(6, 12, 31)), + 'str': ('0004', '0006') } +_3D_DATE_RANGES = { + 'datetime': (datetime.datetime(6, 1, 1), datetime.datetime(6, 1, 31)), + 'datetime64': (np.datetime64('0006-01-01'), np.datetime64('0006-01-31')), + 'cftime': (cftime.DatetimeNoLeap(6, 1, 1), + cftime.DatetimeNoLeap(6, 1, 31)) + # 'str': ('0006', '0006') TODO: This should work once xarray version + # 0.10.5 is released +} +_2D_VARS = {'basic': condensation_rain, 'composite': precip} +_2D_DTYPE_OUT_VERT = {'None': None} +_2D_DTYPE_IN_VERT = {'None': None} +_3D_VARS = {'3D': sphum} +_3D_DTYPE_OUT_VERT = {'vert_int': 'vert_int'} +_3D_DTYPE_IN_VERT = {'sigma': 'sigma'} +_CASES = ( + list(itertools.product(_2D_DATE_RANGES.items(), _2D_VARS.items(), + _2D_DTYPE_IN_VERT.items(), + _2D_DTYPE_OUT_VERT.items())) + + list(itertools.product(_3D_DATE_RANGES.items(), _3D_VARS.items(), + _3D_DTYPE_IN_VERT.items(), + _3D_DTYPE_OUT_VERT.items())) +) +_CALC_TESTS = {} +for ((date_type, date_range), (test_type, var), + (vert_in_label, vert_in), (vert_out_label, vert_out)) in _CASES: + _CALC_TESTS['{}-{}-{}-{}'.format( + date_type, test_type, vert_in_label, vert_out_label)] = ( + date_range, var, vert_in, vert_out) + + [email protected](params=_CALC_TESTS.values(), ids=list(_CALC_TESTS.keys())) +def test_params(request): + date_range, var, vert_in, vert_out = request.param + yield { + 'proj': example_proj, + 'model': example_model, + 'run': example_run, + 'var': var, + 'date_range': date_range, + 'intvl_in': 'monthly', + 'dtype_in_time': 'ts', + 'dtype_in_vert': vert_in, + 'dtype_out_vert': vert_out + } + for direc in [example_proj.direc_out, example_proj.tar_direc_out]: + try: + shutil.rmtree(direc) + except OSError: + pass + + +def test_annual_mean(test_params): + calc = Calc(intvl_out='ann', dtype_out_time='av', **test_params) + calc.compute() + _test_files_and_attrs(calc, 'av') + + +def test_annual_ts(test_params): + calc = Calc(intvl_out='ann', dtype_out_time='ts', **test_params) + calc.compute() + _test_files_and_attrs(calc, 'ts') + + +def test_seasonal_mean(test_params): + calc = Calc(intvl_out='djf', dtype_out_time='av', **test_params) + calc.compute() + _test_files_and_attrs(calc, 'av') + + +def test_seasonal_ts(test_params): + calc = Calc(intvl_out='djf', dtype_out_time='ts', **test_params) + calc.compute() + _test_files_and_attrs(calc, 'ts') + + +def test_monthly_mean(test_params): + calc = Calc(intvl_out=1, dtype_out_time='av', **test_params) + calc.compute() + _test_files_and_attrs(calc, 'av') + + +def test_monthly_ts(test_params): + calc = Calc(intvl_out=1, dtype_out_time='ts', **test_params) + calc.compute() + _test_files_and_attrs(calc, 'ts') + + +def test_simple_reg_av(test_params): + calc = Calc(intvl_out='ann', dtype_out_time='reg.av', region=[globe], + **test_params) + calc.compute() + _test_files_and_attrs(calc, 'reg.av') + + +def test_simple_reg_ts(test_params): + calc = Calc(intvl_out='ann', dtype_out_time='reg.ts', region=[globe], + **test_params) + calc.compute() + _test_files_and_attrs(calc, 'reg.ts') + + +def test_complex_reg_av(test_params): + calc = Calc(intvl_out='ann', dtype_out_time='reg.av', region=[sahel], + **test_params) + calc.compute() + _test_files_and_attrs(calc, 'reg.av') -class TestCalcBasic(unittest.TestCase): - def setUp(self): - self.test_params = _BASIC_TEST_PARAMS.copy() - - def tearDown(self): - for direc in [example_proj.direc_out, example_proj.tar_direc_out]: - try: - shutil.rmtree(direc) - except OSError: - pass - - def test_annual_mean(self): - calc = Calc(intvl_out='ann', dtype_out_time='av', **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'av') - - def test_annual_ts(self): - calc = Calc(intvl_out='ann', dtype_out_time='ts', **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'ts') - - def test_seasonal_mean(self): - calc = Calc(intvl_out='djf', dtype_out_time='av', **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'av') - - def test_seasonal_ts(self): - calc = Calc(intvl_out='djf', dtype_out_time='ts', **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'ts') - - def test_monthly_mean(self): - calc = Calc(intvl_out=1, dtype_out_time='av', **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'av') - - def test_monthly_ts(self): - calc = Calc(intvl_out=1, dtype_out_time='ts', **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'ts') - - def test_simple_reg_av(self): - calc = Calc(intvl_out='ann', dtype_out_time='reg.av', region=[globe], - **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'reg.av') - - def test_simple_reg_ts(self): - calc = Calc(intvl_out='ann', dtype_out_time='reg.ts', region=[globe], - **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'reg.ts') - - def test_complex_reg_av(self): - calc = Calc(intvl_out='ann', dtype_out_time='reg.av', region=[sahel], - **self.test_params) - calc.compute() - _test_files_and_attrs(calc, 'reg.av') - - -class TestCalcComposite(TestCalcBasic): - def setUp(self): - self.test_params = { - 'proj': example_proj, - 'model': example_model, - 'run': example_run, - 'var': precip, - 'date_range': (datetime.datetime(4, 1, 1), - datetime.datetime(6, 12, 31)), - 'intvl_in': 'monthly', - 'dtype_in_time': 'ts' - } - - -class TestCalc3D(TestCalcBasic): - def setUp(self): - self.test_params = { - 'proj': example_proj, - 'model': example_model, - 'run': example_run, - 'var': sphum, - 'date_range': (datetime.datetime(6, 1, 1), - datetime.datetime(6, 1, 31)), - 'intvl_in': 'monthly', - 'dtype_in_time': 'ts', - 'dtype_in_vert': 'sigma', - 'dtype_out_vert': 'vert_int' - } - - -test_params = { +test_params_not_time_defined = { 'proj': example_proj, 'model': example_model, 'run': example_run, @@ -155,8 +171,8 @@ test_params = { @pytest.mark.parametrize('dtype_out_time', [None, []]) def test_calc_object_no_time_options(dtype_out_time): - test_params['dtype_out_time'] = dtype_out_time - calc = Calc(**test_params) + test_params_not_time_defined['dtype_out_time'] = dtype_out_time + calc = Calc(**test_params_not_time_defined) if isinstance(dtype_out_time, list): assert calc.dtype_out_time == tuple(dtype_out_time) else: @@ -167,9 +183,9 @@ def test_calc_object_no_time_options(dtype_out_time): 'dtype_out_time', ['av', 'std', 'ts', 'reg.av', 'reg.std', 'reg.ts']) def test_calc_object_string_time_options(dtype_out_time): - test_params['dtype_out_time'] = dtype_out_time + test_params_not_time_defined['dtype_out_time'] = dtype_out_time with pytest.raises(ValueError): - Calc(**test_params) + Calc(**test_params_not_time_defined) def test_calc_object_time_options(): @@ -177,9 +193,9 @@ def test_calc_object_time_options(): for i in range(1, len(time_options) + 1): for time_option in list(itertools.permutations(time_options, i)): if time_option != ('None',): - test_params['dtype_out_time'] = time_option + test_params_not_time_defined['dtype_out_time'] = time_option with pytest.raises(ValueError): - Calc(**test_params) + Calc(**test_params_not_time_defined) @pytest.mark.parametrize( @@ -216,7 +232,16 @@ def test_attrs(units, description, dtype_out_vert, expected_units, @pytest.fixture() def recursive_test_params(): - basic_params = _BASIC_TEST_PARAMS.copy() + basic_params = { + 'proj': example_proj, + 'model': example_model, + 'run': example_run, + 'var': condensation_rain, + 'date_range': (datetime.datetime(4, 1, 1), + datetime.datetime(6, 12, 31)), + 'intvl_in': 'monthly', + 'dtype_in_time': 'ts' + } recursive_params = basic_params.copy() recursive_condensation_rain = Var( @@ -236,14 +261,16 @@ def test_recursive_calculation(recursive_test_params): calc = Calc(intvl_out='ann', dtype_out_time='av', **basic_params) calc = calc.compute() - expected = xr.open_dataset( - calc.path_out['av'], autoclose=True)['condensation_rain'] + with xr.set_options(enable_cftimeindex=True): + expected = xr.open_dataset( + calc.path_out['av'], autoclose=True)['condensation_rain'] _test_files_and_attrs(calc, 'av') calc = Calc(intvl_out='ann', dtype_out_time='av', **recursive_params) calc = calc.compute() - result = xr.open_dataset( - calc.path_out['av'], autoclose=True)['recursive_condensation_rain'] + with xr.set_options(enable_cftimeindex=True): + result = xr.open_dataset( + calc.path_out['av'], autoclose=True)['recursive_condensation_rain'] _test_files_and_attrs(calc, 'av') xr.testing.assert_equal(expected, result) diff --git a/aospy/test/test_data_loader.py b/aospy/test/test_data_loader.py index 852ea7c..38133e5 100644 --- a/aospy/test/test_data_loader.py +++ b/aospy/test/test_data_loader.py @@ -1,6 +1,6 @@ #!/usr/bin/env python """Test suite for aospy.data_loader module.""" -from datetime import datetime +import datetime import os import unittest import warnings @@ -9,6 +9,8 @@ import numpy as np import pytest import xarray as xr +from cftime import DatetimeNoLeap + from aospy import Var from aospy.data_loader import (DataLoader, DictDataLoader, GFDLDataLoader, NestedDictDataLoader, grid_attrs_to_aospy_names, @@ -21,7 +23,7 @@ from aospy.internal_names import (LAT_STR, LON_STR, TIME_STR, TIME_BOUNDS_STR, TIME_WEIGHTS_STR, GRID_ATTRS, ZSURF_STR) from aospy.utils import io from .data.objects.examples import (condensation_rain, convection_rain, precip, - example_run, ROOT_PATH) + file_map, ROOT_PATH) def _open_ds_catch_warnings(path): @@ -39,612 +41,751 @@ def test_maybe_cast_to_float64(input_dtype, expected_dtype): assert result == expected_dtype -class AospyDataLoaderTestCase(unittest.TestCase): - def setUp(self): - self.DataLoader = DataLoader() - self.generate_file_set_args = dict( - var=condensation_rain, start_date=datetime(2000, 1, 1), - end_date=datetime(2002, 12, 31), domain='atmos', - intvl_in='monthly', dtype_in_vert='sigma', dtype_in_time='ts', - intvl_out=None) - time_bounds = np.array([[0, 31], [31, 59], [59, 90]]) - bounds = np.array([0, 1]) - time = np.array([15, 46, 74]) - data = np.zeros((3, 1, 1)) - lat = [0] - lon = [0] - self.ALT_LAT_STR = 'LATITUDE' - self.var_name = 'a' - ds = xr.DataArray(data, - coords=[time, lat, lon], - dims=[TIME_STR, self.ALT_LAT_STR, LON_STR], - name=self.var_name).to_dataset() - ds[TIME_BOUNDS_STR] = xr.DataArray(time_bounds, - coords=[time, bounds], - dims=[TIME_STR, BOUNDS_STR], - name=TIME_BOUNDS_STR) - units_str = 'days since 2000-01-01 00:00:00' - ds[TIME_STR].attrs['units'] = units_str - ds[TIME_BOUNDS_STR].attrs['units'] = units_str - self.ds = ds - - inst_time = np.array([3, 6, 9]) - inst_units_str = 'hours since 2000-01-01 00:00:00' - inst_ds = ds.copy() - inst_ds.drop(TIME_BOUNDS_STR) - inst_ds[TIME_STR].values = inst_time - inst_ds[TIME_STR].attrs['units'] = inst_units_str - self.inst_ds = inst_ds - - def tearDown(self): - pass - - -class TestDataLoader(AospyDataLoaderTestCase): - def test_rename_grid_attrs_ds(self): - assert LAT_STR not in self.ds - assert self.ALT_LAT_STR in self.ds - ds = grid_attrs_to_aospy_names(self.ds) - assert LAT_STR in ds - - def test_rename_grid_attrs_dim_no_coord(self): - bounds_dim = 'nv' - assert bounds_dim not in self.ds - assert bounds_dim in GRID_ATTRS[BOUNDS_STR] - # Create DataArray with all dims lacking coords - values = self.ds[self.var_name].values - arr = xr.DataArray(values, name='dummy') - # Insert name to be replaced (its physical meaning doesn't matter here) - ds = arr.rename({'dim_0': bounds_dim}).to_dataset() - assert not ds[bounds_dim].coords - result = grid_attrs_to_aospy_names(ds) - assert not result[BOUNDS_STR].coords - - def test_rename_grid_attrs_skip_scalar_dim(self): - phalf_dim = 'phalf' - assert phalf_dim not in self.ds - assert phalf_dim in GRID_ATTRS[PHALF_STR] - ds = self.ds.copy() - ds[phalf_dim] = 4 - ds = ds.set_coords(phalf_dim) - result = grid_attrs_to_aospy_names(ds) - xr.testing.assert_identical(result[phalf_dim], ds[phalf_dim]) - - def test_rename_grid_attrs_copy_attrs(self): - orig_attrs = {'dummy_key': 'dummy_val'} - ds_orig = self.ds.copy() - ds_orig[self.ALT_LAT_STR].attrs = orig_attrs - ds = grid_attrs_to_aospy_names(ds_orig) - self.assertEqual(ds[LAT_STR].attrs, orig_attrs) - - def test_set_grid_attrs_as_coords(self): - ds = grid_attrs_to_aospy_names(self.ds) - sfc_area = ds[self.var_name].isel(**{TIME_STR: 0}).drop(TIME_STR) - ds[SFC_AREA_STR] = sfc_area - - assert SFC_AREA_STR not in ds.coords - - ds = set_grid_attrs_as_coords(ds) - assert SFC_AREA_STR in ds.coords - assert TIME_BOUNDS_STR in ds.coords - - def test_sel_var(self): - time = np.array([0, 31, 59]) + 15 - data = np.zeros((3)) - ds = xr.DataArray(data, - coords=[time], - dims=[TIME_STR], - name=convection_rain.name).to_dataset() - condensation_rain_alt_name, = condensation_rain.alt_names - ds[condensation_rain_alt_name] = xr.DataArray(data, coords=[ds.time]) - result = _sel_var(ds, convection_rain) - self.assertEqual(result.name, convection_rain.name) - - result = _sel_var(ds, condensation_rain) - self.assertEqual(result.name, condensation_rain.name) - - with self.assertRaises(LookupError): - _sel_var(ds, precip) - - def test_maybe_apply_time_shift(self): - ds = xr.decode_cf(self.ds) - da = ds[self.var_name] - - result = self.DataLoader._maybe_apply_time_shift( - da.copy(), **self.generate_file_set_args)[TIME_STR] - assert result.identical(da[TIME_STR]) - - offset = self.DataLoader._maybe_apply_time_shift( - da.copy(), {'days': 1}, **self.generate_file_set_args) - result = offset[TIME_STR] - - expected = da[TIME_STR] + np.timedelta64(1, 'D') - expected[TIME_STR] = expected - - assert result.identical(expected) - - def test_generate_file_set(self): - with self.assertRaises(NotImplementedError): - self.DataLoader._generate_file_set() - - def test_prep_time_data(self): - assert (TIME_WEIGHTS_STR not in self.inst_ds) - ds, min_year, max_year = _prep_time_data(self.inst_ds) - assert (TIME_WEIGHTS_STR in ds) - self.assertEqual(min_year, 2000) - self.assertEqual(max_year, 2000) - - def test_preprocess_and_rename_grid_attrs(self): - def preprocess_func(ds, **kwargs): - # Corrupt a grid attribute name so that we test - # that grid_attrs_to_aospy_names is still called - # after - ds = ds.rename({LON_STR: 'LONGITUDE'}) - ds.attrs['a'] = 'b' - return ds - - assert LAT_STR not in self.ds - assert self.ALT_LAT_STR in self.ds - assert LON_STR in self.ds - - expected = self.ds.rename({self.ALT_LAT_STR: LAT_STR}) - expected = expected.set_coords(TIME_BOUNDS_STR) - expected.attrs['a'] = 'b' - result = _preprocess_and_rename_grid_attrs(preprocess_func)(self.ds) - xr.testing.assert_identical(result, expected) - - -class TestDictDataLoader(TestDataLoader): - def setUp(self): - super(TestDictDataLoader, self).setUp() - file_map = {'monthly': ['a.nc']} - self.DataLoader = DictDataLoader(file_map) - - def test_generate_file_set(self): - result = self.DataLoader._generate_file_set( - **self.generate_file_set_args) - expected = ['a.nc'] - self.assertEqual(result, expected) +_DATE_RANGES = { + 'datetime': (datetime.datetime(2000, 1, 1), + datetime.datetime(2002, 12, 31)), + 'datetime64': (np.datetime64('2000-01-01'), + np.datetime64('2002-12-31')), + 'cftime': (DatetimeNoLeap(2000, 1, 1), + DatetimeNoLeap(2002, 12, 31)), + 'str': ('2000', '2002') +} + + [email protected](params=_DATE_RANGES.values(), ids=list(_DATE_RANGES.keys())) +def generate_file_set_args(request): + start_date, end_date = request.param + return dict( + var=condensation_rain, start_date=start_date, end_date=end_date, + domain='atmos', intvl_in='monthly', dtype_in_vert='sigma', + dtype_in_time='ts', intvl_out=None) + + [email protected]() +def alt_lat_str(): + return 'LATITUDE' + + [email protected]() +def var_name(): + return 'a' + + [email protected]() +def ds(alt_lat_str, var_name): + time_bounds = np.array([[0, 31], [31, 59], [59, 90]]) + bounds = np.array([0, 1]) + time = np.array([15, 46, 74]) + data = np.zeros((3, 1, 1)) + lat = [0] + lon = [0] + ds = xr.DataArray(data, + coords=[time, lat, lon], + dims=[TIME_STR, alt_lat_str, LON_STR], + name=var_name).to_dataset() + ds[TIME_BOUNDS_STR] = xr.DataArray(time_bounds, + coords=[time, bounds], + dims=[TIME_STR, BOUNDS_STR], + name=TIME_BOUNDS_STR) + units_str = 'days since 2000-01-01 00:00:00' + ds[TIME_STR].attrs['units'] = units_str + ds[TIME_BOUNDS_STR].attrs['units'] = units_str + return ds + + [email protected]() +def inst_ds(ds): + inst_time = np.array([3, 6, 9]) + inst_units_str = 'hours since 2000-01-01 00:00:00' + inst_ds = ds.copy() + inst_ds.drop(TIME_BOUNDS_STR) + inst_ds[TIME_STR].values = inst_time + inst_ds[TIME_STR].attrs['units'] = inst_units_str + return inst_ds + + +def _gfdl_data_loader_kwargs(data_start_date, data_end_date): + return dict(data_direc=os.path.join('.', 'test'), + data_dur=6, + data_start_date=data_start_date, + data_end_date=data_end_date, + upcast_float32=False, + data_vars='minimal', + coords='minimal') + + +_DATA_LOADER_KWARGS = { + 'DataLoader': (DataLoader, {}), + 'DictDataLoader': (DictDataLoader, dict(file_map={'monthly': ['a.nc']})), + 'NestedDictDataLoader': ( + NestedDictDataLoader, + dict(file_map={'monthly': {'condensation_rain': ['a.nc']}})), + 'GFDLDataLoader-datetime': ( + GFDLDataLoader, _gfdl_data_loader_kwargs( + datetime.datetime(2000, 1, 1), datetime.datetime(2012, 12, 31))), + 'GFDLDataLoader-datetime64': ( + GFDLDataLoader, _gfdl_data_loader_kwargs( + np.datetime64('2000-01-01'), np.datetime64('2012-12-31'))), + 'GFDLDataLoader-cftime': ( + GFDLDataLoader, _gfdl_data_loader_kwargs( + DatetimeNoLeap(2000, 1, 1), DatetimeNoLeap(2012, 12, 31))), + 'GFDLDataLoader-str': ( + GFDLDataLoader, _gfdl_data_loader_kwargs('2000', '2012')) +} + + [email protected](params=_DATA_LOADER_KWARGS.values(), + ids=list(_DATA_LOADER_KWARGS.keys())) +def data_loader(request): + data_loader_type, kwargs = request.param + return data_loader_type(**kwargs) + + +_GFDL_DATA_LOADER_KWARGS = {key: _DATA_LOADER_KWARGS[key] for key in + _DATA_LOADER_KWARGS if 'GFDL' in key} + + [email protected](params=_GFDL_DATA_LOADER_KWARGS.values(), + ids=list(_GFDL_DATA_LOADER_KWARGS.keys())) +def gfdl_data_loader(request): + data_loader_type, kwargs = request.param + return data_loader_type(**kwargs) + + +def test_rename_grid_attrs_ds(ds, alt_lat_str): + assert LAT_STR not in ds + assert alt_lat_str in ds + ds = grid_attrs_to_aospy_names(ds) + assert LAT_STR in ds + + +def test_rename_grid_attrs_dim_no_coord(ds, var_name): + bounds_dim = 'nv' + assert bounds_dim not in ds + assert bounds_dim in GRID_ATTRS[BOUNDS_STR] + # Create DataArray with all dims lacking coords + values = ds[var_name].values + arr = xr.DataArray(values, name='dummy') + # Insert name to be replaced (its physical meaning doesn't matter here) + ds = arr.rename({'dim_0': bounds_dim}).to_dataset() + assert not ds[bounds_dim].coords + result = grid_attrs_to_aospy_names(ds) + assert not result[BOUNDS_STR].coords + + +def test_rename_grid_attrs_skip_scalar_dim(ds): + phalf_dim = 'phalf' + assert phalf_dim not in ds + assert phalf_dim in GRID_ATTRS[PHALF_STR] + ds_copy = ds.copy() + ds_copy[phalf_dim] = 4 + ds_copy = ds_copy.set_coords(phalf_dim) + result = grid_attrs_to_aospy_names(ds_copy) + xr.testing.assert_identical(result[phalf_dim], ds_copy[phalf_dim]) + + +def test_rename_grid_attrs_copy_attrs(ds, alt_lat_str): + orig_attrs = {'dummy_key': 'dummy_val'} + ds_orig = ds.copy() + ds_orig[alt_lat_str].attrs = orig_attrs + ds = grid_attrs_to_aospy_names(ds_orig) + assert ds[LAT_STR].attrs == orig_attrs + + +def test_set_grid_attrs_as_coords(ds, var_name): + ds = grid_attrs_to_aospy_names(ds) + sfc_area = ds[var_name].isel(**{TIME_STR: 0}).drop(TIME_STR) + ds[SFC_AREA_STR] = sfc_area + + assert SFC_AREA_STR not in ds.coords + + ds = set_grid_attrs_as_coords(ds) + assert SFC_AREA_STR in ds.coords + assert TIME_BOUNDS_STR in ds.coords + + +def test_sel_var(): + time = np.array([0, 31, 59]) + 15 + data = np.zeros((3)) + ds = xr.DataArray(data, + coords=[time], + dims=[TIME_STR], + name=convection_rain.name).to_dataset() + condensation_rain_alt_name, = condensation_rain.alt_names + ds[condensation_rain_alt_name] = xr.DataArray(data, coords=[ds.time]) + result = _sel_var(ds, convection_rain) + assert result.name == convection_rain.name + + result = _sel_var(ds, condensation_rain) + assert result.name == condensation_rain.name + + with pytest.raises(LookupError): + _sel_var(ds, precip) + + +def test_maybe_apply_time_shift(data_loader, ds, inst_ds, var_name, + generate_file_set_args): + ds = xr.decode_cf(ds) + da = ds[var_name] + + result = data_loader._maybe_apply_time_shift( + da.copy(), **generate_file_set_args)[TIME_STR] + assert result.identical(da[TIME_STR]) + + offset = data_loader._maybe_apply_time_shift( + da.copy(), {'days': 1}, **generate_file_set_args) + result = offset[TIME_STR] + + expected = da[TIME_STR] + np.timedelta64(1, 'D') + expected[TIME_STR] = expected + + assert result.identical(expected) + + +def test_maybe_apply_time_shift_ts(gfdl_data_loader, ds, var_name, + generate_file_set_args): + ds = xr.decode_cf(ds) + da = ds[var_name] + result = gfdl_data_loader._maybe_apply_time_shift( + da.copy(), **generate_file_set_args)[TIME_STR] + assert result.identical(da[TIME_STR]) + + +def test_maybe_apply_time_shift_inst(gfdl_data_loader, inst_ds, var_name, + generate_file_set_args): + inst_ds = xr.decode_cf(inst_ds) + generate_file_set_args['dtype_in_time'] = 'inst' + generate_file_set_args['intvl_in'] = '3hr' + da = inst_ds[var_name] + result = gfdl_data_loader._maybe_apply_time_shift( + da.copy(), **generate_file_set_args)[TIME_STR] + + expected = da[TIME_STR] + np.timedelta64(-3, 'h') + expected[TIME_STR] = expected + assert result.identical(expected) + + generate_file_set_args['intvl_in'] = 'daily' + da = inst_ds[var_name] + result = gfdl_data_loader._maybe_apply_time_shift( + da.copy(), **generate_file_set_args)[TIME_STR] + + expected = da[TIME_STR] + expected[TIME_STR] = expected + assert result.identical(expected) + + +def test_prep_time_data(inst_ds): + assert (TIME_WEIGHTS_STR not in inst_ds) + ds = _prep_time_data(inst_ds) + assert (TIME_WEIGHTS_STR in ds) - with self.assertRaises(KeyError): - self.generate_file_set_args['intvl_in'] = 'daily' - result = self.DataLoader._generate_file_set( - **self.generate_file_set_args) +def test_preprocess_and_rename_grid_attrs(ds, alt_lat_str): + def preprocess_func(ds, **kwargs): + # Corrupt a grid attribute name so that we test + # that grid_attrs_to_aospy_names is still called + # after + ds = ds.rename({LON_STR: 'LONGITUDE'}) + ds.attrs['a'] = 'b' + return ds + + assert LAT_STR not in ds + assert alt_lat_str in ds + assert LON_STR in ds + + expected = ds.rename({alt_lat_str: LAT_STR}) + expected = expected.set_coords(TIME_BOUNDS_STR) + expected.attrs['a'] = 'b' + result = _preprocess_and_rename_grid_attrs(preprocess_func)(ds) + xr.testing.assert_identical(result, expected) + + +def test_generate_file_set(data_loader, generate_file_set_args): + if type(data_loader) is DataLoader: + with pytest.raises(NotImplementedError): + data_loader._generate_file_set() + + elif isinstance(data_loader, DictDataLoader): + result = data_loader._generate_file_set( + **generate_file_set_args) + expected = ['a.nc'] + result == expected -class TestNestedDictDataLoader(TestDataLoader): - def setUp(self): - super(TestNestedDictDataLoader, self).setUp() - file_map = {'monthly': {'condensation_rain': ['a.nc']}} - self.DataLoader = NestedDictDataLoader(file_map) + with pytest.raises(KeyError): + generate_file_set_args['intvl_in'] = 'daily' + result = data_loader._generate_file_set( + **generate_file_set_args) - def test_generate_file_set(self): - result = self.DataLoader._generate_file_set( - **self.generate_file_set_args) + elif isinstance(data_loader, NestedDictDataLoader): + result = data_loader._generate_file_set( + **generate_file_set_args) expected = ['a.nc'] - self.assertEqual(result, expected) - - with self.assertRaises(KeyError): - self.generate_file_set_args['var'] = convection_rain - result = self.DataLoader._generate_file_set( - **self.generate_file_set_args) - - -class TestGFDLDataLoader(TestDataLoader): - def setUp(self): - super(TestGFDLDataLoader, self).setUp() - self.DataLoader = GFDLDataLoader( - data_direc=os.path.join('.', 'test'), - data_dur=6, - data_start_date=datetime(2000, 1, 1), - data_end_date=datetime(2012, 12, 31), - upcast_float32=False, - data_vars='minimal', - coords='minimal' - ) - - def test_overriding_constructor(self): - new = GFDLDataLoader(self.DataLoader, - data_direc=os.path.join('.', 'a')) - self.assertEqual(new.data_direc, os.path.join('.', 'a')) - self.assertEqual(new.data_dur, self.DataLoader.data_dur) - self.assertEqual(new.data_start_date, self.DataLoader.data_start_date) - self.assertEqual(new.data_end_date, self.DataLoader.data_end_date) - self.assertEqual(new.preprocess_func, - self.DataLoader.preprocess_func) - self.assertEqual(new.upcast_float32, self.DataLoader.upcast_float32) - - new = GFDLDataLoader(self.DataLoader, data_dur=8) - self.assertEqual(new.data_dur, 8) - - new = GFDLDataLoader(self.DataLoader, - data_start_date=datetime(2001, 1, 1)) - self.assertEqual(new.data_start_date, datetime(2001, 1, 1)) - - new = GFDLDataLoader(self.DataLoader, - data_end_date=datetime(2003, 12, 31)) - self.assertEqual(new.data_end_date, datetime(2003, 12, 31)) - - new = GFDLDataLoader(self.DataLoader, - preprocess_func=lambda ds: ds) - xr.testing.assert_identical(new.preprocess_func(self.ds), self.ds) - - new = GFDLDataLoader(self.DataLoader, upcast_float32=True) - self.assertEqual(new.upcast_float32, True) - - new = GFDLDataLoader(self.DataLoader, data_vars='all') - self.assertEqual(new.data_vars, 'all') - - new = GFDLDataLoader(self.DataLoader, coords='all') - self.assertEqual(new.coords, 'all') - - def test_maybe_apply_time_offset_inst(self): - inst_ds = xr.decode_cf(self.inst_ds) - self.generate_file_set_args['dtype_in_time'] = 'inst' - self.generate_file_set_args['intvl_in'] = '3hr' - da = inst_ds[self.var_name] - result = self.DataLoader._maybe_apply_time_shift( - da.copy(), **self.generate_file_set_args)[TIME_STR] - - expected = da[TIME_STR] + np.timedelta64(-3, 'h') - expected[TIME_STR] = expected - assert result.identical(expected) - - self.generate_file_set_args['intvl_in'] = 'daily' - da = inst_ds[self.var_name] - result = self.DataLoader._maybe_apply_time_shift( - da.copy(), **self.generate_file_set_args)[TIME_STR] - - expected = da[TIME_STR] - expected[TIME_STR] = expected - assert result.identical(expected) - - def test_maybe_apply_time_offset_ts(self): - ds = xr.decode_cf(self.ds) - da = ds[self.var_name] - - result = self.DataLoader._maybe_apply_time_shift( - da.copy(), **self.generate_file_set_args)[TIME_STR] - assert result.identical(da[TIME_STR]) - - def test_generate_file_set(self): - with self.assertRaises(IOError): - self.DataLoader._generate_file_set(**self.generate_file_set_args) - - def test_input_data_paths_gfdl(self): - expected = [os.path.join('.', 'test', 'atmos', 'ts', 'monthly', '6yr', - 'atmos.200601-201112.temp.nc')] - result = self.DataLoader._input_data_paths_gfdl( - 'temp', datetime(2010, 1, 1), datetime(2010, 12, 31), 'atmos', - 'monthly', 'pressure', 'ts', None) - self.assertEqual(result, expected) - - expected = [os.path.join('.', 'test', 'atmos_daily', 'ts', 'daily', - '6yr', - 'atmos_daily.20060101-20111231.temp.nc')] - result = self.DataLoader._input_data_paths_gfdl( - 'temp', datetime(2010, 1, 1), datetime(2010, 12, 31), 'atmos', - 'daily', 'pressure', 'ts', None) - self.assertEqual(result, expected) - - expected = [os.path.join('.', 'test', 'atmos_level', 'ts', 'monthly', - '6yr', 'atmos_level.200601-201112.temp.nc')] - result = self.DataLoader._input_data_paths_gfdl( - 'temp', datetime(2010, 1, 1), datetime(2010, 12, 31), 'atmos', - 'monthly', ETA_STR, 'ts', None) - self.assertEqual(result, expected) - - expected = [os.path.join('.', 'test', 'atmos', 'ts', 'monthly', - '6yr', 'atmos.200601-201112.ps.nc')] - result = self.DataLoader._input_data_paths_gfdl( - 'ps', datetime(2010, 1, 1), datetime(2010, 12, 31), 'atmos', - 'monthly', ETA_STR, 'ts', None) - self.assertEqual(result, expected) - - expected = [os.path.join('.', 'test', 'atmos_inst', 'ts', 'monthly', - '6yr', 'atmos_inst.200601-201112.temp.nc')] - result = self.DataLoader._input_data_paths_gfdl( - 'temp', datetime(2010, 1, 1), datetime(2010, 12, 31), 'atmos', - 'monthly', 'pressure', 'inst', None) - self.assertEqual(result, expected) - - expected = [os.path.join('.', 'test', 'atmos', 'av', 'monthly_6yr', - 'atmos.2006-2011.jja.nc')] - result = self.DataLoader._input_data_paths_gfdl( - 'temp', datetime(2010, 1, 1), datetime(2010, 12, 31), 'atmos', - 'monthly', 'pressure', 'av', 'jja') - self.assertEqual(result, expected) - - def test_data_name_gfdl_annual(self): - for data_type in ['ts', 'inst']: - expected = 'atmos.2010.temp.nc' - result = io.data_name_gfdl('temp', 'atmos', data_type, - 'annual', 2010, None, 2000, 1) - self.assertEqual(result, expected) - - expected = 'atmos.2006-2011.temp.nc' - result = io.data_name_gfdl('temp', 'atmos', data_type, - 'annual', 2010, None, 2000, 6) - self.assertEqual(result, expected) - - for intvl_type in ['annual', 'ann']: - expected = 'atmos.2010.ann.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av', - intvl_type, 2010, None, 2000, 1) - self.assertEqual(result, expected) - - expected = 'atmos.2006-2011.ann.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av', - intvl_type, 2010, None, 2000, 6) - self.assertEqual(result, expected) - - expected = 'atmos.2006-2011.01-12.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av_ts', + assert result == expected + + with pytest.raises(KeyError): + generate_file_set_args['var'] = convection_rain + result = data_loader._generate_file_set( + **generate_file_set_args) + + else: + with pytest.raises(IOError): + data_loader._generate_file_set(**generate_file_set_args) + + +def test_overriding_constructor(gfdl_data_loader, ds): + new = GFDLDataLoader(gfdl_data_loader, + data_direc=os.path.join('.', 'a')) + assert new.data_direc == os.path.join('.', 'a') + assert new.data_dur == gfdl_data_loader.data_dur + assert new.data_start_date == gfdl_data_loader.data_start_date + assert new.data_end_date == gfdl_data_loader.data_end_date + assert new.preprocess_func == gfdl_data_loader.preprocess_func + assert new.upcast_float32 == gfdl_data_loader.upcast_float32 + + new = GFDLDataLoader(gfdl_data_loader, data_dur=8) + assert new.data_dur == 8 + + new = GFDLDataLoader(gfdl_data_loader, + data_start_date=datetime.datetime(2001, 1, 1)) + assert new.data_start_date == datetime.datetime(2001, 1, 1) + + new = GFDLDataLoader(gfdl_data_loader, + data_end_date=datetime.datetime(2003, 12, 31)) + assert new.data_end_date == datetime.datetime(2003, 12, 31) + + new = GFDLDataLoader(gfdl_data_loader, preprocess_func=lambda ds: ds) + xr.testing.assert_identical(new.preprocess_func(ds), ds) + + new = GFDLDataLoader(gfdl_data_loader, upcast_float32=True) + assert new.upcast_float32 + + new = GFDLDataLoader(gfdl_data_loader, data_vars='all') + assert new.data_vars == 'all' + + new = GFDLDataLoader(gfdl_data_loader, coords='all') + assert new.coords == 'all' + + +_GFDL_DATE_RANGES = { + 'datetime': (datetime.datetime(2010, 1, 1), + datetime.datetime(2010, 12, 31)), + 'datetime64': (np.datetime64('2010-01-01'), + np.datetime64('2010-12-31')), + 'cftime': (DatetimeNoLeap(2010, 1, 1), + DatetimeNoLeap(2010, 12, 31)), + 'str': ('2010', '2010') +} + + [email protected](['start_date', 'end_date'], + _GFDL_DATE_RANGES.values(), + ids=list(_GFDL_DATE_RANGES.keys())) +def test_input_data_paths_gfdl(gfdl_data_loader, start_date, end_date): + expected = [os.path.join('.', 'test', 'atmos', 'ts', 'monthly', '6yr', + 'atmos.200601-201112.temp.nc')] + result = gfdl_data_loader._input_data_paths_gfdl( + 'temp', start_date, end_date, 'atmos', + 'monthly', 'pressure', 'ts', None) + assert result == expected + + expected = [os.path.join('.', 'test', 'atmos_daily', 'ts', 'daily', + '6yr', + 'atmos_daily.20060101-20111231.temp.nc')] + result = gfdl_data_loader._input_data_paths_gfdl( + 'temp', start_date, end_date, 'atmos', + 'daily', 'pressure', 'ts', None) + assert result == expected + + expected = [os.path.join('.', 'test', 'atmos_daily', 'ts', 'daily', + '6yr', + 'atmos_daily.20060101-20111231.temp.nc')] + result = gfdl_data_loader._input_data_paths_gfdl( + 'temp', start_date, end_date, 'atmos', + 'daily', 'pressure', 'ts', None) + assert result == expected + + expected = [os.path.join('.', 'test', 'atmos_level', 'ts', 'monthly', + '6yr', 'atmos_level.200601-201112.temp.nc')] + result = gfdl_data_loader._input_data_paths_gfdl( + 'temp', start_date, end_date, 'atmos', + 'monthly', ETA_STR, 'ts', None) + assert result == expected + + expected = [os.path.join('.', 'test', 'atmos', 'ts', 'monthly', + '6yr', 'atmos.200601-201112.ps.nc')] + result = gfdl_data_loader._input_data_paths_gfdl( + 'ps', start_date, end_date, 'atmos', + 'monthly', ETA_STR, 'ts', None) + assert result == expected + + expected = [os.path.join('.', 'test', 'atmos_inst', 'ts', 'monthly', + '6yr', 'atmos_inst.200601-201112.temp.nc')] + result = gfdl_data_loader._input_data_paths_gfdl( + 'temp', start_date, end_date, 'atmos', + 'monthly', 'pressure', 'inst', None) + assert result == expected + + expected = [os.path.join('.', 'test', 'atmos', 'av', 'monthly_6yr', + 'atmos.2006-2011.jja.nc')] + result = gfdl_data_loader._input_data_paths_gfdl( + 'temp', start_date, end_date, 'atmos', + 'monthly', 'pressure', 'av', 'jja') + assert result == expected + + +# TODO: Parametrize these tests +def test_data_name_gfdl_annual(): + for data_type in ['ts', 'inst']: + expected = 'atmos.2010.temp.nc' + result = io.data_name_gfdl('temp', 'atmos', data_type, + 'annual', 2010, None, 2000, 1) + assert result == expected + + expected = 'atmos.2006-2011.temp.nc' + result = io.data_name_gfdl('temp', 'atmos', data_type, 'annual', 2010, None, 2000, 6) - self.assertEqual(result, expected) - - def test_data_name_gfdl_monthly(self): - for data_type in ['ts', 'inst']: - expected = 'atmos.200601-201112.temp.nc' - result = io.data_name_gfdl('temp', 'atmos', data_type, - 'monthly', 2010, 'jja', 2000, 6) - self.assertEqual(result, expected) - - for intvl_type in ['monthly', 'mon']: - expected = 'atmos.2010.jja.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av', - intvl_type, 2010, 'jja', 2000, 1) - self.assertEqual(result, expected) - - expected = 'atmos.2006-2011.jja.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av', - intvl_type, 2010, 'jja', 2000, 6) - self.assertEqual(result, expected) - - expected = 'atmos.2006-2011.01-12.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av_ts', - 'monthly', 2010, 'jja', 2000, 6) - self.assertEqual(result, expected) + assert result == expected - def test_data_name_gfdl_daily(self): - for data_type in ['ts', 'inst']: - expected = 'atmos.20060101-20111231.temp.nc' - result = io.data_name_gfdl('temp', 'atmos', data_type, - 'daily', 2010, None, 2000, 6) - self.assertEqual(result, expected) + for intvl_type in ['annual', 'ann']: + expected = 'atmos.2010.ann.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av', + intvl_type, 2010, None, 2000, 1) + assert result == expected - with self.assertRaises(NameError): - io.data_name_gfdl('temp', 'atmos', 'av', - 'daily', 2010, None, 2000, 6) + expected = 'atmos.2006-2011.ann.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av', + intvl_type, 2010, None, 2000, 6) + assert result == expected - expected = 'atmos.2006-2011.01-12.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av_ts', - 'daily', 2010, None, 2000, 6) - self.assertEqual(result, expected) + expected = 'atmos.2006-2011.01-12.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av_ts', + 'annual', 2010, None, 2000, 6) + assert result == expected - def test_data_name_gfdl_hr(self): - for data_type in ['ts', 'inst']: - expected = 'atmos.2006010100-2011123123.temp.nc' - result = io.data_name_gfdl('temp', 'atmos', data_type, - '3hr', 2010, None, 2000, 6) - self.assertEqual(result, expected) - with self.assertRaises(NameError): - io.data_name_gfdl('temp', 'atmos', 'av', - '3hr', 2010, None, 2000, 6) +def test_data_name_gfdl_monthly(): + for data_type in ['ts', 'inst']: + expected = 'atmos.200601-201112.temp.nc' + result = io.data_name_gfdl('temp', 'atmos', data_type, + 'monthly', 2010, 'jja', 2000, 6) + assert result == expected - expected = 'atmos.2006-2011.01-12.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av_ts', - '3hr', 2010, None, 2000, 6) - self.assertEqual(result, expected) - - def test_data_name_gfdl_seasonal(self): - for data_type in ['ts', 'inst']: - with self.assertRaises(NameError): - io.data_name_gfdl('temp', 'atmos', data_type, - 'seasonal', 2010, None, 2000, 6) - - for intvl_type in ['seasonal', 'seas']: - expected = 'atmos.2010.JJA.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av', - intvl_type, 2010, 'jja', 2000, 1) - self.assertEqual(result, expected) - - expected = 'atmos.2006-2011.JJA.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av', - intvl_type, 2010, 'jja', 2000, 6) - self.assertEqual(result, expected) - - expected = 'atmos.2006-2011.01-12.nc' - result = io.data_name_gfdl('temp', 'atmos', 'av_ts', - 'seasonal', 2010, None, 2000, 6) - self.assertEqual(result, expected) - - -class LoadVariableTestCase(unittest.TestCase): - def setUp(self): - self.data_loader = example_run.data_loader - - def tearDown(self): - # Restore default values of data_vars and coords - self.data_loader.data_vars = 'minimal' - self.data_loader.coords = 'minimal' - self.data_loader.preprocess_func = lambda ds, **kwargs: ds - - def test_load_variable(self): - result = self.data_loader.load_variable( - condensation_rain, datetime(5, 1, 1), datetime(5, 12, 31), - intvl_in='monthly') - filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', - '00050101.precip_monthly.nc') - expected = _open_ds_catch_warnings(filepath)['condensation_rain'] - np.testing.assert_array_equal(result.values, expected.values) - - def test_load_variable_does_not_warn(self): - with warnings.catch_warnings(record=True) as warnlog: - self.data_loader.load_variable(condensation_rain, - datetime(5, 1, 1), - datetime(5, 12, 31), - intvl_in='monthly') - assert len(warnlog) == 0 - - def test_load_variable_float32_to_float64(self): - def preprocess(ds, **kwargs): - # This function converts testing data to the float32 datatype - return ds.astype(np.float32) - self.data_loader.preprocess_func = preprocess - result = self.data_loader.load_variable( - condensation_rain, datetime(4, 1, 1), datetime(4, 12, 31), - intvl_in='monthly').dtype - expected = np.float64 - self.assertEqual(result, expected) - - def test_load_variable_maintain_float32(self): - def preprocess(ds, **kwargs): - # This function converts testing data to the float32 datatype - return ds.astype(np.float32) - self.data_loader.preprocess_func = preprocess - self.data_loader.upcast_float32 = False - result = self.data_loader.load_variable( - condensation_rain, datetime(4, 1, 1), datetime(4, 12, 31), - intvl_in='monthly').dtype - expected = np.float32 - self.assertEqual(result, expected) - - def test_load_variable_data_vars_all(self): - def preprocess(ds, **kwargs): - # This function drops the time coordinate from condensation_rain - temp = ds[condensation_rain.name] - temp = temp.isel(time=0, drop=True) - ds = ds.drop(condensation_rain.name) - ds[condensation_rain.name] = temp - assert TIME_STR not in ds[condensation_rain.name].coords - return ds - - self.data_loader.data_vars = 'all' - self.data_loader.preprocess_func = preprocess - data = self.data_loader.load_variable( - condensation_rain, datetime(4, 1, 1), datetime(5, 12, 31), - intvl_in='monthly') - result = TIME_STR in data.coords - self.assertEqual(result, True) + for intvl_type in ['monthly', 'mon']: + expected = 'atmos.2010.jja.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av', + intvl_type, 2010, 'jja', 2000, 1) + assert result == expected - def test_load_variable_data_vars_default(self): - data = self.data_loader.load_variable( - condensation_rain, datetime(4, 1, 1), datetime(5, 12, 31), - intvl_in='monthly') - result = TIME_STR in data.coords - self.assertEqual(result, True) + expected = 'atmos.2006-2011.jja.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av', + intvl_type, 2010, 'jja', 2000, 6) + assert result == expected - def test_load_variable_coords_all(self): - self.data_loader.coords = 'all' - data = self.data_loader.load_variable( - condensation_rain, datetime(4, 1, 1), datetime(5, 12, 31), - intvl_in='monthly') - result = TIME_STR in data[ZSURF_STR].coords - self.assertEqual(result, True) - - def test_load_variable_non_0001_refdate(self): - def preprocess(ds, **kwargs): - # This function converts our testing data (encoded with a units - # attribute with a reference data of 0001-01-01) to one - # with a reference data of 0004-01-01 (to do so we also need - # to offset the raw time values by three years). - three_yrs = 1095. - ds['time'] = ds['time'] - three_yrs - ds['time'].attrs['units'] = 'days since 0004-01-01 00:00:00' - ds['time_bounds'] = ds['time_bounds'] - three_yrs - ds['time_bounds'].attrs['units'] = 'days since 0004-01-01 00:00:00' - return ds - - self.data_loader.preprocess_func = preprocess - - for year in [4, 5, 6]: - result = self.data_loader.load_variable( - condensation_rain, datetime(year, 1, 1), - datetime(year, 12, 31), - intvl_in='monthly') - filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', - '000{}0101.precip_monthly.nc'.format(year)) - expected = _open_ds_catch_warnings(filepath)['condensation_rain'] - np.testing.assert_allclose(result.values, expected.values) - - def test_load_variable_preprocess(self): - def preprocess(ds, **kwargs): - if kwargs['start_date'] == datetime(5, 1, 1): - ds['condensation_rain'] = 10. * ds['condensation_rain'] - return ds - - self.data_loader.preprocess_func = preprocess - - result = self.data_loader.load_variable( - condensation_rain, datetime(5, 1, 1), datetime(5, 12, 31), - intvl_in='monthly') - filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', - '00050101.precip_monthly.nc') - expected = 10. * _open_ds_catch_warnings(filepath)['condensation_rain'] - np.testing.assert_allclose(result.values, expected.values) + expected = 'atmos.2006-2011.01-12.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av_ts', + 'monthly', 2010, 'jja', 2000, 6) + assert result == expected - result = self.data_loader.load_variable( - condensation_rain, datetime(4, 1, 1), datetime(4, 12, 31), - intvl_in='monthly') - filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', - '00040101.precip_monthly.nc') - expected = _open_ds_catch_warnings(filepath)['condensation_rain'] - np.testing.assert_allclose(result.values, expected.values) - - def test_load_variable_mask_and_scale(self): - def convert_all_to_missing_val(ds, **kwargs): - ds['condensation_rain'] = 0. * ds['condensation_rain'] + 1.0e20 - ds['condensation_rain'].attrs['_FillValue'] = 1.0e20 - return ds - - self.data_loader.preprocess_func = convert_all_to_missing_val - - data = self.data_loader.load_variable( - condensation_rain, datetime(5, 1, 1), - datetime(5, 12, 31), - intvl_in='monthly') - num_non_missing = np.isfinite(data).sum().item() - expected_num_non_missing = 0 - self.assertEqual(num_non_missing, expected_num_non_missing) +def test_data_name_gfdl_daily(): + for data_type in ['ts', 'inst']: + expected = 'atmos.20060101-20111231.temp.nc' + result = io.data_name_gfdl('temp', 'atmos', data_type, + 'daily', 2010, None, 2000, 6) + assert result == expected + + with pytest.raises(NameError): + io.data_name_gfdl('temp', 'atmos', 'av', + 'daily', 2010, None, 2000, 6) - def test_recursively_compute_variable_native(self): - result = self.data_loader.recursively_compute_variable( - condensation_rain, datetime(5, 1, 1), datetime(5, 12, 31), - intvl_in='monthly') - filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', - '00050101.precip_monthly.nc') - expected = _open_ds_catch_warnings(filepath)['condensation_rain'] - np.testing.assert_array_equal(result.values, expected.values) - - def test_recursively_compute_variable_one_level(self): - one_level = Var( - name='one_level', variables=(condensation_rain, condensation_rain), - func=lambda x, y: x + y) - result = self.data_loader.recursively_compute_variable( - one_level, datetime(5, 1, 1), datetime(5, 12, 31), - intvl_in='monthly') - filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', - '00050101.precip_monthly.nc') - expected = 2. * _open_ds_catch_warnings(filepath)['condensation_rain'] - np.testing.assert_array_equal(result.values, expected.values) - - def test_recursively_compute_variable_multi_level(self): - one_level = Var( - name='one_level', variables=(condensation_rain, condensation_rain), - func=lambda x, y: x + y) - multi_level = Var( - name='multi_level', variables=(one_level, condensation_rain), - func=lambda x, y: x + y) - result = self.data_loader.recursively_compute_variable( - multi_level, datetime(5, 1, 1), datetime(5, 12, 31), + expected = 'atmos.2006-2011.01-12.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av_ts', + 'daily', 2010, None, 2000, 6) + assert result == expected + + +def test_data_name_gfdl_hr(): + for data_type in ['ts', 'inst']: + expected = 'atmos.2006010100-2011123123.temp.nc' + result = io.data_name_gfdl('temp', 'atmos', data_type, + '3hr', 2010, None, 2000, 6) + assert result == expected + + with pytest.raises(NameError): + io.data_name_gfdl('temp', 'atmos', 'av', + '3hr', 2010, None, 2000, 6) + + expected = 'atmos.2006-2011.01-12.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av_ts', + '3hr', 2010, None, 2000, 6) + assert result == expected + + +def test_data_name_gfdl_seasonal(): + for data_type in ['ts', 'inst']: + with pytest.raises(NameError): + io.data_name_gfdl('temp', 'atmos', data_type, + 'seasonal', 2010, None, 2000, 6) + + for intvl_type in ['seasonal', 'seas']: + expected = 'atmos.2010.JJA.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av', + intvl_type, 2010, 'jja', 2000, 1) + assert result == expected + + expected = 'atmos.2006-2011.JJA.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av', + intvl_type, 2010, 'jja', 2000, 6) + assert result == expected + + expected = 'atmos.2006-2011.01-12.nc' + result = io.data_name_gfdl('temp', 'atmos', 'av_ts', + 'seasonal', 2010, None, 2000, 6) + assert result == expected + + [email protected]() +def load_variable_data_loader(): + return NestedDictDataLoader(file_map, upcast_float32=False) + + +_LOAD_VAR_DATE_RANGES = { + 'datetime': (datetime.datetime(5, 1, 1), + datetime.datetime(5, 12, 31)), + 'datetime64': (np.datetime64('0005-01-01'), + np.datetime64('0005-12-31')), + 'cftime': (DatetimeNoLeap(5, 1, 1), DatetimeNoLeap(5, 12, 31)), + 'str': ('0005', '0005') +} + + [email protected](['start_date', 'end_date'], + _LOAD_VAR_DATE_RANGES.values(), + ids=list(_LOAD_VAR_DATE_RANGES.keys())) +def test_load_variable(load_variable_data_loader, start_date, end_date): + result = load_variable_data_loader.load_variable( + condensation_rain, start_date, end_date, intvl_in='monthly') + filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', + '00050101.precip_monthly.nc') + expected = _open_ds_catch_warnings(filepath)['condensation_rain'] + np.testing.assert_array_equal(result.values, expected.values) + + [email protected](['start_date', 'end_date'], + _LOAD_VAR_DATE_RANGES.values(), + ids=list(_LOAD_VAR_DATE_RANGES.keys())) +def test_load_variable_does_not_warn(load_variable_data_loader, + start_date, end_date): + with warnings.catch_warnings(record=True) as warnlog: + load_variable_data_loader.load_variable( + condensation_rain, + start_date, end_date, intvl_in='monthly') - filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', - '00050101.precip_monthly.nc') - expected = 3. * _open_ds_catch_warnings(filepath)['condensation_rain'] - np.testing.assert_array_equal(result.values, expected.values) + assert len(warnlog) == 0 + + [email protected](['start_date', 'end_date'], + _LOAD_VAR_DATE_RANGES.values(), + ids=list(_LOAD_VAR_DATE_RANGES.keys())) +def test_load_variable_float32_to_float64(load_variable_data_loader, + start_date, end_date): + def preprocess(ds, **kwargs): + # This function converts testing data to the float32 datatype + return ds.astype(np.float32) + load_variable_data_loader.upcast_float32 = True + load_variable_data_loader.preprocess_func = preprocess + result = load_variable_data_loader.load_variable( + condensation_rain, start_date, + end_date, + intvl_in='monthly').dtype + expected = np.float64 + assert result == expected + + [email protected](['start_date', 'end_date'], + _LOAD_VAR_DATE_RANGES.values(), + ids=list(_LOAD_VAR_DATE_RANGES.keys())) +def test_load_variable_maintain_float32(load_variable_data_loader, + start_date, end_date): + def preprocess(ds, **kwargs): + # This function converts testing data to the float32 datatype + return ds.astype(np.float32) + load_variable_data_loader.preprocess_func = preprocess + load_variable_data_loader.upcast_float32 = False + result = load_variable_data_loader.load_variable( + condensation_rain, start_date, + end_date, + intvl_in='monthly').dtype + expected = np.float32 + assert result == expected + + +_LOAD_VAR_MULTI_YEAR_RANGES = { + 'datetime': (datetime.datetime(4, 1, 1), + datetime.datetime(5, 12, 31)), + 'datetime64': (np.datetime64('0004-01-01'), + np.datetime64('0005-12-31')), + 'cftime': (DatetimeNoLeap(4, 1, 1), DatetimeNoLeap(5, 12, 31)), + 'str': ('0004', '0005') +} + + [email protected](['start_date', 'end_date'], + _LOAD_VAR_MULTI_YEAR_RANGES.values(), + ids=list(_LOAD_VAR_MULTI_YEAR_RANGES.keys())) +def test_load_variable_data_vars_all(load_variable_data_loader, + start_date, end_date): + def preprocess(ds, **kwargs): + # This function drops the time coordinate from condensation_rain + temp = ds[condensation_rain.name] + temp = temp.isel(time=0, drop=True) + ds = ds.drop(condensation_rain.name) + ds[condensation_rain.name] = temp + assert TIME_STR not in ds[condensation_rain.name].coords + return ds + + load_variable_data_loader.data_vars = 'all' + load_variable_data_loader.preprocess_func = preprocess + data = load_variable_data_loader.load_variable( + condensation_rain, start_date, end_date, + intvl_in='monthly') + assert TIME_STR in data.coords + + [email protected](['start_date', 'end_date'], + _LOAD_VAR_MULTI_YEAR_RANGES.values(), + ids=list(_LOAD_VAR_MULTI_YEAR_RANGES.keys())) +def test_load_variable_data_vars_default(load_variable_data_loader, start_date, + end_date): + data = load_variable_data_loader.load_variable( + condensation_rain, start_date, end_date, + intvl_in='monthly') + assert TIME_STR in data.coords + + [email protected](['start_date', 'end_date'], + _LOAD_VAR_MULTI_YEAR_RANGES.values(), + ids=list(_LOAD_VAR_MULTI_YEAR_RANGES.keys())) +def test_load_variable_coords_all(load_variable_data_loader, start_date, + end_date): + load_variable_data_loader.coords = 'all' + data = load_variable_data_loader.load_variable( + condensation_rain, start_date, end_date, + intvl_in='monthly') + assert TIME_STR in data[ZSURF_STR].coords + + [email protected]('year', [4, 5, 6]) +def test_load_variable_non_0001_refdate(load_variable_data_loader, year): + def preprocess(ds, **kwargs): + # This function converts our testing data (encoded with a units + # attribute with a reference data of 0001-01-01) to one + # with a reference data of 0004-01-01 (to do so we also need + # to offset the raw time values by three years). + three_yrs = 1095. + ds['time'] = ds['time'] - three_yrs + ds['time'].attrs['units'] = 'days since 0004-01-01 00:00:00' + ds['time'].attrs['calendar'] = 'noleap' + ds['time_bounds'] = ds['time_bounds'] - three_yrs + ds['time_bounds'].attrs['units'] = 'days since 0004-01-01 00:00:00' + ds['time_bounds'].attrs['calendar'] = 'noleap' + return ds + + load_variable_data_loader.preprocess_func = preprocess + + result = load_variable_data_loader.load_variable( + condensation_rain, DatetimeNoLeap(year, 1, 1), + DatetimeNoLeap(year, 12, 31), + intvl_in='monthly') + filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', + '000{}0101.precip_monthly.nc'.format(year)) + expected = _open_ds_catch_warnings(filepath)['condensation_rain'] + np.testing.assert_allclose(result.values, expected.values) + + +def test_load_variable_preprocess(load_variable_data_loader): + def preprocess(ds, **kwargs): + if kwargs['start_date'] == DatetimeNoLeap(5, 1, 1): + ds['condensation_rain'] = 10. * ds['condensation_rain'] + return ds + + load_variable_data_loader.preprocess_func = preprocess + + result = load_variable_data_loader.load_variable( + condensation_rain, DatetimeNoLeap(5, 1, 1), + DatetimeNoLeap(5, 12, 31), + intvl_in='monthly') + filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', + '00050101.precip_monthly.nc') + expected = 10. * _open_ds_catch_warnings(filepath)['condensation_rain'] + np.testing.assert_allclose(result.values, expected.values) + + result = load_variable_data_loader.load_variable( + condensation_rain, DatetimeNoLeap(4, 1, 1), + DatetimeNoLeap(4, 12, 31), + intvl_in='monthly') + filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', + '00040101.precip_monthly.nc') + expected = _open_ds_catch_warnings(filepath)['condensation_rain'] + np.testing.assert_allclose(result.values, expected.values) + + +def test_load_variable_mask_and_scale(load_variable_data_loader): + def convert_all_to_missing_val(ds, **kwargs): + ds['condensation_rain'] = 0. * ds['condensation_rain'] + 1.0e20 + ds['condensation_rain'].attrs['_FillValue'] = 1.0e20 + return ds + + load_variable_data_loader.preprocess_func = convert_all_to_missing_val + + data = load_variable_data_loader.load_variable( + condensation_rain, DatetimeNoLeap(5, 1, 1), + DatetimeNoLeap(5, 12, 31), + intvl_in='monthly') + + num_non_missing = np.isfinite(data).sum().item() + expected_num_non_missing = 0 + assert num_non_missing == expected_num_non_missing + + +def test_recursively_compute_variable_native(load_variable_data_loader): + result = load_variable_data_loader.recursively_compute_variable( + condensation_rain, DatetimeNoLeap(5, 1, 1), + DatetimeNoLeap(5, 12, 31), + intvl_in='monthly') + filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', + '00050101.precip_monthly.nc') + expected = _open_ds_catch_warnings(filepath)['condensation_rain'] + np.testing.assert_array_equal(result.values, expected.values) + + +def test_recursively_compute_variable_one_level(load_variable_data_loader): + one_level = Var( + name='one_level', variables=(condensation_rain, condensation_rain), + func=lambda x, y: x + y) + result = load_variable_data_loader.recursively_compute_variable( + one_level, DatetimeNoLeap(5, 1, 1), DatetimeNoLeap(5, 12, 31), + intvl_in='monthly') + filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', + '00050101.precip_monthly.nc') + expected = 2. * _open_ds_catch_warnings(filepath)['condensation_rain'] + np.testing.assert_array_equal(result.values, expected.values) + + +def test_recursively_compute_variable_multi_level(load_variable_data_loader): + one_level = Var( + name='one_level', variables=(condensation_rain, condensation_rain), + func=lambda x, y: x + y) + multi_level = Var( + name='multi_level', variables=(one_level, condensation_rain), + func=lambda x, y: x + y) + result = load_variable_data_loader.recursively_compute_variable( + multi_level, DatetimeNoLeap(5, 1, 1), DatetimeNoLeap(5, 12, 31), + intvl_in='monthly') + filepath = os.path.join(os.path.split(ROOT_PATH)[0], 'netcdf', + '00050101.precip_monthly.nc') + expected = 3. * _open_ds_catch_warnings(filepath)['condensation_rain'] + np.testing.assert_array_equal(result.values, expected.values) if __name__ == '__main__': diff --git a/aospy/test/test_run.py b/aospy/test/test_run.py index 96fa9be..aec1d17 100644 --- a/aospy/test/test_run.py +++ b/aospy/test/test_run.py @@ -1,9 +1,11 @@ #!/usr/bin/env python """Test suite for aospy.run module.""" -import datetime import sys import unittest +import cftime +import numpy as np + from aospy.run import Run from aospy.data_loader import DictDataLoader, GFDLDataLoader @@ -19,22 +21,24 @@ class RunTestCase(unittest.TestCase): class TestRun(RunTestCase): def test_init_dates_valid_input(self): for attr in ['default_start_date', 'default_end_date']: - for date in [None, datetime.datetime(1, 1, 1)]: + for date in [None, np.datetime64('2000-01-01')]: run_ = Run(**{attr: date}) self.assertEqual(date, getattr(run_, attr)) def test_init_dates_invalid_input(self): for attr in ['default_start_date', 'default_end_date']: - for date in [1985, False, '1750-12-10']: + for date in [1985, False]: with self.assertRaises(TypeError): Run(**{attr: date}) def test_init_default_dates(self): - gdl = GFDLDataLoader(data_start_date=datetime.datetime(1, 1, 1), - data_end_date=datetime.datetime(1, 12, 31)) + gdl = GFDLDataLoader(data_start_date=cftime.DatetimeNoLeap(1, 1, 1), + data_end_date=cftime.DatetimeNoLeap(1, 12, 31)) run_ = Run(data_loader=gdl) - self.assertEqual(run_.default_start_date, datetime.datetime(1, 1, 1)) - self.assertEqual(run_.default_end_date, datetime.datetime(1, 12, 31)) + self.assertEqual(run_.default_start_date, + cftime.DatetimeNoLeap(1, 1, 1)) + self.assertEqual(run_.default_end_date, + cftime.DatetimeNoLeap(1, 12, 31)) ddl = DictDataLoader({'monthly': '/a/'}) run_ = Run(data_loader=ddl) diff --git a/aospy/test/test_utils_times.py b/aospy/test/test_utils_times.py index 00b4216..f42d8b4 100755 --- a/aospy/test/test_utils_times.py +++ b/aospy/test/test_utils_times.py @@ -1,19 +1,22 @@ #!/usr/bin/env python """Test suite for aospy.timedate module.""" import datetime -import warnings +import cftime import numpy as np import pandas as pd import pytest import xarray as xr +from itertools import product + from aospy.data_loader import set_grid_attrs_as_coords from aospy.internal_names import ( TIME_STR, TIME_BOUNDS_STR, BOUNDS_STR, TIME_WEIGHTS_STR, RAW_START_DATE_STR, RAW_END_DATE_STR, SUBSET_START_DATE_STR, SUBSET_END_DATE_STR ) +from aospy.automate import _merge_dicts from aospy.utils.times import ( apply_time_offset, average_time_bounds, @@ -21,8 +24,6 @@ from aospy.utils.times import ( monthly_mean_at_each_ind, ensure_datetime, datetime_or_default, - numpy_datetime_range_workaround, - numpy_datetime_workaround_encode_cf, month_indices, _month_conditional, extract_months, @@ -32,11 +33,13 @@ from aospy.utils.times import ( assert_matching_time_coord, ensure_time_as_index, sel_time, - yearly_average + yearly_average, + infer_year, + maybe_convert_to_index_date_type ) -_INVALID_DATE_OBJECTS = [1985, True, None, '2016-04-07', np.datetime64(1, 'Y')] +_INVALID_DATE_OBJECTS = [1985, True, None] def test_apply_time_offset(): @@ -110,10 +113,12 @@ def test_monthly_mean_at_each_ind(): assert actual.identical(desired) -def test_ensure_datetime_valid_input(): - for date in [datetime.datetime(1981, 7, 15), - datetime.datetime(1, 1, 1)]: - assert ensure_datetime(date) == date [email protected]('date', [np.datetime64('2000-01-01'), + cftime.DatetimeNoLeap(1, 1, 1), + datetime.datetime(1, 1, 1), + '2000-01-01']) +def test_ensure_datetime_valid_input(date): + assert ensure_datetime(date) == date def test_ensure_datetime_invalid_input(): @@ -123,119 +128,11 @@ def test_ensure_datetime_invalid_input(): def test_datetime_or_default(): - date = datetime.datetime(1, 2, 3) + date = np.datetime64('2000-01-01') assert datetime_or_default(None, 'dummy') == 'dummy' assert datetime_or_default(date, 'dummy') == ensure_datetime(date) -def test_numpy_datetime_range_workaround(): - assert (numpy_datetime_range_workaround( - datetime.datetime(pd.Timestamp.min.year + 1, 1, 1), - pd.Timestamp.min.year + 1, pd.Timestamp.min.year + 2) == - datetime.datetime(pd.Timestamp.min.year + 1, 1, 1)) - - assert ( - numpy_datetime_range_workaround(datetime.datetime(3, 1, 1), 1, 6) == - datetime.datetime(pd.Timestamp.min.year + 3, 1, 1) - ) - - assert ( - numpy_datetime_range_workaround(datetime.datetime(5, 1, 1), 4, 6) == - datetime.datetime(pd.Timestamp.min.year + 2, 1, 1) - ) - - # Test min_yr outside valid range - assert ( - numpy_datetime_range_workaround( - datetime.datetime(pd.Timestamp.min.year + 3, 1, 1), - pd.Timestamp.min.year, pd.Timestamp.min.year + 2) == - datetime.datetime(pd.Timestamp.min.year + 4, 1, 1) - ) - - # Test max_yr outside valid range - assert ( - numpy_datetime_range_workaround( - datetime.datetime(pd.Timestamp.max.year + 2, 1, 1), - pd.Timestamp.max.year - 1, pd.Timestamp.max.year) == - datetime.datetime(pd.Timestamp.min.year + 4, 1, 1)) - - -def _create_datetime_workaround_test_data(days, ref_units, expected_units): - # 1095 days corresponds to three years in a noleap calendar - # This allows us to generate ranges which straddle the - # Timestamp-valid range - three_yrs = 1095. - time = xr.DataArray([days, days + three_yrs], dims=[TIME_STR]) - ds = xr.Dataset(coords={TIME_STR: time}) - ds[TIME_STR].attrs['units'] = ref_units - ds[TIME_STR].attrs['calendar'] = 'noleap' - actual, min_yr, max_yr = numpy_datetime_workaround_encode_cf(ds) - - time_desired = xr.DataArray([days, days + three_yrs], - dims=[TIME_STR]) - desired = xr.Dataset(coords={TIME_STR: time_desired}) - desired[TIME_STR].attrs['units'] = expected_units - desired[TIME_STR].attrs['calendar'] = 'noleap' - return actual, min_yr, max_yr, desired - - -def _numpy_datetime_workaround_encode_cf_tests(days, ref_units, expected_units, - expected_time0, expected_min_yr, - expected_max_yr): - with warnings.catch_warnings(record=True) as warnlog: - actual, minyr, maxyr, desired = _create_datetime_workaround_test_data( - days, ref_units, expected_units) - assert len(warnlog) == 0 - xr.testing.assert_identical(actual, desired) - assert xr.decode_cf(actual).time.values[0] == expected_time0 - assert minyr == expected_min_yr - assert maxyr == expected_max_yr - - -def test_numpy_datetime_workaround_encode_cf(): - # 255169 days from 0001-01-01 corresponds to date 700-02-04. - _numpy_datetime_workaround_encode_cf_tests( - 255169., 'days since 0001-01-01 00:00:00', - 'days since 979-01-01 00:00:00', np.datetime64('1678-02-04'), - 700, 703) - - # Test a case where times are in the Timestamp-valid range - _numpy_datetime_workaround_encode_cf_tests( - 10., 'days since 2000-01-01 00:00:00', - 'days since 2000-01-01 00:00:00', np.datetime64('2000-01-11'), - 2000, 2003) - - # Regression tests for GH188 - _numpy_datetime_workaround_encode_cf_tests( - 732., 'days since 0700-01-01 00:00:00', - 'days since 1676-01-01 00:00:00', np.datetime64('1678-01-03'), - 702, 705) - - # Non-January 1st reference date - _numpy_datetime_workaround_encode_cf_tests( - 732., 'days since 0700-05-03 00:00:00', - 'days since 1676-05-03 00:00:00', np.datetime64('1678-05-05'), - 702, 705) - - # Above Timestamp.max - _numpy_datetime_workaround_encode_cf_tests( - 732., 'days since 2300-01-01 00:00:00', - 'days since 1676-01-01 00:00:00', np.datetime64('1678-01-03'), - 2302, 2305) - - # Straddle lower bound - _numpy_datetime_workaround_encode_cf_tests( - 2., 'days since 1677-01-01 00:00:00', - 'days since 1678-01-01 00:00:00', np.datetime64('1678-01-03'), - 1677, 1680) - - # Straddle upper bound - _numpy_datetime_workaround_encode_cf_tests( - 2., 'days since 2262-01-01 00:00:00', - 'days since 1678-01-01 00:00:00', np.datetime64('1678-01-03'), - 2262, 2265) - - def test_month_indices(): np.testing.assert_array_equal(month_indices('ann'), range(1, 13)) np.testing.assert_array_equal(month_indices('jja'), @@ -421,6 +318,94 @@ def test_assert_has_data_for_time(): _assert_has_data_for_time(da, start_date_bad, end_date_bad) +_CFTIME_DATE_TYPES = { + 'noleap': cftime.DatetimeNoLeap, + '365_day': cftime.DatetimeNoLeap, + '360_day': cftime.Datetime360Day, + 'julian': cftime.DatetimeJulian, + 'all_leap': cftime.DatetimeAllLeap, + '366_day': cftime.DatetimeAllLeap, + 'gregorian': cftime.DatetimeGregorian, + 'proleptic_gregorian': cftime.DatetimeProlepticGregorian +} + + [email protected](['calendar', 'date_type'], + list(_CFTIME_DATE_TYPES.items())) +def test_assert_has_data_for_time_cftime_datetimes(calendar, date_type): + time_bounds = np.array([[0, 2], [2, 4], [4, 6]]) + nv = np.array([0, 1]) + time = np.array([1, 3, 5]) + data = np.zeros((3)) + var_name = 'a' + ds = xr.DataArray(data, + coords=[time], + dims=[TIME_STR], + name=var_name).to_dataset() + ds[TIME_BOUNDS_STR] = xr.DataArray(time_bounds, + coords=[time, nv], + dims=[TIME_STR, BOUNDS_STR], + name=TIME_BOUNDS_STR) + units_str = 'days since 0002-01-02 00:00:00' + ds[TIME_STR].attrs['units'] = units_str + ds[TIME_STR].attrs['calendar'] = calendar + ds = ensure_time_avg_has_cf_metadata(ds) + ds = set_grid_attrs_as_coords(ds) + with xr.set_options(enable_cftimeindex=True): + ds = xr.decode_cf(ds) + da = ds[var_name] + + start_date = date_type(2, 1, 2) + end_date = date_type(2, 1, 8) + _assert_has_data_for_time(da, start_date, end_date) + + start_date_bad = date_type(2, 1, 1) + end_date_bad = date_type(2, 1, 9) + + with pytest.raises(AssertionError): + _assert_has_data_for_time(da, start_date_bad, end_date) + + with pytest.raises(AssertionError): + _assert_has_data_for_time(da, start_date, end_date_bad) + + with pytest.raises(AssertionError): + _assert_has_data_for_time(da, start_date_bad, end_date_bad) + + +def test_assert_has_data_for_time_str_input(): + time_bounds = np.array([[0, 31], [31, 59], [59, 90]]) + nv = np.array([0, 1]) + time = np.array([15, 46, 74]) + data = np.zeros((3)) + var_name = 'a' + ds = xr.DataArray(data, + coords=[time], + dims=[TIME_STR], + name=var_name).to_dataset() + ds[TIME_BOUNDS_STR] = xr.DataArray(time_bounds, + coords=[time, nv], + dims=[TIME_STR, BOUNDS_STR], + name=TIME_BOUNDS_STR) + units_str = 'days since 2000-01-01 00:00:00' + ds[TIME_STR].attrs['units'] = units_str + ds = ensure_time_avg_has_cf_metadata(ds) + ds = set_grid_attrs_as_coords(ds) + ds = xr.decode_cf(ds) + da = ds[var_name] + + start_date = '2000-01-01' + end_date = '2000-03-31' + _assert_has_data_for_time(da, start_date, end_date) + + start_date_bad = '1999-12-31' + end_date_bad = '2000-04-01' + + # With strings these checks are disabled + _assert_has_data_for_time(da, start_date_bad, end_date) + _assert_has_data_for_time(da, start_date, end_date_bad) + _assert_has_data_for_time(da, start_date_bad, end_date_bad) + + def test_assert_matching_time_coord(): rng = pd.date_range('2000-01-01', '2001-01-01', freq='M') arr1 = xr.DataArray(rng, coords=[rng], dims=[TIME_STR]) @@ -555,3 +540,83 @@ def test_average_time_bounds(ds_time_encoded_cf): coords={TIME_STR: desired_values}, name=TIME_STR) xr.testing.assert_identical(actual, desired) + + +_INFER_YEAR_TESTS = [ + (np.datetime64('2000-01-01'), 2000), + (datetime.datetime(2000, 1, 1), 2000), + ('2000', 2000), + ('2000-01', 2000), + ('2000-01-01', 2000) +] +_INFER_YEAR_TESTS = _INFER_YEAR_TESTS + [ + (date_type(2000, 1, 1), 2000) for date_type in _CFTIME_DATE_TYPES.values()] + + [email protected]( + ['date', 'expected'], + _INFER_YEAR_TESTS) +def test_infer_year(date, expected): + assert infer_year(date) == expected + + [email protected]('date', ['-0001', 'A001', '01']) +def test_infer_year_invalid(date): + with pytest.raises(ValueError): + infer_year(date) + + +_DATETIME_INDEX = pd.date_range('2000-01-01', freq='M', periods=1) +_DATETIME_CONVERT_TESTS = {} +for date_label, date_type in _CFTIME_DATE_TYPES.items(): + key = 'DatetimeIndex-{}'.format(date_label) + _DATETIME_CONVERT_TESTS[key] = (_DATETIME_INDEX, date_type(2000, 1, 1), + np.datetime64('2000-01')) +_NON_CFTIME_DATES = { + 'datetime.datetime': datetime.datetime(2000, 1, 1), + 'np.datetime64': np.datetime64('2000-01-01'), + 'str': '2000' +} +for date_label, date in _NON_CFTIME_DATES.items(): + key = 'DatetimeIndex-{}'.format(date_label) + if isinstance(date, str): + _DATETIME_CONVERT_TESTS[key] = (_DATETIME_INDEX, date, date) + else: + _DATETIME_CONVERT_TESTS[key] = (_DATETIME_INDEX, date, + np.datetime64('2000-01')) + +_CFTIME_INDEXES = { + 'CFTimeIndex[{}]'.format(key): xr.CFTimeIndex([value(1, 1, 1)]) for + key, value in _CFTIME_DATE_TYPES.items() +} +_CFTIME_CONVERT_TESTS = {} +for ((index_label, index), + (date_label, date_type)) in product(_CFTIME_INDEXES.items(), + _CFTIME_DATE_TYPES.items()): + key = '{}-{}'.format(index_label, date_label) + _CFTIME_CONVERT_TESTS[key] = (index, date_type(1, 1, 1), + index.date_type(1, 1, 1)) +_NON_CFTIME_DATES_0001 = { + 'datetime.datetime': datetime.datetime(1, 1, 1), + 'np.datetime64': np.datetime64('0001-01-01'), + 'str': '0001' +} +for ((idx_label, index), + (date_label, date)) in product(_CFTIME_INDEXES.items(), + _NON_CFTIME_DATES_0001.items()): + key = '{}-{}'.format(index_label, date_label) + if isinstance(date, str): + _CFTIME_CONVERT_TESTS[key] = (index, date, date) + else: + _CFTIME_CONVERT_TESTS[key] = (index, date, index.date_type(1, 1, 1)) + +_CONVERT_DATE_TYPE_TESTS = _merge_dicts(_DATETIME_CONVERT_TESTS, + _CFTIME_CONVERT_TESTS) + + [email protected](['index', 'date', 'expected'], + list(_CONVERT_DATE_TYPE_TESTS.values()), + ids=list(_CONVERT_DATE_TYPE_TESTS.keys())) +def test_maybe_convert_to_index_date_type(index, date, expected): + result = maybe_convert_to_index_date_type(index, date) + assert result == expected
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": -1, "issue_text_score": 1, "test_score": -1 }, "num_modified_files": 9 }
0.2
{ "env_vars": null, "env_yml_path": [ "ci/environment-py36.yml" ], "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "environment.yml", "pip_packages": [ "pytest", "flake8", "pytest-cov", "pytest-catchlog" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/spencerahill/aospy.git@7162010ef9cdc1b7a69146dd7feba91933af99ef#egg=aospy argon2-cffi @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi_1633990451307/work async_generator @ file:///home/conda/feedstock_root/build_artifacts/async_generator_1722652753231/work attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1671632566681/work backcall @ file:///home/conda/feedstock_root/build_artifacts/backcall_1592338393461/work backports.functools-lru-cache @ file:///home/conda/feedstock_root/build_artifacts/backports.functools_lru_cache_1702571698061/work bleach @ file:///home/conda/feedstock_root/build_artifacts/bleach_1696630167146/work bokeh @ file:///home/conda/feedstock_root/build_artifacts/bokeh_1625756939897/work certifi==2021.5.30 cffi @ file:///home/conda/feedstock_root/build_artifacts/cffi_1631636256886/work cftime @ file:///home/conda/feedstock_root/build_artifacts/cftime_1632539733990/work charset-normalizer==2.0.12 click==7.1.2 cloudpickle @ file:///home/conda/feedstock_root/build_artifacts/cloudpickle_1674202310934/work contextvars==2.4 coverage==6.2 coveralls==3.3.1 cycler @ file:///home/conda/feedstock_root/build_artifacts/cycler_1635519461629/work cytoolz==0.11.0 dask @ file:///home/conda/feedstock_root/build_artifacts/dask-core_1614995065708/work decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1641555617451/work defusedxml @ file:///home/conda/feedstock_root/build_artifacts/defusedxml_1615232257335/work distributed @ file:///home/conda/feedstock_root/build_artifacts/distributed_1615002625500/work docopt==0.6.2 entrypoints @ file:///home/conda/feedstock_root/build_artifacts/entrypoints_1643888246732/work flake8 @ file:///home/conda/feedstock_root/build_artifacts/flake8_1659645013175/work fsspec @ file:///home/conda/feedstock_root/build_artifacts/fsspec_1674184942191/work future @ file:///home/conda/feedstock_root/build_artifacts/future_1610147328086/work HeapDict==1.0.1 idna==3.10 immutables @ file:///home/conda/feedstock_root/build_artifacts/immutables_1628601257972/work importlib-metadata==4.2.0 iniconfig @ file:///home/conda/feedstock_root/build_artifacts/iniconfig_1603384189793/work ipykernel @ file:///home/conda/feedstock_root/build_artifacts/ipykernel_1620912934572/work/dist/ipykernel-5.5.5-py3-none-any.whl ipython @ file:///home/conda/feedstock_root/build_artifacts/ipython_1609697613279/work ipython_genutils @ file:///home/conda/feedstock_root/build_artifacts/ipython_genutils_1716278396992/work ipywidgets @ file:///home/conda/feedstock_root/build_artifacts/ipywidgets_1679421482533/work jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1605054537831/work Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1636510082894/work jsonschema @ file:///home/conda/feedstock_root/build_artifacts/jsonschema_1634752161479/work jupyter @ file:///home/conda/feedstock_root/build_artifacts/jupyter_1696255489086/work jupyter-client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1642858610849/work jupyter-console @ file:///home/conda/feedstock_root/build_artifacts/jupyter_console_1676328545892/work jupyter-core @ file:///home/conda/feedstock_root/build_artifacts/jupyter_core_1631852698933/work jupyterlab-pygments @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_pygments_1601375948261/work jupyterlab-widgets @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_widgets_1655961217661/work kiwisolver @ file:///home/conda/feedstock_root/build_artifacts/kiwisolver_1610099771815/work locket @ file:///home/conda/feedstock_root/build_artifacts/locket_1650660393415/work MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1621455668064/work matplotlib @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-suite_1611858699142/work mccabe @ file:///home/conda/feedstock_root/build_artifacts/mccabe_1643049622439/work mistune @ file:///home/conda/feedstock_root/build_artifacts/mistune_1673904152039/work more-itertools @ file:///home/conda/feedstock_root/build_artifacts/more-itertools_1690211628840/work msgpack @ file:///home/conda/feedstock_root/build_artifacts/msgpack-python_1610121702224/work nbclient @ file:///home/conda/feedstock_root/build_artifacts/nbclient_1637327213451/work nbconvert @ file:///home/conda/feedstock_root/build_artifacts/nbconvert_1605401832871/work nbformat @ file:///home/conda/feedstock_root/build_artifacts/nbformat_1617383142101/work nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1705850609492/work netCDF4 @ file:///home/conda/feedstock_root/build_artifacts/netcdf4_1633096406418/work notebook @ file:///home/conda/feedstock_root/build_artifacts/notebook_1616419146127/work numpy @ file:///home/conda/feedstock_root/build_artifacts/numpy_1626681920064/work olefile @ file:///home/conda/feedstock_root/build_artifacts/olefile_1602866521163/work packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1637239678211/work pandas==1.1.5 pandocfilters @ file:///home/conda/feedstock_root/build_artifacts/pandocfilters_1631603243851/work parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1595548966091/work partd @ file:///home/conda/feedstock_root/build_artifacts/partd_1617910651905/work pexpect @ file:///home/conda/feedstock_root/build_artifacts/pexpect_1667297516076/work pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1602536217715/work Pillow @ file:///home/conda/feedstock_root/build_artifacts/pillow_1630696616009/work pluggy @ file:///home/conda/feedstock_root/build_artifacts/pluggy_1631522669284/work prometheus-client @ file:///home/conda/feedstock_root/build_artifacts/prometheus_client_1689032443210/work prompt-toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1670414775770/work psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1610127101219/work ptyprocess @ file:///home/conda/feedstock_root/build_artifacts/ptyprocess_1609419310487/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl py @ file:///home/conda/feedstock_root/build_artifacts/py_1636301881863/work pycodestyle @ file:///home/conda/feedstock_root/build_artifacts/pycodestyle_1659638152915/work pycparser @ file:///home/conda/feedstock_root/build_artifacts/pycparser_1636257122734/work pyflakes @ file:///home/conda/feedstock_root/build_artifacts/pyflakes_1659210156976/work Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1672682006896/work pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1724616129934/work PyQt5==5.12.3 PyQt5_sip==4.19.18 PyQtChart==5.12 PyQtWebEngine==5.12.1 pyrsistent @ file:///home/conda/feedstock_root/build_artifacts/pyrsistent_1610146795286/work pytest==6.2.5 pytest-catchlog==1.2.2 pytest-cov==4.0.0 python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1626286286081/work pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1693930252784/work PyYAML==5.4.1 pyzmq @ file:///home/conda/feedstock_root/build_artifacts/pyzmq_1631793305981/work qtconsole @ file:///home/conda/feedstock_root/build_artifacts/qtconsole-base_1640876679830/work QtPy @ file:///home/conda/feedstock_root/build_artifacts/qtpy_1643828301492/work requests==2.27.1 scipy @ file:///home/conda/feedstock_root/build_artifacts/scipy_1629411471490/work Send2Trash @ file:///home/conda/feedstock_root/build_artifacts/send2trash_1682601222253/work six @ file:///home/conda/feedstock_root/build_artifacts/six_1620240208055/work sortedcontainers @ file:///home/conda/feedstock_root/build_artifacts/sortedcontainers_1621217038088/work tblib @ file:///home/conda/feedstock_root/build_artifacts/tblib_1616261298899/work terminado @ file:///home/conda/feedstock_root/build_artifacts/terminado_1631128154882/work testpath @ file:///home/conda/feedstock_root/build_artifacts/testpath_1645693042223/work toml @ file:///home/conda/feedstock_root/build_artifacts/toml_1604308577558/work tomli==1.2.3 toolz @ file:///home/conda/feedstock_root/build_artifacts/toolz_1657485559105/work tornado @ file:///home/conda/feedstock_root/build_artifacts/tornado_1610094701020/work traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1631041982274/work typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/typing_extensions_1644850595256/work urllib3==1.26.20 wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1699959196938/work webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1694681268211/work widgetsnbextension @ file:///home/conda/feedstock_root/build_artifacts/widgetsnbextension_1655939017940/work xarray @ file:///home/conda/feedstock_root/build_artifacts/xarray_1621474818012/work zict==2.0.0 zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1633302054558/work
name: aospy channels: - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=conda_forge - _openmp_mutex=4.5=2_gnu - alsa-lib=1.2.7.2=h166bdaf_0 - argon2-cffi=21.1.0=py36h8f6f2f9_0 - async_generator=1.10=pyhd8ed1ab_1 - attrs=22.2.0=pyh71513ae_0 - backcall=0.2.0=pyh9f0ad1d_0 - backports=1.0=pyhd8ed1ab_4 - backports.functools_lru_cache=2.0.0=pyhd8ed1ab_0 - bleach=6.1.0=pyhd8ed1ab_0 - bokeh=2.3.3=py36h5fab9bb_0 - bzip2=1.0.8=h4bc722e_7 - c-ares=1.34.4=hb9d3cd8_0 - ca-certificates=2025.1.31=hbcca054_0 - certifi=2021.5.30=py36h5fab9bb_0 - cffi=1.14.6=py36hd8eec40_1 - cftime=1.5.1=py36he33b4a0_0 - click=7.1.2=pyh9f0ad1d_0 - cloudpickle=2.2.1=pyhd8ed1ab_0 - contextvars=2.4=py_0 - curl=7.87.0=h6312ad2_0 - cycler=0.11.0=pyhd8ed1ab_0 - cytoolz=0.11.0=py36h8f6f2f9_3 - dask=2021.3.0=pyhd8ed1ab_0 - dask-core=2021.3.0=pyhd8ed1ab_0 - dbus=1.13.6=h5008d03_3 - decorator=5.1.1=pyhd8ed1ab_0 - defusedxml=0.7.1=pyhd8ed1ab_0 - distributed=2021.3.0=py36h5fab9bb_0 - entrypoints=0.4=pyhd8ed1ab_0 - expat=2.6.4=h5888daf_0 - flake8=5.0.4=pyhd8ed1ab_0 - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 - font-ttf-inconsolata=3.000=h77eed37_0 - font-ttf-source-code-pro=2.038=h77eed37_0 - font-ttf-ubuntu=0.83=h77eed37_3 - fontconfig=2.14.2=h14ed4e7_0 - fonts-conda-ecosystem=1=0 - fonts-conda-forge=1=0 - freetype=2.12.1=h267a509_2 - fsspec=2023.1.0=pyhd8ed1ab_0 - future=0.18.2=py36h5fab9bb_3 - gettext=0.23.1=h5888daf_0 - gettext-tools=0.23.1=h5888daf_0 - glib=2.80.2=hf974151_0 - glib-tools=2.80.2=hb6ce0ca_0 - gst-plugins-base=1.20.3=h57caac4_2 - gstreamer=1.20.3=hd4edc92_2 - hdf4=4.2.15=h9772cbc_5 - hdf5=1.12.1=nompi_h2386368_104 - heapdict=1.0.1=py_0 - icu=69.1=h9c3ff4c_0 - immutables=0.16=py36h8f6f2f9_0 - importlib_metadata=4.8.1=hd8ed1ab_1 - iniconfig=1.1.1=pyh9f0ad1d_0 - ipykernel=5.5.5=py36hcb3619a_0 - ipython=7.16.1=py36he448a4c_2 - ipython_genutils=0.2.0=pyhd8ed1ab_1 - ipywidgets=7.7.4=pyhd8ed1ab_0 - jedi=0.17.2=py36h5fab9bb_1 - jinja2=3.0.3=pyhd8ed1ab_0 - jpeg=9e=h0b41bf4_3 - jsonschema=4.1.2=pyhd8ed1ab_0 - jupyter=1.0.0=pyhd8ed1ab_10 - jupyter_client=7.1.2=pyhd8ed1ab_0 - jupyter_console=6.5.1=pyhd8ed1ab_0 - jupyter_core=4.8.1=py36h5fab9bb_0 - jupyterlab_pygments=0.1.2=pyh9f0ad1d_0 - jupyterlab_widgets=1.1.1=pyhd8ed1ab_0 - keyutils=1.6.1=h166bdaf_0 - kiwisolver=1.3.1=py36h605e78d_1 - krb5=1.20.1=hf9c8cef_0 - lcms2=2.12=hddcbb42_0 - ld_impl_linux-64=2.43=h712a8e2_4 - lerc=3.0=h9c3ff4c_0 - libasprintf=0.23.1=h8e693c7_0 - libasprintf-devel=0.23.1=h8e693c7_0 - libblas=3.9.0=20_linux64_openblas - libcblas=3.9.0=20_linux64_openblas - libclang=13.0.1=default_hb5137d0_10 - libcurl=7.87.0=h6312ad2_0 - libdeflate=1.10=h7f98852_0 - libedit=3.1.20250104=pl5321h7949ede_0 - libev=4.33=hd590300_2 - libevent=2.1.10=h9b69904_4 - libexpat=2.6.4=h5888daf_0 - libffi=3.4.6=h2dba641_0 - libgcc=14.2.0=h767d61c_2 - libgcc-ng=14.2.0=h69a702a_2 - libgettextpo=0.23.1=h5888daf_0 - libgettextpo-devel=0.23.1=h5888daf_0 - libgfortran=14.2.0=h69a702a_2 - libgfortran-ng=14.2.0=h69a702a_2 - libgfortran5=14.2.0=hf1ad2bd_2 - libglib=2.80.2=hf974151_0 - libgomp=14.2.0=h767d61c_2 - libiconv=1.18=h4ce23a2_1 - liblapack=3.9.0=20_linux64_openblas - libllvm13=13.0.1=hf817b99_2 - liblzma=5.6.4=hb9d3cd8_0 - liblzma-devel=5.6.4=hb9d3cd8_0 - libnetcdf=4.8.1=nompi_h329d8a1_102 - libnghttp2=1.51.0=hdcd2b5c_0 - libnsl=2.0.1=hd590300_0 - libogg=1.3.5=h4ab18f5_0 - libopenblas=0.3.25=pthreads_h413a1c8_0 - libopus=1.3.1=h7f98852_1 - libpng=1.6.43=h2797004_0 - libpq=14.5=h2baec63_5 - libsodium=1.0.18=h36c2ea0_1 - libsqlite=3.46.0=hde9e2c9_0 - libssh2=1.10.0=haa6b8db_3 - libstdcxx=14.2.0=h8f9b012_2 - libstdcxx-ng=14.2.0=h4852527_2 - libtiff=4.3.0=h0fcbabc_4 - libuuid=2.38.1=h0b41bf4_0 - libvorbis=1.3.7=h9c3ff4c_0 - libwebp-base=1.5.0=h851e524_0 - libxcb=1.13=h7f98852_1004 - libxkbcommon=1.0.3=he3ba5ed_0 - libxml2=2.9.14=haae042b_4 - libzip=1.9.2=hc869a4a_1 - libzlib=1.2.13=h4ab18f5_6 - locket=1.0.0=pyhd8ed1ab_0 - markupsafe=2.0.1=py36h8f6f2f9_0 - matplotlib=3.3.4=py36h5fab9bb_0 - matplotlib-base=3.3.4=py36hd391965_0 - mccabe=0.7.0=pyhd8ed1ab_0 - mistune=0.8.4=pyh1a96a4e_1006 - more-itertools=10.0.0=pyhd8ed1ab_0 - msgpack-python=1.0.2=py36h605e78d_1 - mysql-common=8.0.32=h14678bc_0 - mysql-libs=8.0.32=h54cf53e_0 - nbclient=0.5.9=pyhd8ed1ab_0 - nbconvert=6.0.7=py36h5fab9bb_3 - nbformat=5.1.3=pyhd8ed1ab_0 - ncurses=6.5=h2d0b736_3 - nest-asyncio=1.6.0=pyhd8ed1ab_0 - netcdf4=1.5.7=nompi_py36h775750b_103 - notebook=6.3.0=py36h5fab9bb_0 - nspr=4.36=h5888daf_0 - nss=3.100=hca3bf56_0 - numpy=1.19.5=py36hfc0c790_2 - olefile=0.46=pyh9f0ad1d_1 - openjpeg=2.5.0=h7d73246_0 - openssl=1.1.1w=hd590300_0 - packaging=21.3=pyhd8ed1ab_0 - pandas=1.1.5=py36h284efc9_0 - pandoc=2.19.2=h32600fe_2 - pandocfilters=1.5.0=pyhd8ed1ab_0 - parso=0.7.1=pyh9f0ad1d_0 - partd=1.2.0=pyhd8ed1ab_0 - pcre2=10.43=hcad00b1_0 - pexpect=4.8.0=pyh1a96a4e_2 - pickleshare=0.7.5=py_1003 - pillow=8.3.2=py36h676a545_0 - pip=21.3.1=pyhd8ed1ab_0 - pluggy=1.0.0=py36h5fab9bb_1 - prometheus_client=0.17.1=pyhd8ed1ab_0 - prompt-toolkit=3.0.36=pyha770c72_0 - prompt_toolkit=3.0.36=hd8ed1ab_0 - psutil=5.8.0=py36h8f6f2f9_1 - pthread-stubs=0.4=hb9d3cd8_1002 - ptyprocess=0.7.0=pyhd3deb0d_0 - py=1.11.0=pyh6c4a22f_0 - pycodestyle=2.9.1=pyhd8ed1ab_0 - pycparser=2.21=pyhd8ed1ab_0 - pyflakes=2.5.0=pyhd8ed1ab_0 - pygments=2.14.0=pyhd8ed1ab_0 - pyparsing=3.1.4=pyhd8ed1ab_0 - pyqt=5.12.3=py36h5fab9bb_7 - pyqt-impl=5.12.3=py36h7ec31b9_7 - pyqt5-sip=4.19.18=py36hc4f0c31_7 - pyqtchart=5.12=py36h7ec31b9_7 - pyqtwebengine=5.12.1=py36h7ec31b9_7 - pyrsistent=0.17.3=py36h8f6f2f9_2 - pytest=6.2.5=py36h5fab9bb_0 - python=3.6.15=hb7a2778_0_cpython - python-dateutil=2.8.2=pyhd8ed1ab_0 - python_abi=3.6=2_cp36m - pytz=2023.3.post1=pyhd8ed1ab_0 - pyyaml=5.4.1=py36h8f6f2f9_1 - pyzmq=22.3.0=py36h7068817_0 - qt=5.12.9=h1304e3e_6 - qtconsole-base=5.2.2=pyhd8ed1ab_1 - qtpy=2.0.1=pyhd8ed1ab_0 - readline=8.2=h8c095d6_2 - scipy=1.5.3=py36h81d768a_1 - send2trash=1.8.2=pyh41d4057_0 - setuptools=58.0.4=py36h5fab9bb_2 - six=1.16.0=pyh6c4a22f_0 - sortedcontainers=2.4.0=pyhd8ed1ab_0 - sqlite=3.46.0=h6d4b2fc_0 - tblib=1.7.0=pyhd8ed1ab_0 - terminado=0.12.1=py36h5fab9bb_0 - testpath=0.6.0=pyhd8ed1ab_0 - tk=8.6.13=noxft_h4845f30_101 - toml=0.10.2=pyhd8ed1ab_0 - toolz=0.12.0=pyhd8ed1ab_0 - tornado=6.1=py36h8f6f2f9_1 - traitlets=4.3.3=pyhd8ed1ab_2 - typing-extensions=4.1.1=hd8ed1ab_0 - typing_extensions=4.1.1=pyha770c72_0 - wcwidth=0.2.10=pyhd8ed1ab_0 - webencodings=0.5.1=pyhd8ed1ab_2 - wheel=0.37.1=pyhd8ed1ab_0 - widgetsnbextension=3.6.1=pyha770c72_0 - xarray=0.18.2=pyhd8ed1ab_0 - xorg-libxau=1.0.12=hb9d3cd8_0 - xorg-libxdmcp=1.1.5=hb9d3cd8_0 - xz=5.6.4=hbcc6ac9_0 - xz-gpl-tools=5.6.4=hbcc6ac9_0 - xz-tools=5.6.4=hb9d3cd8_0 - yaml=0.2.5=h7f98852_2 - zeromq=4.3.5=h59595ed_1 - zict=2.0.0=py_0 - zipp=3.6.0=pyhd8ed1ab_0 - zlib=1.2.13=h4ab18f5_6 - zstd=1.5.6=ha6fb4c9_0 - pip: - charset-normalizer==2.0.12 - coverage==6.2 - coveralls==3.3.1 - docopt==0.6.2 - idna==3.10 - importlib-metadata==4.2.0 - pytest-catchlog==1.2.2 - pytest-cov==4.0.0 - requests==2.27.1 - tomli==1.2.3 - urllib3==1.26.20 prefix: /opt/conda/envs/aospy
[ "aospy/test/test_calc_basic.py::test_calc_object_string_time_options[av]", "aospy/test/test_calc_basic.py::test_calc_object_string_time_options[std]", "aospy/test/test_calc_basic.py::test_calc_object_string_time_options[ts]", "aospy/test/test_calc_basic.py::test_calc_object_string_time_options[reg.av]", "aospy/test/test_calc_basic.py::test_calc_object_string_time_options[reg.std]", "aospy/test/test_calc_basic.py::test_calc_object_string_time_options[reg.ts]", "aospy/test/test_calc_basic.py::test_calc_object_time_options", "aospy/test/test_calc_basic.py::test_attrs[--None--]", "aospy/test/test_calc_basic.py::test_attrs[m--None-m-]", "aospy/test/test_calc_basic.py::test_attrs[-rain-None--rain]", "aospy/test/test_calc_basic.py::test_attrs[m-rain-None-m-rain]", "aospy/test/test_calc_basic.py::test_attrs[--vert_av--]", "aospy/test/test_calc_basic.py::test_attrs[m--vert_av-m-]", "aospy/test/test_calc_basic.py::test_attrs[-rain-vert_av--rain]", "aospy/test/test_calc_basic.py::test_attrs[m-rain-vert_av-m-rain]", "aospy/test/test_calc_basic.py::test_attrs[--vert_int-(vertical", "aospy/test/test_calc_basic.py::test_attrs[m--vert_int-(vertical", "aospy/test/test_calc_basic.py::test_attrs[-rain-vert_int-(vertical", "aospy/test/test_calc_basic.py::test_attrs[m-rain-vert_int-(vertical", "aospy/test/test_data_loader.py::test_maybe_cast_to_float64[float32-float64]", "aospy/test/test_data_loader.py::test_maybe_cast_to_float64[int-int]", "aospy/test/test_data_loader.py::test_rename_grid_attrs_ds", "aospy/test/test_data_loader.py::test_rename_grid_attrs_dim_no_coord", "aospy/test/test_data_loader.py::test_rename_grid_attrs_skip_scalar_dim", "aospy/test/test_data_loader.py::test_rename_grid_attrs_copy_attrs", "aospy/test/test_data_loader.py::test_set_grid_attrs_as_coords", "aospy/test/test_data_loader.py::test_sel_var", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-datetime-datetime]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-datetime-datetime64]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-datetime-cftime]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-datetime-str]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-datetime64-datetime]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-datetime64-datetime64]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-datetime64-cftime]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-datetime64-str]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-cftime-datetime]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-cftime-datetime64]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-cftime-cftime]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-cftime-str]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-str-datetime]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-str-datetime64]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-str-cftime]", "aospy/test/test_data_loader.py::test_maybe_apply_time_shift_ts[GFDLDataLoader-str-str]", "aospy/test/test_data_loader.py::test_preprocess_and_rename_grid_attrs", "aospy/test/test_data_loader.py::test_generate_file_set[DataLoader-datetime]", "aospy/test/test_data_loader.py::test_generate_file_set[DataLoader-datetime64]", "aospy/test/test_data_loader.py::test_generate_file_set[DataLoader-cftime]", "aospy/test/test_data_loader.py::test_generate_file_set[DataLoader-str]", "aospy/test/test_data_loader.py::test_generate_file_set[DictDataLoader-datetime]", "aospy/test/test_data_loader.py::test_generate_file_set[DictDataLoader-datetime64]", "aospy/test/test_data_loader.py::test_generate_file_set[DictDataLoader-cftime]", "aospy/test/test_data_loader.py::test_generate_file_set[DictDataLoader-str]", "aospy/test/test_data_loader.py::test_generate_file_set[NestedDictDataLoader-datetime]", "aospy/test/test_data_loader.py::test_generate_file_set[NestedDictDataLoader-datetime64]", "aospy/test/test_data_loader.py::test_generate_file_set[NestedDictDataLoader-cftime]", "aospy/test/test_data_loader.py::test_generate_file_set[NestedDictDataLoader-str]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-datetime-datetime]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-datetime-datetime64]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-datetime-cftime]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-datetime-str]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-datetime64-datetime]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-datetime64-datetime64]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-datetime64-cftime]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-datetime64-str]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-cftime-datetime]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-cftime-datetime64]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-cftime-cftime]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-cftime-str]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-str-datetime]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-str-datetime64]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-str-cftime]", "aospy/test/test_data_loader.py::test_generate_file_set[GFDLDataLoader-str-str]", "aospy/test/test_data_loader.py::test_overriding_constructor[GFDLDataLoader-datetime]", "aospy/test/test_data_loader.py::test_overriding_constructor[GFDLDataLoader-datetime64]", "aospy/test/test_data_loader.py::test_overriding_constructor[GFDLDataLoader-cftime]", "aospy/test/test_data_loader.py::test_overriding_constructor[GFDLDataLoader-str]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-datetime-datetime]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-datetime-datetime64]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-datetime-cftime]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-datetime-str]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-datetime64-datetime]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-datetime64-datetime64]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-datetime64-cftime]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-datetime64-str]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-cftime-datetime]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-cftime-datetime64]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-cftime-cftime]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-cftime-str]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-str-datetime]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-str-datetime64]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-str-cftime]", "aospy/test/test_data_loader.py::test_input_data_paths_gfdl[GFDLDataLoader-str-str]", "aospy/test/test_data_loader.py::test_data_name_gfdl_annual", "aospy/test/test_data_loader.py::test_data_name_gfdl_monthly", "aospy/test/test_data_loader.py::test_data_name_gfdl_daily", "aospy/test/test_data_loader.py::test_data_name_gfdl_hr", "aospy/test/test_data_loader.py::test_data_name_gfdl_seasonal", "aospy/test/test_data_loader.py::test_load_variable[datetime]", "aospy/test/test_data_loader.py::test_load_variable[datetime64]", "aospy/test/test_data_loader.py::test_load_variable[cftime]", "aospy/test/test_data_loader.py::test_load_variable[str]", "aospy/test/test_data_loader.py::test_load_variable_float32_to_float64[datetime]", "aospy/test/test_data_loader.py::test_load_variable_float32_to_float64[datetime64]", "aospy/test/test_data_loader.py::test_load_variable_float32_to_float64[cftime]", "aospy/test/test_data_loader.py::test_load_variable_float32_to_float64[str]", "aospy/test/test_data_loader.py::test_load_variable_maintain_float32[datetime]", "aospy/test/test_data_loader.py::test_load_variable_maintain_float32[datetime64]", "aospy/test/test_data_loader.py::test_load_variable_maintain_float32[cftime]", "aospy/test/test_data_loader.py::test_load_variable_maintain_float32[str]", "aospy/test/test_data_loader.py::test_load_variable_data_vars_all[datetime]", "aospy/test/test_data_loader.py::test_load_variable_data_vars_all[datetime64]", "aospy/test/test_data_loader.py::test_load_variable_data_vars_all[cftime]", "aospy/test/test_data_loader.py::test_load_variable_data_vars_all[str]", "aospy/test/test_data_loader.py::test_load_variable_data_vars_default[datetime]", "aospy/test/test_data_loader.py::test_load_variable_data_vars_default[datetime64]", "aospy/test/test_data_loader.py::test_load_variable_data_vars_default[cftime]", "aospy/test/test_data_loader.py::test_load_variable_data_vars_default[str]", "aospy/test/test_data_loader.py::test_load_variable_coords_all[datetime]", "aospy/test/test_data_loader.py::test_load_variable_coords_all[datetime64]", "aospy/test/test_data_loader.py::test_load_variable_coords_all[cftime]", "aospy/test/test_data_loader.py::test_load_variable_coords_all[str]", "aospy/test/test_data_loader.py::test_load_variable_non_0001_refdate[4]", "aospy/test/test_data_loader.py::test_load_variable_non_0001_refdate[5]", "aospy/test/test_data_loader.py::test_load_variable_non_0001_refdate[6]", "aospy/test/test_data_loader.py::test_load_variable_preprocess", "aospy/test/test_data_loader.py::test_load_variable_mask_and_scale", "aospy/test/test_data_loader.py::test_recursively_compute_variable_native", "aospy/test/test_data_loader.py::test_recursively_compute_variable_one_level", "aospy/test/test_data_loader.py::test_recursively_compute_variable_multi_level", "aospy/test/test_run.py::TestRun::test_init_dates_invalid_input", "aospy/test/test_run.py::TestRun::test_init_dates_valid_input", "aospy/test/test_run.py::TestRun::test_init_default_dates", "aospy/test/test_utils_times.py::test_apply_time_offset", "aospy/test/test_utils_times.py::test_ensure_datetime_valid_input[date0]", "aospy/test/test_utils_times.py::test_ensure_datetime_valid_input[date1]", "aospy/test/test_utils_times.py::test_ensure_datetime_valid_input[date2]", "aospy/test/test_utils_times.py::test_ensure_datetime_valid_input[2000-01-01]", "aospy/test/test_utils_times.py::test_ensure_datetime_invalid_input", "aospy/test/test_utils_times.py::test_datetime_or_default", "aospy/test/test_utils_times.py::test_month_indices", "aospy/test/test_utils_times.py::test_month_conditional", "aospy/test/test_utils_times.py::test_extract_months", "aospy/test/test_utils_times.py::test_extract_months_single_month", "aospy/test/test_utils_times.py::test_ensure_time_avg_has_cf_metadata", "aospy/test/test_utils_times.py::test_add_uniform_time_weights", "aospy/test/test_utils_times.py::test_assert_has_data_for_time", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[noleap-DatetimeNoLeap]", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[365_day-DatetimeNoLeap]", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[360_day-Datetime360Day]", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[julian-DatetimeJulian]", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[all_leap-DatetimeAllLeap]", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[366_day-DatetimeAllLeap]", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[gregorian-DatetimeGregorian]", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_cftime_datetimes[proleptic_gregorian-DatetimeProlepticGregorian]", "aospy/test/test_utils_times.py::test_assert_has_data_for_time_str_input", "aospy/test/test_utils_times.py::test_assert_matching_time_coord", "aospy/test/test_utils_times.py::test_ensure_time_as_index_no_change", "aospy/test/test_utils_times.py::test_ensure_time_as_index_with_change", "aospy/test/test_utils_times.py::test_sel_time", "aospy/test/test_utils_times.py::test_yearly_average_no_mask", "aospy/test/test_utils_times.py::test_yearly_average_masked_data", "aospy/test/test_utils_times.py::test_average_time_bounds", "aospy/test/test_utils_times.py::test_infer_year[date0-2000]", "aospy/test/test_utils_times.py::test_infer_year[date1-2000]", "aospy/test/test_utils_times.py::test_infer_year[2000-2000]", "aospy/test/test_utils_times.py::test_infer_year[2000-01-2000]", "aospy/test/test_utils_times.py::test_infer_year[2000-01-01-2000]", "aospy/test/test_utils_times.py::test_infer_year[date5-2000]", "aospy/test/test_utils_times.py::test_infer_year[date6-2000]", "aospy/test/test_utils_times.py::test_infer_year[date7-2000]", "aospy/test/test_utils_times.py::test_infer_year[date8-2000]", "aospy/test/test_utils_times.py::test_infer_year[date9-2000]", "aospy/test/test_utils_times.py::test_infer_year[date10-2000]", "aospy/test/test_utils_times.py::test_infer_year[date11-2000]", "aospy/test/test_utils_times.py::test_infer_year[date12-2000]", "aospy/test/test_utils_times.py::test_infer_year_invalid[-0001]", "aospy/test/test_utils_times.py::test_infer_year_invalid[A001]", "aospy/test/test_utils_times.py::test_infer_year_invalid[01]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-datetime.datetime]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-np.datetime64]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[DatetimeIndex-str]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[noleap]-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[365_day]-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[360_day]-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[julian]-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[all_leap]-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[366_day]-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[gregorian]-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-noleap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-365_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-360_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-julian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-all_leap]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-366_day]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-proleptic_gregorian]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-datetime.datetime]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-np.datetime64]", "aospy/test/test_utils_times.py::test_maybe_convert_to_index_date_type[CFTimeIndex[proleptic_gregorian]-str]" ]
[ "aospy/test/test_calc_basic.py::test_recursive_calculation", "aospy/test/test_calc_basic.py::test_annual_mean[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_annual_mean[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_annual_mean[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_annual_mean[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_annual_mean[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_annual_mean[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_annual_mean[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_annual_mean[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_annual_mean[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_annual_mean[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_annual_mean[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_annual_ts[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_annual_ts[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_annual_ts[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_annual_ts[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_annual_ts[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_annual_ts[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_annual_ts[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_annual_ts[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_annual_ts[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_annual_ts[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_annual_ts[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_seasonal_mean[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_mean[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_mean[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_mean[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_mean[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_mean[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_mean[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_mean[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_mean[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_seasonal_mean[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_seasonal_mean[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_seasonal_ts[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_ts[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_ts[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_ts[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_ts[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_ts[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_ts[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_ts[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_seasonal_ts[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_seasonal_ts[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_seasonal_ts[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_monthly_mean[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_monthly_mean[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_monthly_mean[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_monthly_mean[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_monthly_mean[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_monthly_mean[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_monthly_mean[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_monthly_mean[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_monthly_mean[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_monthly_mean[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_monthly_mean[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_monthly_ts[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_monthly_ts[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_monthly_ts[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_monthly_ts[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_monthly_ts[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_monthly_ts[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_monthly_ts[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_monthly_ts[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_monthly_ts[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_monthly_ts[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_monthly_ts[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_simple_reg_av[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_av[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_av[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_av[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_av[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_av[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_av[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_av[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_av[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_simple_reg_av[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_simple_reg_av[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_simple_reg_ts[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_complex_reg_av[datetime-basic-None-None]", "aospy/test/test_calc_basic.py::test_complex_reg_av[datetime-composite-None-None]", "aospy/test/test_calc_basic.py::test_complex_reg_av[datetime64-basic-None-None]", "aospy/test/test_calc_basic.py::test_complex_reg_av[datetime64-composite-None-None]", "aospy/test/test_calc_basic.py::test_complex_reg_av[cftime-basic-None-None]", "aospy/test/test_calc_basic.py::test_complex_reg_av[cftime-composite-None-None]", "aospy/test/test_calc_basic.py::test_complex_reg_av[str-basic-None-None]", "aospy/test/test_calc_basic.py::test_complex_reg_av[str-composite-None-None]", "aospy/test/test_calc_basic.py::test_complex_reg_av[datetime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_complex_reg_av[datetime64-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_complex_reg_av[cftime-3D-sigma-vert_int]", "aospy/test/test_calc_basic.py::test_calc_object_no_time_options[None]", "aospy/test/test_calc_basic.py::test_calc_object_no_time_options[dtype_out_time1]", "aospy/test/test_data_loader.py::test_load_variable_does_not_warn[datetime]", "aospy/test/test_data_loader.py::test_load_variable_does_not_warn[datetime64]", "aospy/test/test_data_loader.py::test_load_variable_does_not_warn[cftime]", "aospy/test/test_data_loader.py::test_load_variable_does_not_warn[str]", "aospy/test/test_utils_times.py::test_monthly_mean_ts_single_month", "aospy/test/test_utils_times.py::test_monthly_mean_ts_submonthly", "aospy/test/test_utils_times.py::test_monthly_mean_ts_monthly", "aospy/test/test_utils_times.py::test_monthly_mean_ts_na", "aospy/test/test_utils_times.py::test_monthly_mean_at_each_ind" ]
[]
[]
Apache License 2.0
2,549
[ "aospy/utils/times.py", "docs/whats-new.rst", "setup.py", "aospy/examples/example_obj_lib.py", "aospy/data_loader.py", "docs/examples.rst", "aospy/calc.py", "appveyor.yml", "aospy/examples/tutorial.ipynb" ]
[ "aospy/utils/times.py", "docs/whats-new.rst", "setup.py", "aospy/examples/example_obj_lib.py", "aospy/data_loader.py", "docs/examples.rst", "aospy/calc.py", "appveyor.yml", "aospy/examples/tutorial.ipynb" ]
fniessink__next-action-58
59b44d490e41069dad67aea493337747864d639c
2018-05-19 16:35:02
59b44d490e41069dad67aea493337747864d639c
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f75f42..c4ec0b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- Other properties being equal, task with more projects get precedence over tasks with fewer projects when selecting the next action. Closes #57. + ## [0.4.0] - 2018-05-19 ### Changed diff --git a/README.md b/README.md index 4a0f179..2337d3d 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,9 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the $ next-action --help usage: next-action [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...] -Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on -priority, due date, creation date, and supplied filters. +Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task +properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by +specifying contexts the tasks must have and/or projects the tasks must belong to. optional arguments: -h, --help show this help message and exit @@ -56,7 +57,7 @@ $ next-action (A) Call mom @phone ``` -The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks. +The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks. FInally, tasks that belong to more projects get precedence over tasks that belong to fewer projects. Completed tasks (~~`x This is a completed task`~~) and tasks with a creation date in the future (`9999-01-01 Start preparing for five-digit years`) are not considered when determining the next action. diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index 0d3ed9d..a53589e 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -10,7 +10,9 @@ def build_parser(default_filenames: List[str]) -> argparse.ArgumentParser: """ Create the arguments parsers. """ parser = argparse.ArgumentParser( description="Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt \ - file based on priority, due date, creation date, and supplied filters.", + file based on task properties such as priority, due date, and creation date. Limit the tasks from \ + which the next action is selected by specifying contexts the tasks must have and/or projects the \ + tasks must belong to.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, usage="%(prog)s [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...]") add_optional_arguments(parser, default_filenames) diff --git a/next_action/pick_action.py b/next_action/pick_action.py index 2542cfb..71646d4 100644 --- a/next_action/pick_action.py +++ b/next_action/pick_action.py @@ -6,9 +6,10 @@ from typing import Set, Sequence, Tuple from .todotxt import Task -def sort_key(task: Task) -> Tuple[str, datetime.date, datetime.date]: +def sort_key(task: Task) -> Tuple[str, datetime.date, datetime.date, int]: """ Return the sort key for a task. """ - return (task.priority() or "ZZZ", task.due_date() or datetime.date.max, task.creation_date() or datetime.date.max) + return (task.priority() or "ZZZ", task.due_date() or datetime.date.max, task.creation_date() or datetime.date.max, + -len(task.projects())) def next_actions(tasks: Sequence[Task], contexts: Set[str] = None, projects: Set[str] = None,
When picking the next action, give priority to tasks that belong to a project
fniessink/next-action
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index 0cabed3..1352148 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -65,8 +65,9 @@ class CLITest(unittest.TestCase): self.assertEqual(call("""\ usage: next-action [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...] -Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on -priority, due date, creation date, and supplied filters. +Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task +properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by +specifying contexts the tasks must have and/or projects the tasks must belong to. optional arguments: -h, --help show this help message and exit diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py index 8fec9cc..8ccd64b 100644 --- a/tests/unittests/test_pick_action.py +++ b/tests/unittests/test_pick_action.py @@ -61,6 +61,18 @@ class PickActionTest(unittest.TestCase): task2 = todotxt.Task("Task 2 due:2018-1-1") self.assertEqual([task2, task1], pick_action.next_actions([task1, task2])) + def test_project(self): + """ Test that a task with a project takes precedence over a task without a project. """ + task1 = todotxt.Task("Task 1") + task2 = todotxt.Task("Task 2 +Project") + self.assertEqual([task2, task1], pick_action.next_actions([task1, task2])) + + def test_projects(self): + """ Test that a task with more projects takes precedence over a task with less projects. """ + task1 = todotxt.Task("Task 1 +Project") + task2 = todotxt.Task("Task 2 +Project1 +Project2") + self.assertEqual([task2, task1], pick_action.next_actions([task1, task2])) + class FilterTasksTest(unittest.TestCase): """ Test that the tasks from which the next action is picked, can be filtered. """
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 4 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@59b44d490e41069dad67aea493337747864d639c#egg=next_action packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/test_cli.py::CLITest::test_help", "tests/unittests/test_pick_action.py::PickActionTest::test_project", "tests/unittests/test_pick_action.py::PickActionTest::test_projects" ]
[]
[ "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_missing_file", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_version", "tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_due_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first", "tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks", "tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks", "tests/unittests/test_pick_action.py::PickActionTest::test_one_task", "tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date", "tests/unittests/test_pick_action.py::FilterTasksTest::test_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_contexts", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_contexts", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_projects", "tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_project_and_context", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_completed_task", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_future_task", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_these_tasks" ]
[]
Apache License 2.0
2,550
[ "next_action/pick_action.py", "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
[ "next_action/pick_action.py", "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
pypa__twine-369
34c08ef97d05d219ae018f041cd37e1d409b7a4d
2018-05-19 18:01:32
c977b44cf87e066125e9de496429f8b3f5c90bf4
codecov[bot]: # [Codecov](https://codecov.io/gh/pypa/twine/pull/369?src=pr&el=h1) Report > Merging [#369](https://codecov.io/gh/pypa/twine/pull/369?src=pr&el=desc) into [master](https://codecov.io/gh/pypa/twine/commit/34c08ef97d05d219ae018f041cd37e1d409b7a4d?src=pr&el=desc) will **decrease** coverage by `0.45%`. > The diff coverage is `100%`. [![Impacted file tree graph](https://codecov.io/gh/pypa/twine/pull/369/graphs/tree.svg?width=650&token=NrvN4iFbj6&height=150&src=pr)](https://codecov.io/gh/pypa/twine/pull/369?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #369 +/- ## ========================================= - Coverage 74.55% 74.1% -0.46% ========================================= Files 13 13 Lines 672 668 -4 Branches 101 100 -1 ========================================= - Hits 501 495 -6 - Misses 143 145 +2 Partials 28 28 ``` | [Impacted Files](https://codecov.io/gh/pypa/twine/pull/369?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [twine/utils.py](https://codecov.io/gh/pypa/twine/pull/369/diff?src=pr&el=tree#diff-dHdpbmUvdXRpbHMucHk=) | `82.25% <100%> (-2.12%)` | :arrow_down: | | [twine/wininst.py](https://codecov.io/gh/pypa/twine/pull/369/diff?src=pr&el=tree#diff-dHdpbmUvd2luaW5zdC5weQ==) | `29.72% <0%> (ø)` | :arrow_up: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/pypa/twine/pull/369?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/pypa/twine/pull/369?src=pr&el=footer). Last update [34c08ef...6e1a1ea](https://codecov.io/gh/pypa/twine/pull/369?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments). anlutro: I wonder if I could remove this line and just always configure `testpypi`, regardless of `index-servers`? I left it in to stay consistent with old behaviour. https://github.com/pypa/twine/pull/369/files#diff-547bab308763f89cacec226151fcbb80R83 anlutro: docs failed in Travis - unrelated, I guess? theacodes: Yes, unrelated and up to me to fix. Can you get lint passing? anlutro: Amended, lint should pass now.
diff --git a/twine/utils.py b/twine/utils.py index d83e080..4feca1b 100644 --- a/twine/utils.py +++ b/twine/utils.py @@ -21,6 +21,7 @@ import getpass import sys import argparse import warnings +import collections from requests.exceptions import HTTPError @@ -48,68 +49,52 @@ TEST_REPOSITORY = "https://test.pypi.org/legacy/" def get_config(path="~/.pypirc"): + # even if the config file does not exist, set up the parser + # variable to reduce the number of if/else statements + parser = configparser.RawConfigParser() + + # this list will only be used if index-servers + # is not defined in the config file + index_servers = ["pypi", "testpypi"] + + # default configuration for each repository + defaults = {"username": None, "password": None} + # Expand user strings in the path path = os.path.expanduser(path) - if not os.path.isfile(path): - return {"pypi": {"repository": DEFAULT_REPOSITORY, - "username": None, - "password": None - }, - "pypitest": {"repository": TEST_REPOSITORY, - "username": None, - "password": None - }, - } - # Parse the rc file - parser = configparser.RawConfigParser() - parser.read(path) - - # Get a list of repositories from the config file - # format: https://docs.python.org/3/distutils/packageindex.html#pypirc - if (parser.has_section("distutils") and - parser.has_option("distutils", "index-servers")): - repositories = parser.get("distutils", "index-servers").split() - elif parser.has_section("pypi"): - # Special case: if the .pypirc file has a 'pypi' section, - # even if there's no list of index servers, - # be lenient and include that in our list of repositories. - repositories = ['pypi'] - else: - repositories = [] + if os.path.isfile(path): + parser.read(path) - config = {} + # Get a list of index_servers from the config file + # format: https://docs.python.org/3/distutils/packageindex.html#pypirc + if parser.has_option("distutils", "index-servers"): + index_servers = parser.get("distutils", "index-servers").split() - defaults = {"username": None, "password": None} - if parser.has_section("server-login"): for key in ["username", "password"]: if parser.has_option("server-login", key): defaults[key] = parser.get("server-login", key) - for repository in repositories: - # Skip this repository if it doesn't exist in the config file - if not parser.has_section(repository): - continue + config = collections.defaultdict(lambda: defaults.copy()) - # Mandatory configuration and defaults - config[repository] = { - "repository": DEFAULT_REPOSITORY, - "username": None, - "password": None, - } + # don't require users to manually configure URLs for these repositories + config["pypi"]["repository"] = DEFAULT_REPOSITORY + if "testpypi" in index_servers: + config["testpypi"]["repository"] = TEST_REPOSITORY - # Optional configuration values + # optional configuration values for individual repositories + for repository in index_servers: for key in [ "username", "repository", "password", "ca_cert", "client_cert", ]: if parser.has_option(repository, key): config[repository][key] = parser.get(repository, key) - elif defaults.get(key): - config[repository][key] = defaults[key] - return config + # convert the defaultdict to a regular dict at this point + # to prevent surprising behavior later on + return dict(config) def get_repository_from_config(config_file, repository, repository_url=None):
Twine should have a built-in alias for testpypi Instead of needing to specify the full upload URL for Test PyPI we should always have an alias ready, for example: ``` twine upload --repository=testpypi dist/* ``` Should work even without a `-/.pypirc`. If `testpypi` is defined in `~/.pypic`, it should take precedence.
pypa/twine
diff --git a/tests/test_utils.py b/tests/test_utils.py index 4cd45a6..4d60e04 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -72,6 +72,11 @@ def test_get_config_no_distutils(tmpdir): "username": "testuser", "password": "testpassword", }, + "testpypi": { + "repository": utils.TEST_REPOSITORY, + "username": None, + "password": None, + }, } @@ -97,6 +102,18 @@ def test_get_config_no_section(tmpdir): } +def test_get_config_override_pypi_url(tmpdir): + pypirc = os.path.join(str(tmpdir), ".pypirc") + + with open(pypirc, "w") as fp: + fp.write(textwrap.dedent(""" + [pypi] + repository = http://pypiproxy + """)) + + assert utils.get_config(pypirc)['pypi']['repository'] == 'http://pypiproxy' + + def test_get_config_missing(tmpdir): pypirc = os.path.join(str(tmpdir), ".pypirc") @@ -106,7 +123,7 @@ def test_get_config_missing(tmpdir): "username": None, "password": None, }, - "pypitest": { + "testpypi": { "repository": utils.TEST_REPOSITORY, "username": None, "password": None @@ -143,8 +160,13 @@ def test_get_config_deprecated_pypirc(): assert utils.get_config(deprecated_pypirc_path) == { "pypi": { "repository": utils.DEFAULT_REPOSITORY, - "username": 'testusername', - "password": 'testpassword', + "username": "testusername", + "password": "testpassword", + }, + "testpypi": { + "repository": utils.TEST_REPOSITORY, + "username": "testusername", + "password": "testpassword", }, }
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[keyring]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 colorama==0.4.5 cryptography==40.0.2 distlib==0.3.9 doc8==0.11.2 docutils==0.18.1 filelock==3.4.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 jeepney==0.7.1 Jinja2==3.0.3 keyring==23.4.1 MarkupSafe==2.0.1 packaging==21.3 pbr==6.1.1 pkginfo==1.10.0 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pycparser==2.21 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytz==2025.2 readme-renderer==34.0 releases==2.1.1 requests==2.27.1 requests-toolbelt==1.0.0 restructuredtext-lint==1.4.0 rfc3986==1.5.0 SecretStorage==3.3.3 semantic-version==2.6.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 stevedore==3.5.2 toml==0.10.2 tomli==1.2.3 tox==3.28.0 tqdm==4.64.1 -e git+https://github.com/pypa/twine.git@34c08ef97d05d219ae018f041cd37e1d409b7a4d#egg=twine typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 webencodings==0.5.1 zipp==3.6.0
name: twine channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cffi==1.15.1 - charset-normalizer==2.0.12 - colorama==0.4.5 - cryptography==40.0.2 - distlib==0.3.9 - doc8==0.11.2 - docutils==0.18.1 - filelock==3.4.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jeepney==0.7.1 - jinja2==3.0.3 - keyring==23.4.1 - markupsafe==2.0.1 - packaging==21.3 - pbr==6.1.1 - pkginfo==1.10.0 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycparser==2.21 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytz==2025.2 - readme-renderer==34.0 - releases==2.1.1 - requests==2.27.1 - requests-toolbelt==1.0.0 - restructuredtext-lint==1.4.0 - rfc3986==1.5.0 - secretstorage==3.3.3 - semantic-version==2.6.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - stevedore==3.5.2 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - tqdm==4.64.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/twine
[ "tests/test_utils.py::test_get_config_no_distutils", "tests/test_utils.py::test_get_config_missing", "tests/test_utils.py::test_get_config_deprecated_pypirc" ]
[]
[ "tests/test_utils.py::test_get_config", "tests/test_utils.py::test_get_config_no_section", "tests/test_utils.py::test_get_config_override_pypi_url", "tests/test_utils.py::test_get_repository_config_missing", "tests/test_utils.py::test_get_userpass_value[cli-config0-key-<lambda>-cli]", "tests/test_utils.py::test_get_userpass_value[None-config1-key-<lambda>-value]", "tests/test_utils.py::test_get_userpass_value[None-config2-key-<lambda>-fallback]", "tests/test_utils.py::test_default_to_environment_action[MY_PASSWORD-None-environ0-None]", "tests/test_utils.py::test_default_to_environment_action[MY_PASSWORD-None-environ1-foo]", "tests/test_utils.py::test_default_to_environment_action[URL-https://example.org-environ2-https://example.org]", "tests/test_utils.py::test_default_to_environment_action[URL-https://example.org-environ3-https://pypi.org]", "tests/test_utils.py::test_get_password_keyring_overrides_prompt", "tests/test_utils.py::test_get_password_keyring_defers_to_prompt", "tests/test_utils.py::test_get_password_keyring_missing_prompts", "tests/test_utils.py::test_get_password_runtime_error_suppressed", "tests/test_utils.py::test_no_positional_on_method", "tests/test_utils.py::test_no_positional_on_function" ]
[]
Apache License 2.0
2,551
[ "twine/utils.py" ]
[ "twine/utils.py" ]
python-cmd2__cmd2-409
a38e3f26887f60a358a5e36421a52526a04637f5
2018-05-19 20:12:22
8f88f819fae7508066a81a8d961a7115f2ec4bed
diff --git a/cmd2/argcomplete_bridge.py b/cmd2/argcomplete_bridge.py index a036af1e..0ac68f1c 100644 --- a/cmd2/argcomplete_bridge.py +++ b/cmd2/argcomplete_bridge.py @@ -6,11 +6,16 @@ try: import argcomplete except ImportError: # pragma: no cover # not installed, skip the rest of the file - pass - + DEFAULT_COMPLETER = None else: # argcomplete is installed + # Newer versions of argcomplete have FilesCompleter at top level, older versions only have it under completers + try: + DEFAULT_COMPLETER = argcomplete.FilesCompleter() + except AttributeError: + DEFAULT_COMPLETER = argcomplete.completers.FilesCompleter() + from contextlib import redirect_stdout import copy from io import StringIO @@ -102,7 +107,7 @@ else: def __call__(self, argument_parser, completer=None, always_complete_options=True, exit_method=os._exit, output_stream=None, exclude=None, validator=None, print_suppressed=False, append_space=None, - default_completer=argcomplete.FilesCompleter()): + default_completer=DEFAULT_COMPLETER): """ :param argument_parser: The argument parser to autocomplete on :type argument_parser: :class:`argparse.ArgumentParser` @@ -140,9 +145,14 @@ else: added to argcomplete.safe_actions, if their values are wanted in the ``parsed_args`` completer argument, or their execution is otherwise desirable. """ - self.__init__(argument_parser, always_complete_options=always_complete_options, exclude=exclude, - validator=validator, print_suppressed=print_suppressed, append_space=append_space, - default_completer=default_completer) + # Older versions of argcomplete have fewer keyword arguments + if sys.version_info >= (3, 5): + self.__init__(argument_parser, always_complete_options=always_complete_options, exclude=exclude, + validator=validator, print_suppressed=print_suppressed, append_space=append_space, + default_completer=default_completer) + else: + self.__init__(argument_parser, always_complete_options=always_complete_options, exclude=exclude, + validator=validator, print_suppressed=print_suppressed) if "_ARGCOMPLETE" not in os.environ: # not an argument completion invocation diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index a8a0f24a..1995b8d5 100755 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -472,8 +472,23 @@ class AutoCompleter(object): if action.dest in self._arg_choices: arg_choices = self._arg_choices[action.dest] - if isinstance(arg_choices, tuple) and len(arg_choices) > 0 and callable(arg_choices[0]): - completer = arg_choices[0] + # if arg_choices is a tuple + # Let's see if it's a custom completion function. If it is, return what it provides + # To do this, we make sure the first element is either a callable + # or it's the name of a callable in the application + if isinstance(arg_choices, tuple) and len(arg_choices) > 0 and \ + (callable(arg_choices[0]) or + (isinstance(arg_choices[0], str) and hasattr(self._cmd2_app, arg_choices[0]) and + callable(getattr(self._cmd2_app, arg_choices[0])) + ) + ): + + if callable(arg_choices[0]): + completer = arg_choices[0] + elif isinstance(arg_choices[0], str) and callable(getattr(self._cmd2_app, arg_choices[0])): + completer = getattr(self._cmd2_app, arg_choices[0]) + + # extract the positional and keyword arguments from the tuple list_args = None kw_args = None for index in range(1, len(arg_choices)): @@ -481,14 +496,19 @@ class AutoCompleter(object): list_args = arg_choices[index] elif isinstance(arg_choices[index], dict): kw_args = arg_choices[index] - if list_args is not None and kw_args is not None: - return completer(text, line, begidx, endidx, *list_args, **kw_args) - elif list_args is not None: - return completer(text, line, begidx, endidx, *list_args) - elif kw_args is not None: - return completer(text, line, begidx, endidx, **kw_args) - else: - return completer(text, line, begidx, endidx) + try: + # call the provided function differently depending on the provided positional and keyword arguments + if list_args is not None and kw_args is not None: + return completer(text, line, begidx, endidx, *list_args, **kw_args) + elif list_args is not None: + return completer(text, line, begidx, endidx, *list_args) + elif kw_args is not None: + return completer(text, line, begidx, endidx, **kw_args) + else: + return completer(text, line, begidx, endidx) + except TypeError: + # assume this is due to an incorrect function signature, return nothing. + return [] else: return AutoCompleter.basic_complete(text, line, begidx, endidx, self._resolve_choices_for_arg(action, used_values)) @@ -499,6 +519,16 @@ class AutoCompleter(object): if action.dest in self._arg_choices: args = self._arg_choices[action.dest] + # is the argument a string? If so, see if we can find an attribute in the + # application matching the string. + if isinstance(args, str): + try: + args = getattr(self._cmd2_app, args) + except AttributeError: + # Couldn't find anything matching the name + return [] + + # is the provided argument a callable. If so, call it if callable(args): try: if self._cmd2_app is not None: @@ -535,7 +565,10 @@ class AutoCompleter(object): prefix = '{}{}'.format(flags, param) else: - prefix = '{}'.format(str(action.dest).upper()) + if action.dest != SUPPRESS: + prefix = '{}'.format(str(action.dest).upper()) + else: + prefix = '' prefix = ' {0: <{width}} '.format(prefix, width=20) pref_len = len(prefix) diff --git a/cmd2/pyscript_bridge.py b/cmd2/pyscript_bridge.py index 277d8531..196be82b 100644 --- a/cmd2/pyscript_bridge.py +++ b/cmd2/pyscript_bridge.py @@ -230,7 +230,7 @@ class ArgparseFunctor: if action.option_strings: cmd_str[0] += '{} '.format(action.option_strings[0]) - if isinstance(value, List) or isinstance(value, Tuple): + if isinstance(value, List) or isinstance(value, tuple): for item in value: item = str(item).strip() if ' ' in item: @@ -250,7 +250,7 @@ class ArgparseFunctor: cmd_str[0] += '{} '.format(self._args[action.dest]) traverse_parser(action.choices[self._args[action.dest]]) elif isinstance(action, argparse._AppendAction): - if isinstance(self._args[action.dest], List) or isinstance(self._args[action.dest], Tuple): + if isinstance(self._args[action.dest], list) or isinstance(self._args[action.dest], tuple): for values in self._args[action.dest]: process_flag(action, values) else: diff --git a/examples/tab_autocompletion.py b/examples/tab_autocompletion.py index f3302533..adfe9702 100755 --- a/examples/tab_autocompletion.py +++ b/examples/tab_autocompletion.py @@ -96,6 +96,15 @@ class TabCompleteExample(cmd2.Cmd): }, } + file_list = \ + [ + '/home/user/file.db', + '/home/user/file space.db', + '/home/user/another.db', + '/home/other user/maps.db', + '/home/other user/tests.db' + ] + def instance_query_actors(self) -> List[str]: """Simulating a function that queries and returns a completion values""" return actors @@ -225,9 +234,23 @@ class TabCompleteExample(cmd2.Cmd): required=True) actor_action = vid_movies_add_parser.add_argument('actor', help='Actors', nargs='*') + vid_movies_load_parser = vid_movies_commands_subparsers.add_parser('load') + vid_movie_file_action = vid_movies_load_parser.add_argument('movie_file', help='Movie database') + + vid_movies_read_parser = vid_movies_commands_subparsers.add_parser('read') + vid_movie_fread_action = vid_movies_read_parser.add_argument('movie_file', help='Movie database') + # tag the action objects with completion providers. This can be a collection or a callable setattr(director_action, argparse_completer.ACTION_ARG_CHOICES, static_list_directors) - setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, instance_query_actors) + setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, 'instance_query_actors') + + # tag the file property with a custom completion function 'delimeter_complete' provided by cmd2. + setattr(vid_movie_file_action, argparse_completer.ACTION_ARG_CHOICES, + ('delimiter_complete', + {'delimiter': '/', + 'match_against': file_list})) + setattr(vid_movie_fread_action, argparse_completer.ACTION_ARG_CHOICES, + ('path_complete', [False, False])) vid_movies_delete_parser = vid_movies_commands_subparsers.add_parser('delete') @@ -306,6 +329,9 @@ class TabCompleteExample(cmd2.Cmd): movies_delete_parser = movies_commands_subparsers.add_parser('delete') + movies_load_parser = movies_commands_subparsers.add_parser('load') + movie_file_action = movies_load_parser.add_argument('movie_file', help='Movie database') + shows_parser = media_types_subparsers.add_parser('shows') shows_parser.set_defaults(func=_do_media_shows) @@ -333,7 +359,8 @@ class TabCompleteExample(cmd2.Cmd): def complete_media(self, text, line, begidx, endidx): """ Adds tab completion to media""" choices = {'actor': query_actors, # function - 'director': TabCompleteExample.static_list_directors # static list + 'director': TabCompleteExample.static_list_directors, # static list + 'movie_file': (self.path_complete, [False, False]) } completer = argparse_completer.AutoCompleter(TabCompleteExample.media_parser, arg_choices=choices)
Autocompleter - type invalid text for a subcommand and press tab and ==SUPPRESS== is displayed. Type invalid text for a subcommand and press tab and ==SUPPRESS== is displayed. If the text typed doesn't match anything in the subcommand list for a command, autocompleter attempts to print the Hint for the parameter. For a subcommand that comes out as == SUPPRESS ==.
python-cmd2/cmd2
diff --git a/tests/test_autocompletion.py b/tests/test_autocompletion.py index 1d0c9678..e0a71831 100644 --- a/tests/test_autocompletion.py +++ b/tests/test_autocompletion.py @@ -168,7 +168,7 @@ def test_autocomp_subcmd_nested(cmd2_app): first_match = complete_tester(text, line, begidx, endidx, cmd2_app) assert first_match is not None and \ - cmd2_app.completion_matches == ['add', 'delete', 'list'] + cmd2_app.completion_matches == ['add', 'delete', 'list', 'load'] def test_autocomp_subcmd_flag_choices_append(cmd2_app): @@ -246,7 +246,7 @@ def test_autcomp_pos_consumed(cmd2_app): def test_autcomp_pos_after_flag(cmd2_app): text = 'Joh' - line = 'media movies add -d "George Lucas" -- "Han Solo" PG "Emilia Clarke" "{}'.format(text) + line = 'video movies add -d "George Lucas" -- "Han Solo" PG "Emilia Clarke" "{}'.format(text) endidx = len(line) begidx = endidx - len(text) diff --git a/tests/test_bashcompletion.py b/tests/test_bashcompletion.py index ceae2aa9..298bdf1e 100644 --- a/tests/test_bashcompletion.py +++ b/tests/test_bashcompletion.py @@ -139,15 +139,13 @@ def test_invalid_ifs(parser1, mock): @pytest.mark.parametrize('comp_line, exp_out, exp_err', [ ('media ', 'movies\013shows', ''), ('media mo', 'movies', ''), + ('media movies list -a "J', '"John Boyega"\013"Jake Lloyd"', ''), + ('media movies list ', '', ''), ('media movies add ', '\013\013 ', ''' Hint: TITLE Movie Title'''), - ('media movies list -a "J', '"John Boyega"\013"Jake Lloyd"', ''), - ('media movies list ', '', '') ]) def test_commands(parser1, capfd, mock, comp_line, exp_out, exp_err): - completer = CompletionFinder() - mock.patch.dict(os.environ, {'_ARGCOMPLETE': '1', '_ARGCOMPLETE_IFS': '\013', 'COMP_TYPE': '63', @@ -157,6 +155,8 @@ def test_commands(parser1, capfd, mock, comp_line, exp_out, exp_err): mock.patch.object(os, 'fdopen', my_fdopen) with pytest.raises(SystemExit): + completer = CompletionFinder() + choices = {'actor': query_actors, # function } autocompleter = AutoCompleter(parser1, arg_choices=choices)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 4 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-mock pytest-xdist", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/python-cmd2/cmd2.git@a38e3f26887f60a358a5e36421a52526a04637f5#egg=cmd2 colorama==0.4.6 coverage==7.8.0 exceptiongroup==1.2.2 execnet==2.1.1 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pyperclip==1.9.0 pytest==8.3.5 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 tomli==2.2.1 wcwidth==0.2.13
name: cmd2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - colorama==0.4.6 - coverage==7.8.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pyperclip==1.9.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - tomli==2.2.1 - wcwidth==0.2.13 prefix: /opt/conda/envs/cmd2
[ "tests/test_autocompletion.py::test_autocomp_subcmd_nested" ]
[]
[ "tests/test_autocompletion.py::test_help_required_group", "tests/test_autocompletion.py::test_help_required_group_long", "tests/test_autocompletion.py::test_autocomp_flags", "tests/test_autocompletion.py::test_autcomp_hint", "tests/test_autocompletion.py::test_autcomp_flag_comp", "tests/test_autocompletion.py::test_autocomp_flags_choices", "tests/test_autocompletion.py::test_autcomp_hint_in_narg_range", "tests/test_autocompletion.py::test_autocomp_flags_narg_max", "tests/test_autocompletion.py::test_autcomp_narg_beyond_max", "tests/test_autocompletion.py::test_autocomp_subcmd_flag_choices_append", "tests/test_autocompletion.py::test_autocomp_subcmd_flag_choices_append_exclude", "tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_func", "tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_list", "tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_func_attr", "tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_list_attr", "tests/test_autocompletion.py::test_autcomp_pos_consumed", "tests/test_autocompletion.py::test_autcomp_pos_after_flag", "tests/test_autocompletion.py::test_autcomp_custom_func_list_arg", "tests/test_autocompletion.py::test_autcomp_custom_func_list_and_dict_arg" ]
[]
MIT License
2,552
[ "cmd2/pyscript_bridge.py", "cmd2/argcomplete_bridge.py", "examples/tab_autocompletion.py", "cmd2/argparse_completer.py" ]
[ "cmd2/pyscript_bridge.py", "cmd2/argcomplete_bridge.py", "examples/tab_autocompletion.py", "cmd2/argparse_completer.py" ]
tornadoweb__tornado-2393
eb487cac3d829292ecca6e5124b1da5ae6bba407
2018-05-19 23:59:17
6410cd98c1a5e938246a17cac0769f689ed471c5
diff --git a/tornado/autoreload.py b/tornado/autoreload.py index 2f911270..7d69474a 100644 --- a/tornado/autoreload.py +++ b/tornado/autoreload.py @@ -107,6 +107,9 @@ _watched_files = set() _reload_hooks = [] _reload_attempted = False _io_loops = weakref.WeakKeyDictionary() # type: ignore +_autoreload_is_main = False +_original_argv = None +_original_spec = None def start(check_time=500): @@ -214,11 +217,15 @@ def _reload(): # __spec__ is not available (Python < 3.4), check instead if # sys.path[0] is an empty string and add the current directory to # $PYTHONPATH. - spec = getattr(sys.modules['__main__'], '__spec__', None) - if spec: - argv = ['-m', spec.name] + sys.argv[1:] + if _autoreload_is_main: + spec = _original_spec + argv = _original_argv else: + spec = getattr(sys.modules['__main__'], '__spec__', None) argv = sys.argv + if spec: + argv = ['-m', spec.name] + argv[1:] + else: path_prefix = '.' + os.pathsep if (sys.path[0] == '' and not os.environ.get("PYTHONPATH", "").startswith(path_prefix)): @@ -226,7 +233,7 @@ def _reload(): os.environ.get("PYTHONPATH", "")) if not _has_execv: subprocess.Popen([sys.executable] + argv) - sys.exit(0) + os._exit(0) else: try: os.execv(sys.executable, [sys.executable] + argv) @@ -269,7 +276,17 @@ def main(): can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`. """ + # Remember that we were launched with autoreload as main. + # The main module can be tricky; set the variables both in our globals + # (which may be __main__) and the real importable version. + import tornado.autoreload + global _autoreload_is_main + global _original_argv, _original_spec + tornado.autoreload._autoreload_is_main = _autoreload_is_main = True original_argv = sys.argv + tornado.autoreload._original_argv = _original_argv = original_argv + original_spec = getattr(sys.modules['__main__'], '__spec__', None) + tornado.autoreload._original_spec = _original_spec = original_spec sys.argv = sys.argv[:] if len(sys.argv) >= 3 and sys.argv[1] == "-m": mode = "module" diff --git a/tornado/iostream.py b/tornado/iostream.py index 89e1e234..63110a1a 100644 --- a/tornado/iostream.py +++ b/tornado/iostream.py @@ -1410,13 +1410,7 @@ class IOStream(BaseIOStream): return future def _handle_connect(self): - try: - err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) - except socket.error as e: - # Hurd doesn't allow SO_ERROR for loopback sockets because all - # errors for such sockets are reported synchronously. - if errno_from_exception(e) == errno.ENOPROTOOPT: - err = 0 + err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: self.error = socket.error(err, os.strerror(err)) # IOLoop implementations may vary: some of them return diff --git a/tornado/netutil.py b/tornado/netutil.py index e63683ad..08c9d886 100644 --- a/tornado/netutil.py +++ b/tornado/netutil.py @@ -138,12 +138,7 @@ def bind_sockets(port, address=None, family=socket.AF_UNSPEC, raise set_close_exec(sock.fileno()) if os.name != 'nt': - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - except socket.error as e: - if errno_from_exception(e) != errno.ENOPROTOOPT: - # Hurd doesn't support SO_REUSEADDR. - raise + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if reuse_port: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) if af == socket.AF_INET6: @@ -185,12 +180,7 @@ if hasattr(socket, 'AF_UNIX'): """ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) set_close_exec(sock.fileno()) - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - except socket.error as e: - if errno_from_exception(e) != errno.ENOPROTOOPT: - # Hurd doesn't support SO_REUSEADDR - raise + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: st = os.stat(file) diff --git a/tornado/web.py b/tornado/web.py index 6760b0b9..f970bd13 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -749,18 +749,7 @@ class RequestHandler(object): self._write_buffer.append(chunk) def render(self, template_name, **kwargs): - """Renders the template with the given arguments as the response. - - ``render()`` calls ``finish()``, so no other output methods can be called - after it. - - Returns a `.Future` with the same semantics as the one returned by `finish`. - Awaiting this `.Future` is optional. - - .. versionchanged:: 5.1 - - Now returns a `.Future` instead of ``None``. - """ + """Renders the template with the given arguments as the response.""" if self._finished: raise RuntimeError("Cannot render() after finish()") html = self.render_string(template_name, **kwargs) @@ -821,7 +810,7 @@ class RequestHandler(object): if html_bodies: hloc = html.index(b'</body>') html = html[:hloc] + b''.join(html_bodies) + b'\n' + html[hloc:] - return self.finish(html) + self.finish(html) def render_linked_js(self, js_files): """Default method used to render the final js links for the @@ -1004,20 +993,7 @@ class RequestHandler(object): return future def finish(self, chunk=None): - """Finishes this response, ending the HTTP request. - - Passing a ``chunk`` to ``finish()`` is equivalent to passing that - chunk to ``write()`` and then calling ``finish()`` with no arguments. - - Returns a `.Future` which may optionally be awaited to track the sending - of the response to the client. This `.Future` resolves when all the response - data has been sent, and raises an error if the connection is closed before all - data can be sent. - - .. versionchanged:: 5.1 - - Now returns a `.Future` instead of ``None``. - """ + """Finishes this response, ending the HTTP request.""" if self._finished: raise RuntimeError("finish() called twice") @@ -1049,13 +1025,12 @@ class RequestHandler(object): # are keepalive connections) self.request.connection.set_close_callback(None) - future = self.flush(include_footers=True) + self.flush(include_footers=True) self.request.connection.finish() self._log() self._finished = True self.on_finish() self._break_cycles() - return future def detach(self): """Take control of the underlying stream.
autoreload: Fix argv preservation `autoreload` currently has a wrapper mode (e.g. `python -m tornado.autoreload -m tornado.test`) for scripts, and an in-process mode (enabled by `Application(..., debug=True)`). It's useful to combine these, since the wrapper can catch syntax errors that cause the process to abort before entering its IOLoop. However, this doesn't work as well as it should, because the `main` wrapper only restores `sys.argv` if the process exits, meaning the `-m tornado.autoreload` flags are lost if the inner autoreload fires. The original argv needs to be stored in a global when `autoreload` is `__main__`, so that it can be used in `_reload()`.
tornadoweb/tornado
diff --git a/tornado/test/autoreload_test.py b/tornado/test/autoreload_test.py index 6a9729db..1ea53167 100644 --- a/tornado/test/autoreload_test.py +++ b/tornado/test/autoreload_test.py @@ -1,14 +1,19 @@ from __future__ import absolute_import, division, print_function import os +import shutil import subprocess from subprocess import Popen import sys from tempfile import mkdtemp +import time from tornado.test.util import unittest -MAIN = """\ +class AutoreloadTest(unittest.TestCase): + + def test_reload_module(self): + main = """\ import os import sys @@ -24,15 +29,13 @@ if 'TESTAPP_STARTED' not in os.environ: autoreload._reload() """ - -class AutoreloadTest(unittest.TestCase): - def test_reload_module(self): # Create temporary test application path = mkdtemp() + self.addCleanup(shutil.rmtree, path) os.mkdir(os.path.join(path, 'testapp')) open(os.path.join(path, 'testapp/__init__.py'), 'w').close() with open(os.path.join(path, 'testapp/__main__.py'), 'w') as f: - f.write(MAIN) + f.write(main) # Make sure the tornado module under test is available to the test # application @@ -46,3 +49,64 @@ class AutoreloadTest(unittest.TestCase): universal_newlines=True) out = p.communicate()[0] self.assertEqual(out, 'Starting\nStarting\n') + + def test_reload_wrapper_preservation(self): + # This test verifies that when `python -m tornado.autoreload` + # is used on an application that also has an internal + # autoreload, the reload wrapper is preserved on restart. + main = """\ +import os +import sys + +# This import will fail if path is not set up correctly +import testapp + +if 'tornado.autoreload' not in sys.modules: + raise Exception('started without autoreload wrapper') + +import tornado.autoreload + +print('Starting') +sys.stdout.flush() +if 'TESTAPP_STARTED' not in os.environ: + os.environ['TESTAPP_STARTED'] = '1' + # Simulate an internal autoreload (one not caused + # by the wrapper). + tornado.autoreload._reload() +else: + # Exit directly so autoreload doesn't catch it. + os._exit(0) +""" + + # Create temporary test application + path = mkdtemp() + os.mkdir(os.path.join(path, 'testapp')) + self.addCleanup(shutil.rmtree, path) + init_file = os.path.join(path, 'testapp', '__init__.py') + open(init_file, 'w').close() + main_file = os.path.join(path, 'testapp', '__main__.py') + with open(main_file, 'w') as f: + f.write(main) + + # Make sure the tornado module under test is available to the test + # application + pythonpath = os.getcwd() + if 'PYTHONPATH' in os.environ: + pythonpath += os.pathsep + os.environ['PYTHONPATH'] + + autoreload_proc = Popen( + [sys.executable, '-m', 'tornado.autoreload', '-m', 'testapp'], + stdout=subprocess.PIPE, cwd=path, + env=dict(os.environ, PYTHONPATH=pythonpath), + universal_newlines=True) + + for i in range(20): + if autoreload_proc.poll() is not None: + break + time.sleep(0.1) + else: + autoreload_proc.kill() + raise Exception("subprocess failed to terminate") + + out = autoreload_proc.communicate()[0] + self.assertEqual(out, 'Starting\n' * 2) diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py index b77311df..45072aac 100644 --- a/tornado/test/web_test.py +++ b/tornado/test/web_test.py @@ -191,40 +191,6 @@ class SecureCookieV2Test(unittest.TestCase): self.assertEqual(new_handler.get_secure_cookie('foo'), None) -class FinalReturnTest(WebTestCase): - def get_handlers(self): - test = self - - class FinishHandler(RequestHandler): - @gen.coroutine - def get(self): - test.final_return = self.finish() - - class RenderHandler(RequestHandler): - def create_template_loader(self, path): - return DictLoader({'foo.html': 'hi'}) - - @gen.coroutine - def get(self): - test.final_return = self.render('foo.html') - - return [("/finish", FinishHandler), - ("/render", RenderHandler)] - - def get_app_kwargs(self): - return dict(template_path='FinalReturnTest') - - def test_finish_method_return_future(self): - response = self.fetch(self.get_url('/finish')) - self.assertEqual(response.code, 200) - self.assertIsInstance(self.final_return, Future) - - def test_render_method_return_future(self): - response = self.fetch(self.get_url('/render')) - self.assertEqual(response.code, 200) - self.assertIsInstance(self.final_return, Future) - - class CookieTest(WebTestCase): def get_handlers(self): class SetCookieHandler(RequestHandler):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 4 }
5.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 flake8==5.0.4 importlib-metadata==4.2.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pycodestyle==2.9.1 pyflakes==2.5.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work -e git+https://github.com/tornadoweb/tornado.git@eb487cac3d829292ecca6e5124b1da5ae6bba407#egg=tornado typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: tornado channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - flake8==5.0.4 - importlib-metadata==4.2.0 - mccabe==0.7.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 prefix: /opt/conda/envs/tornado
[ "tornado/test/autoreload_test.py::AutoreloadTest::test_reload_wrapper_preservation" ]
[]
[ "tornado/test/autoreload_test.py::AutoreloadTest::test_reload_module", "tornado/test/web_test.py::SecureCookieV1Test::test_arbitrary_bytes", "tornado/test/web_test.py::SecureCookieV1Test::test_cookie_tampering_future_timestamp", "tornado/test/web_test.py::SecureCookieV1Test::test_round_trip", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_increment_version", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_invalidate_version", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_roundtrip", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_roundtrip_differing_version", "tornado/test/web_test.py::SecureCookieV2Test::test_round_trip", "tornado/test/web_test.py::CookieTest::test_cookie_special_char", "tornado/test/web_test.py::CookieTest::test_get_cookie", "tornado/test/web_test.py::CookieTest::test_set_cookie", "tornado/test/web_test.py::CookieTest::test_set_cookie_domain", "tornado/test/web_test.py::CookieTest::test_set_cookie_expires_days", "tornado/test/web_test.py::CookieTest::test_set_cookie_false_flags", "tornado/test/web_test.py::CookieTest::test_set_cookie_max_age", "tornado/test/web_test.py::CookieTest::test_set_cookie_overwrite", "tornado/test/web_test.py::AuthRedirectTest::test_absolute_auth_redirect", "tornado/test/web_test.py::AuthRedirectTest::test_relative_auth_redirect", "tornado/test/web_test.py::ConnectionCloseTest::test_connection_close", "tornado/test/web_test.py::RequestEncodingTest::test_error", "tornado/test/web_test.py::RequestEncodingTest::test_group_encoding", "tornado/test/web_test.py::RequestEncodingTest::test_group_question_mark", "tornado/test/web_test.py::RequestEncodingTest::test_slashes", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument_invalid_unicode", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument_plus", "tornado/test/web_test.py::WSGISafeWebTest::test_get_argument", "tornado/test/web_test.py::WSGISafeWebTest::test_get_body_arguments", "tornado/test/web_test.py::WSGISafeWebTest::test_get_query_arguments", "tornado/test/web_test.py::WSGISafeWebTest::test_header_injection", "tornado/test/web_test.py::WSGISafeWebTest::test_multi_header", "tornado/test/web_test.py::WSGISafeWebTest::test_no_gzip", "tornado/test/web_test.py::WSGISafeWebTest::test_optional_path", "tornado/test/web_test.py::WSGISafeWebTest::test_redirect", "tornado/test/web_test.py::WSGISafeWebTest::test_reverse_url", "tornado/test/web_test.py::WSGISafeWebTest::test_types", "tornado/test/web_test.py::WSGISafeWebTest::test_uimodule_resources", "tornado/test/web_test.py::WSGISafeWebTest::test_uimodule_unescaped", "tornado/test/web_test.py::WSGISafeWebTest::test_web_redirect", "tornado/test/web_test.py::WSGISafeWebTest::test_web_redirect_double_slash", "tornado/test/web_test.py::NonWSGIWebTests::test_empty_flush", "tornado/test/web_test.py::NonWSGIWebTests::test_flow_control", "tornado/test/web_test.py::ErrorResponseTest::test_default", "tornado/test/web_test.py::ErrorResponseTest::test_failed_write_error", "tornado/test/web_test.py::ErrorResponseTest::test_write_error", "tornado/test/web_test.py::StaticFileTest::test_absolute_static_url", "tornado/test/web_test.py::StaticFileTest::test_absolute_version_exclusion", "tornado/test/web_test.py::StaticFileTest::test_include_host_override", "tornado/test/web_test.py::StaticFileTest::test_path_traversal_protection", "tornado/test/web_test.py::StaticFileTest::test_relative_version_exclusion", "tornado/test/web_test.py::StaticFileTest::test_root_static_path", "tornado/test/web_test.py::StaticFileTest::test_static_304_etag_modified_bug", "tornado/test/web_test.py::StaticFileTest::test_static_304_if_modified_since", "tornado/test/web_test.py::StaticFileTest::test_static_304_if_none_match", "tornado/test/web_test.py::StaticFileTest::test_static_404", "tornado/test/web_test.py::StaticFileTest::test_static_compressed_files", "tornado/test/web_test.py::StaticFileTest::test_static_etag", "tornado/test/web_test.py::StaticFileTest::test_static_files", "tornado/test/web_test.py::StaticFileTest::test_static_head", "tornado/test/web_test.py::StaticFileTest::test_static_head_range", "tornado/test/web_test.py::StaticFileTest::test_static_if_modified_since_pre_epoch", "tornado/test/web_test.py::StaticFileTest::test_static_if_modified_since_time_zone", "tornado/test/web_test.py::StaticFileTest::test_static_invalid_range", "tornado/test/web_test.py::StaticFileTest::test_static_range_if_none_match", "tornado/test/web_test.py::StaticFileTest::test_static_unsatisfiable_range_invalid_start", "tornado/test/web_test.py::StaticFileTest::test_static_unsatisfiable_range_zero_suffix", "tornado/test/web_test.py::StaticFileTest::test_static_url", "tornado/test/web_test.py::StaticFileTest::test_static_with_range", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_end_edge", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_full_file", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_full_past_end", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_neg_end", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_partial_past_end", "tornado/test/web_test.py::StaticDefaultFilenameTest::test_static_default_filename", "tornado/test/web_test.py::StaticDefaultFilenameTest::test_static_default_redirect", "tornado/test/web_test.py::StaticFileWithPathTest::test_serve", "tornado/test/web_test.py::CustomStaticFileTest::test_serve", "tornado/test/web_test.py::CustomStaticFileTest::test_static_url", "tornado/test/web_test.py::HostMatchingTest::test_host_matching", "tornado/test/web_test.py::DefaultHostMatchingTest::test_default_host_matching", "tornado/test/web_test.py::NamedURLSpecGroupsTest::test_named_urlspec_groups", "tornado/test/web_test.py::ClearHeaderTest::test_clear_header", "tornado/test/web_test.py::Header204Test::test_204_headers", "tornado/test/web_test.py::Header304Test::test_304_headers", "tornado/test/web_test.py::StatusReasonTest::test_status", "tornado/test/web_test.py::DateHeaderTest::test_date_header", "tornado/test/web_test.py::RaiseWithReasonTest::test_httperror_str", "tornado/test/web_test.py::RaiseWithReasonTest::test_httperror_str_from_httputil", "tornado/test/web_test.py::RaiseWithReasonTest::test_raise_with_reason", "tornado/test/web_test.py::ErrorHandlerXSRFTest::test_404_xsrf", "tornado/test/web_test.py::ErrorHandlerXSRFTest::test_error_xsrf", "tornado/test/web_test.py::GzipTestCase::test_gzip", "tornado/test/web_test.py::GzipTestCase::test_gzip_not_requested", "tornado/test/web_test.py::GzipTestCase::test_gzip_static", "tornado/test/web_test.py::GzipTestCase::test_vary_already_present", "tornado/test/web_test.py::GzipTestCase::test_vary_already_present_multiple", "tornado/test/web_test.py::PathArgsInPrepareTest::test_kw", "tornado/test/web_test.py::PathArgsInPrepareTest::test_pos", "tornado/test/web_test.py::ClearAllCookiesTest::test_clear_all_cookies", "tornado/test/web_test.py::ExceptionHandlerTest::test_http_error", "tornado/test/web_test.py::ExceptionHandlerTest::test_known_error", "tornado/test/web_test.py::ExceptionHandlerTest::test_unknown_error", "tornado/test/web_test.py::BuggyLoggingTest::test_buggy_log_exception", "tornado/test/web_test.py::UIMethodUIModuleTest::test_ui_method", "tornado/test/web_test.py::GetArgumentErrorTest::test_catch_error", "tornado/test/web_test.py::MultipleExceptionTest::test_multi_exception", "tornado/test/web_test.py::SetLazyPropertiesTest::test_set_properties", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_from_ui_module_is_lazy", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_from_ui_module_works", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_works", "tornado/test/web_test.py::UnimplementedHTTPMethodsTest::test_unimplemented_standard_methods", "tornado/test/web_test.py::UnimplementedNonStandardMethodsTest::test_unimplemented_other", "tornado/test/web_test.py::UnimplementedNonStandardMethodsTest::test_unimplemented_patch", "tornado/test/web_test.py::AllHTTPMethodsTest::test_standard_methods", "tornado/test/web_test.py::PatchMethodTest::test_other", "tornado/test/web_test.py::PatchMethodTest::test_patch", "tornado/test/web_test.py::FinishInPrepareTest::test_finish_in_prepare", "tornado/test/web_test.py::Default404Test::test_404", "tornado/test/web_test.py::Custom404Test::test_404", "tornado/test/web_test.py::DefaultHandlerArgumentsTest::test_403", "tornado/test/web_test.py::HandlerByNameTest::test_handler_by_name", "tornado/test/web_test.py::StreamingRequestBodyTest::test_close_during_upload", "tornado/test/web_test.py::StreamingRequestBodyTest::test_early_return", "tornado/test/web_test.py::StreamingRequestBodyTest::test_early_return_with_data", "tornado/test/web_test.py::StreamingRequestBodyTest::test_streaming_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_chunked_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_compressed_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_fixed_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_chunked_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_compressed_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_fixed_body", "tornado/test/web_test.py::IncorrectContentLengthTest::test_content_length_too_high", "tornado/test/web_test.py::IncorrectContentLengthTest::test_content_length_too_low", "tornado/test/web_test.py::ClientCloseTest::test_client_close", "tornado/test/web_test.py::SignedValueTest::test_expired", "tornado/test/web_test.py::SignedValueTest::test_key_version_retrieval", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_invalid_key", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_read_write_default_key", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_read_write_non_default_key", "tornado/test/web_test.py::SignedValueTest::test_known_values", "tornado/test/web_test.py::SignedValueTest::test_name_swap", "tornado/test/web_test.py::SignedValueTest::test_non_ascii", "tornado/test/web_test.py::SignedValueTest::test_payload_tampering", "tornado/test/web_test.py::SignedValueTest::test_signature_tampering", "tornado/test/web_test.py::XSRFTest::test_cross_user", "tornado/test/web_test.py::XSRFTest::test_distinct_tokens", "tornado/test/web_test.py::XSRFTest::test_refresh_token", "tornado/test/web_test.py::XSRFTest::test_versioning", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_argument_invalid_format", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_body_no_cookie", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_cookie_invalid_format", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_cookie_no_body", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_no_token", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_header", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_non_hex_token", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_post_body", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_query_string", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_short_token", "tornado/test/web_test.py::XSRFCookieKwargsTest::test_xsrf_httponly", "tornado/test/web_test.py::FinishExceptionTest::test_finish_exception", "tornado/test/web_test.py::DecoratorTest::test_addslash", "tornado/test/web_test.py::DecoratorTest::test_removeslash", "tornado/test/web_test.py::CacheTest::test_multiple_strong_etag_match", "tornado/test/web_test.py::CacheTest::test_multiple_strong_etag_not_match", "tornado/test/web_test.py::CacheTest::test_multiple_weak_etag_match", "tornado/test/web_test.py::CacheTest::test_multiple_weak_etag_not_match", "tornado/test/web_test.py::CacheTest::test_strong_etag_match", "tornado/test/web_test.py::CacheTest::test_strong_etag_not_match", "tornado/test/web_test.py::CacheTest::test_weak_etag_match", "tornado/test/web_test.py::CacheTest::test_weak_etag_not_match", "tornado/test/web_test.py::CacheTest::test_wildcard_etag", "tornado/test/web_test.py::RequestSummaryTest::test_missing_remote_ip", "tornado/test/web_test.py::HTTPErrorTest::test_copy", "tornado/test/web_test.py::ApplicationTest::test_listen", "tornado/test/web_test.py::URLSpecReverseTest::test_non_reversible", "tornado/test/web_test.py::URLSpecReverseTest::test_reverse", "tornado/test/web_test.py::URLSpecReverseTest::test_reverse_arguments", "tornado/test/web_test.py::RedirectHandlerTest::test_basic_redirect", "tornado/test/web_test.py::RedirectHandlerTest::test_redirect_pattern", "tornado/test/web_test.py::RedirectHandlerTest::test_redirect_with_appending_argument", "tornado/test/web_test.py::RedirectHandlerTest::test_redirect_with_argument" ]
[]
Apache License 2.0
2,553
[ "tornado/autoreload.py", "tornado/web.py", "tornado/iostream.py", "tornado/netutil.py" ]
[ "tornado/autoreload.py", "tornado/web.py", "tornado/iostream.py", "tornado/netutil.py" ]
tornadoweb__tornado-2394
50800f37b72c7a401cd49c948cb5be85cabbafea
2018-05-20 00:48:24
6410cd98c1a5e938246a17cac0769f689ed471c5
diff --git a/tornado/iostream.py b/tornado/iostream.py index 89e1e234..63110a1a 100644 --- a/tornado/iostream.py +++ b/tornado/iostream.py @@ -1410,13 +1410,7 @@ class IOStream(BaseIOStream): return future def _handle_connect(self): - try: - err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) - except socket.error as e: - # Hurd doesn't allow SO_ERROR for loopback sockets because all - # errors for such sockets are reported synchronously. - if errno_from_exception(e) == errno.ENOPROTOOPT: - err = 0 + err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: self.error = socket.error(err, os.strerror(err)) # IOLoop implementations may vary: some of them return diff --git a/tornado/netutil.py b/tornado/netutil.py index e63683ad..08c9d886 100644 --- a/tornado/netutil.py +++ b/tornado/netutil.py @@ -138,12 +138,7 @@ def bind_sockets(port, address=None, family=socket.AF_UNSPEC, raise set_close_exec(sock.fileno()) if os.name != 'nt': - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - except socket.error as e: - if errno_from_exception(e) != errno.ENOPROTOOPT: - # Hurd doesn't support SO_REUSEADDR. - raise + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if reuse_port: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) if af == socket.AF_INET6: @@ -185,12 +180,7 @@ if hasattr(socket, 'AF_UNIX'): """ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) set_close_exec(sock.fileno()) - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - except socket.error as e: - if errno_from_exception(e) != errno.ENOPROTOOPT: - # Hurd doesn't support SO_REUSEADDR - raise + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: st = os.stat(file) diff --git a/tornado/web.py b/tornado/web.py index f970bd13..6760b0b9 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -749,7 +749,18 @@ class RequestHandler(object): self._write_buffer.append(chunk) def render(self, template_name, **kwargs): - """Renders the template with the given arguments as the response.""" + """Renders the template with the given arguments as the response. + + ``render()`` calls ``finish()``, so no other output methods can be called + after it. + + Returns a `.Future` with the same semantics as the one returned by `finish`. + Awaiting this `.Future` is optional. + + .. versionchanged:: 5.1 + + Now returns a `.Future` instead of ``None``. + """ if self._finished: raise RuntimeError("Cannot render() after finish()") html = self.render_string(template_name, **kwargs) @@ -810,7 +821,7 @@ class RequestHandler(object): if html_bodies: hloc = html.index(b'</body>') html = html[:hloc] + b''.join(html_bodies) + b'\n' + html[hloc:] - self.finish(html) + return self.finish(html) def render_linked_js(self, js_files): """Default method used to render the final js links for the @@ -993,7 +1004,20 @@ class RequestHandler(object): return future def finish(self, chunk=None): - """Finishes this response, ending the HTTP request.""" + """Finishes this response, ending the HTTP request. + + Passing a ``chunk`` to ``finish()`` is equivalent to passing that + chunk to ``write()`` and then calling ``finish()`` with no arguments. + + Returns a `.Future` which may optionally be awaited to track the sending + of the response to the client. This `.Future` resolves when all the response + data has been sent, and raises an error if the connection is closed before all + data can be sent. + + .. versionchanged:: 5.1 + + Now returns a `.Future` instead of ``None``. + """ if self._finished: raise RuntimeError("finish() called twice") @@ -1025,12 +1049,13 @@ class RequestHandler(object): # are keepalive connections) self.request.connection.set_close_callback(None) - self.flush(include_footers=True) + future = self.flush(include_footers=True) self.request.connection.finish() self._log() self._finished = True self.on_finish() self._break_cycles() + return future def detach(self): """Take control of the underlying stream.
RequestHandler.finish should return a Future `RequestHandler.finish` may call `flush()`, which returns a Future, but this Future is simply discarded. The main reason for that Future is flow control in streaming responses, which is no longer relevant by the time we are closing the connection, but it also contains errors if the stream is closed while the response is streamed. This error will be logged as a stack trace if left uncaught, so some applications may wish to await their calls to `finish()` to be able to catch it. This logic also extends to `render()`, which calls `finish()`. From https://github.com/tornadoweb/tornado/issues/2055#issuecomment-304456147
tornadoweb/tornado
diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py index 45072aac..b77311df 100644 --- a/tornado/test/web_test.py +++ b/tornado/test/web_test.py @@ -191,6 +191,40 @@ class SecureCookieV2Test(unittest.TestCase): self.assertEqual(new_handler.get_secure_cookie('foo'), None) +class FinalReturnTest(WebTestCase): + def get_handlers(self): + test = self + + class FinishHandler(RequestHandler): + @gen.coroutine + def get(self): + test.final_return = self.finish() + + class RenderHandler(RequestHandler): + def create_template_loader(self, path): + return DictLoader({'foo.html': 'hi'}) + + @gen.coroutine + def get(self): + test.final_return = self.render('foo.html') + + return [("/finish", FinishHandler), + ("/render", RenderHandler)] + + def get_app_kwargs(self): + return dict(template_path='FinalReturnTest') + + def test_finish_method_return_future(self): + response = self.fetch(self.get_url('/finish')) + self.assertEqual(response.code, 200) + self.assertIsInstance(self.final_return, Future) + + def test_render_method_return_future(self): + response = self.fetch(self.get_url('/render')) + self.assertEqual(response.code, 200) + self.assertIsInstance(self.final_return, Future) + + class CookieTest(WebTestCase): def get_handlers(self): class SetCookieHandler(RequestHandler):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 3 }
5.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 flake8==5.0.4 importlib-metadata==4.2.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pycodestyle==2.9.1 pyflakes==2.5.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work -e git+https://github.com/tornadoweb/tornado.git@50800f37b72c7a401cd49c948cb5be85cabbafea#egg=tornado typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: tornado channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - flake8==5.0.4 - importlib-metadata==4.2.0 - mccabe==0.7.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 prefix: /opt/conda/envs/tornado
[ "tornado/test/web_test.py::FinalReturnTest::test_finish_method_return_future", "tornado/test/web_test.py::FinalReturnTest::test_render_method_return_future" ]
[]
[ "tornado/test/web_test.py::SecureCookieV1Test::test_arbitrary_bytes", "tornado/test/web_test.py::SecureCookieV1Test::test_cookie_tampering_future_timestamp", "tornado/test/web_test.py::SecureCookieV1Test::test_round_trip", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_increment_version", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_invalidate_version", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_roundtrip", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_roundtrip_differing_version", "tornado/test/web_test.py::SecureCookieV2Test::test_round_trip", "tornado/test/web_test.py::CookieTest::test_cookie_special_char", "tornado/test/web_test.py::CookieTest::test_get_cookie", "tornado/test/web_test.py::CookieTest::test_set_cookie", "tornado/test/web_test.py::CookieTest::test_set_cookie_domain", "tornado/test/web_test.py::CookieTest::test_set_cookie_expires_days", "tornado/test/web_test.py::CookieTest::test_set_cookie_false_flags", "tornado/test/web_test.py::CookieTest::test_set_cookie_max_age", "tornado/test/web_test.py::CookieTest::test_set_cookie_overwrite", "tornado/test/web_test.py::AuthRedirectTest::test_absolute_auth_redirect", "tornado/test/web_test.py::AuthRedirectTest::test_relative_auth_redirect", "tornado/test/web_test.py::ConnectionCloseTest::test_connection_close", "tornado/test/web_test.py::RequestEncodingTest::test_error", "tornado/test/web_test.py::RequestEncodingTest::test_group_encoding", "tornado/test/web_test.py::RequestEncodingTest::test_group_question_mark", "tornado/test/web_test.py::RequestEncodingTest::test_slashes", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument_invalid_unicode", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument_plus", "tornado/test/web_test.py::WSGISafeWebTest::test_get_argument", "tornado/test/web_test.py::WSGISafeWebTest::test_get_body_arguments", "tornado/test/web_test.py::WSGISafeWebTest::test_get_query_arguments", "tornado/test/web_test.py::WSGISafeWebTest::test_header_injection", "tornado/test/web_test.py::WSGISafeWebTest::test_multi_header", "tornado/test/web_test.py::WSGISafeWebTest::test_no_gzip", "tornado/test/web_test.py::WSGISafeWebTest::test_optional_path", "tornado/test/web_test.py::WSGISafeWebTest::test_redirect", "tornado/test/web_test.py::WSGISafeWebTest::test_reverse_url", "tornado/test/web_test.py::WSGISafeWebTest::test_types", "tornado/test/web_test.py::WSGISafeWebTest::test_uimodule_resources", "tornado/test/web_test.py::WSGISafeWebTest::test_uimodule_unescaped", "tornado/test/web_test.py::WSGISafeWebTest::test_web_redirect", "tornado/test/web_test.py::WSGISafeWebTest::test_web_redirect_double_slash", "tornado/test/web_test.py::NonWSGIWebTests::test_empty_flush", "tornado/test/web_test.py::NonWSGIWebTests::test_flow_control", "tornado/test/web_test.py::ErrorResponseTest::test_default", "tornado/test/web_test.py::ErrorResponseTest::test_failed_write_error", "tornado/test/web_test.py::ErrorResponseTest::test_write_error", "tornado/test/web_test.py::StaticFileTest::test_absolute_static_url", "tornado/test/web_test.py::StaticFileTest::test_absolute_version_exclusion", "tornado/test/web_test.py::StaticFileTest::test_include_host_override", "tornado/test/web_test.py::StaticFileTest::test_path_traversal_protection", "tornado/test/web_test.py::StaticFileTest::test_relative_version_exclusion", "tornado/test/web_test.py::StaticFileTest::test_root_static_path", "tornado/test/web_test.py::StaticFileTest::test_static_304_etag_modified_bug", "tornado/test/web_test.py::StaticFileTest::test_static_304_if_modified_since", "tornado/test/web_test.py::StaticFileTest::test_static_304_if_none_match", "tornado/test/web_test.py::StaticFileTest::test_static_404", "tornado/test/web_test.py::StaticFileTest::test_static_compressed_files", "tornado/test/web_test.py::StaticFileTest::test_static_etag", "tornado/test/web_test.py::StaticFileTest::test_static_files", "tornado/test/web_test.py::StaticFileTest::test_static_head", "tornado/test/web_test.py::StaticFileTest::test_static_head_range", "tornado/test/web_test.py::StaticFileTest::test_static_if_modified_since_pre_epoch", "tornado/test/web_test.py::StaticFileTest::test_static_if_modified_since_time_zone", "tornado/test/web_test.py::StaticFileTest::test_static_invalid_range", "tornado/test/web_test.py::StaticFileTest::test_static_range_if_none_match", "tornado/test/web_test.py::StaticFileTest::test_static_unsatisfiable_range_invalid_start", "tornado/test/web_test.py::StaticFileTest::test_static_unsatisfiable_range_zero_suffix", "tornado/test/web_test.py::StaticFileTest::test_static_url", "tornado/test/web_test.py::StaticFileTest::test_static_with_range", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_end_edge", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_full_file", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_full_past_end", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_neg_end", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_partial_past_end", "tornado/test/web_test.py::StaticDefaultFilenameTest::test_static_default_filename", "tornado/test/web_test.py::StaticDefaultFilenameTest::test_static_default_redirect", "tornado/test/web_test.py::StaticFileWithPathTest::test_serve", "tornado/test/web_test.py::CustomStaticFileTest::test_serve", "tornado/test/web_test.py::CustomStaticFileTest::test_static_url", "tornado/test/web_test.py::HostMatchingTest::test_host_matching", "tornado/test/web_test.py::DefaultHostMatchingTest::test_default_host_matching", "tornado/test/web_test.py::NamedURLSpecGroupsTest::test_named_urlspec_groups", "tornado/test/web_test.py::ClearHeaderTest::test_clear_header", "tornado/test/web_test.py::Header204Test::test_204_headers", "tornado/test/web_test.py::Header304Test::test_304_headers", "tornado/test/web_test.py::StatusReasonTest::test_status", "tornado/test/web_test.py::DateHeaderTest::test_date_header", "tornado/test/web_test.py::RaiseWithReasonTest::test_httperror_str", "tornado/test/web_test.py::RaiseWithReasonTest::test_httperror_str_from_httputil", "tornado/test/web_test.py::RaiseWithReasonTest::test_raise_with_reason", "tornado/test/web_test.py::ErrorHandlerXSRFTest::test_404_xsrf", "tornado/test/web_test.py::ErrorHandlerXSRFTest::test_error_xsrf", "tornado/test/web_test.py::GzipTestCase::test_gzip", "tornado/test/web_test.py::GzipTestCase::test_gzip_not_requested", "tornado/test/web_test.py::GzipTestCase::test_gzip_static", "tornado/test/web_test.py::GzipTestCase::test_vary_already_present", "tornado/test/web_test.py::GzipTestCase::test_vary_already_present_multiple", "tornado/test/web_test.py::PathArgsInPrepareTest::test_kw", "tornado/test/web_test.py::PathArgsInPrepareTest::test_pos", "tornado/test/web_test.py::ClearAllCookiesTest::test_clear_all_cookies", "tornado/test/web_test.py::ExceptionHandlerTest::test_http_error", "tornado/test/web_test.py::ExceptionHandlerTest::test_known_error", "tornado/test/web_test.py::ExceptionHandlerTest::test_unknown_error", "tornado/test/web_test.py::BuggyLoggingTest::test_buggy_log_exception", "tornado/test/web_test.py::UIMethodUIModuleTest::test_ui_method", "tornado/test/web_test.py::GetArgumentErrorTest::test_catch_error", "tornado/test/web_test.py::MultipleExceptionTest::test_multi_exception", "tornado/test/web_test.py::SetLazyPropertiesTest::test_set_properties", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_from_ui_module_is_lazy", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_from_ui_module_works", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_works", "tornado/test/web_test.py::UnimplementedHTTPMethodsTest::test_unimplemented_standard_methods", "tornado/test/web_test.py::UnimplementedNonStandardMethodsTest::test_unimplemented_other", "tornado/test/web_test.py::UnimplementedNonStandardMethodsTest::test_unimplemented_patch", "tornado/test/web_test.py::AllHTTPMethodsTest::test_standard_methods", "tornado/test/web_test.py::PatchMethodTest::test_other", "tornado/test/web_test.py::PatchMethodTest::test_patch", "tornado/test/web_test.py::FinishInPrepareTest::test_finish_in_prepare", "tornado/test/web_test.py::Default404Test::test_404", "tornado/test/web_test.py::Custom404Test::test_404", "tornado/test/web_test.py::DefaultHandlerArgumentsTest::test_403", "tornado/test/web_test.py::HandlerByNameTest::test_handler_by_name", "tornado/test/web_test.py::StreamingRequestBodyTest::test_close_during_upload", "tornado/test/web_test.py::StreamingRequestBodyTest::test_early_return", "tornado/test/web_test.py::StreamingRequestBodyTest::test_early_return_with_data", "tornado/test/web_test.py::StreamingRequestBodyTest::test_streaming_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_chunked_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_compressed_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_fixed_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_chunked_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_compressed_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_fixed_body", "tornado/test/web_test.py::IncorrectContentLengthTest::test_content_length_too_high", "tornado/test/web_test.py::IncorrectContentLengthTest::test_content_length_too_low", "tornado/test/web_test.py::ClientCloseTest::test_client_close", "tornado/test/web_test.py::SignedValueTest::test_expired", "tornado/test/web_test.py::SignedValueTest::test_key_version_retrieval", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_invalid_key", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_read_write_default_key", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_read_write_non_default_key", "tornado/test/web_test.py::SignedValueTest::test_known_values", "tornado/test/web_test.py::SignedValueTest::test_name_swap", "tornado/test/web_test.py::SignedValueTest::test_non_ascii", "tornado/test/web_test.py::SignedValueTest::test_payload_tampering", "tornado/test/web_test.py::SignedValueTest::test_signature_tampering", "tornado/test/web_test.py::XSRFTest::test_cross_user", "tornado/test/web_test.py::XSRFTest::test_distinct_tokens", "tornado/test/web_test.py::XSRFTest::test_refresh_token", "tornado/test/web_test.py::XSRFTest::test_versioning", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_argument_invalid_format", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_body_no_cookie", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_cookie_invalid_format", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_cookie_no_body", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_no_token", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_header", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_non_hex_token", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_post_body", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_query_string", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_short_token", "tornado/test/web_test.py::XSRFCookieKwargsTest::test_xsrf_httponly", "tornado/test/web_test.py::FinishExceptionTest::test_finish_exception", "tornado/test/web_test.py::DecoratorTest::test_addslash", "tornado/test/web_test.py::DecoratorTest::test_removeslash", "tornado/test/web_test.py::CacheTest::test_multiple_strong_etag_match", "tornado/test/web_test.py::CacheTest::test_multiple_strong_etag_not_match", "tornado/test/web_test.py::CacheTest::test_multiple_weak_etag_match", "tornado/test/web_test.py::CacheTest::test_multiple_weak_etag_not_match", "tornado/test/web_test.py::CacheTest::test_strong_etag_match", "tornado/test/web_test.py::CacheTest::test_strong_etag_not_match", "tornado/test/web_test.py::CacheTest::test_weak_etag_match", "tornado/test/web_test.py::CacheTest::test_weak_etag_not_match", "tornado/test/web_test.py::CacheTest::test_wildcard_etag", "tornado/test/web_test.py::RequestSummaryTest::test_missing_remote_ip", "tornado/test/web_test.py::HTTPErrorTest::test_copy", "tornado/test/web_test.py::ApplicationTest::test_listen", "tornado/test/web_test.py::URLSpecReverseTest::test_non_reversible", "tornado/test/web_test.py::URLSpecReverseTest::test_reverse", "tornado/test/web_test.py::URLSpecReverseTest::test_reverse_arguments", "tornado/test/web_test.py::RedirectHandlerTest::test_basic_redirect", "tornado/test/web_test.py::RedirectHandlerTest::test_redirect_pattern", "tornado/test/web_test.py::RedirectHandlerTest::test_redirect_with_appending_argument", "tornado/test/web_test.py::RedirectHandlerTest::test_redirect_with_argument" ]
[]
Apache License 2.0
2,554
[ "tornado/iostream.py", "tornado/web.py", "tornado/netutil.py" ]
[ "tornado/iostream.py", "tornado/web.py", "tornado/netutil.py" ]
marshmallow-code__marshmallow-821
bfc6bedf291bb54f8623acc9380139c06bc8acb2
2018-05-20 02:24:22
8e217c8d6fefb7049ab3389f31a8d35824fa2d96
diff --git a/marshmallow/fields.py b/marshmallow/fields.py index ecfd28d4..737fbfb0 100755 --- a/marshmallow/fields.py +++ b/marshmallow/fields.py @@ -1134,6 +1134,15 @@ class Dict(Field): 'marshmallow.base.FieldABC') self.key_container = keys + def _add_to_schema(self, field_name, schema): + super(Dict, self)._add_to_schema(field_name, schema) + if self.value_container: + self.value_container.parent = self + self.value_container.name = field_name + if self.key_container: + self.key_container.parent = self + self.key_container.name = field_name + def _serialize(self, value, attr, obj): if value is None: return None
Question: How can I pass the context in a nested field of a structured dict? I noticed that if you use a nested field for values in a structured Dict, the context is not automatically given to the nested schema. Is there a way to pass it the context? Example: ```python class Inner(Schema): foo = fields.String() @validates('foo') def validate_foo(self, value): if 'foo_context' not in self.context: raise ValidationError('no context!') class Outer(Schema): bar = fields.Dict(values=fields.Nested(Inner)) # gives no error: Inner(context={'foo_context': 'foo'}).load({'foo': 'some foo'}) # gives 'no context!' error: Outer(context={'foo_context': 'foo'}).load({'bar': { 'key': {'foo': 'some foo'}}}) ```
marshmallow-code/marshmallow
diff --git a/tests/test_schema.py b/tests/test_schema.py index 17c04300..9fee0d63 100755 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -2134,6 +2134,27 @@ class TestContext: outer.context['foo_context'] = 'foo' assert outer.load({'bars': [{'foo': 42}]}) + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates('foo') + def validate_foo(self, value): + if 'foo_context' not in self.context: + raise ValidationError('Missing context') + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context['foo_context'] = 'foo' + assert inner.load({'foo': 42}) + + outer = OuterSchema() + outer.context['foo_context'] = 'foo' + assert outer.load({'bars': {'test': {'foo': 42}}}) + def test_serializer_can_specify_nested_object_as_attribute(blog): class BlogUsernameSchema(Schema):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[reco]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": [ "dev-requirements.txt", "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 flake8==3.5.0 iniconfig==2.1.0 invoke==1.0.0 -e git+https://github.com/marshmallow-code/marshmallow.git@bfc6bedf291bb54f8623acc9380139c06bc8acb2#egg=marshmallow mccabe==0.6.1 more-itertools==10.6.0 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 py==1.11.0 pycodestyle==2.3.1 pyflakes==1.6.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.7.3 pytz==2018.4 simplejson==3.15.0 six==1.17.0 toml==0.10.2 tomli==2.2.1 tox==3.12.1 typing_extensions==4.13.0 virtualenv==20.29.3
name: marshmallow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - flake8==3.5.0 - iniconfig==2.1.0 - invoke==1.0.0 - mccabe==0.6.1 - more-itertools==10.6.0 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - py==1.11.0 - pycodestyle==2.3.1 - pyflakes==1.6.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.7.3 - pytz==2018.4 - simplejson==3.15.0 - six==1.17.0 - toml==0.10.2 - tomli==2.2.1 - tox==3.12.1 - typing-extensions==4.13.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/marshmallow
[ "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context" ]
[]
[ "tests/test_schema.py::test_serializing_basic_object[UserSchema]", "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", "tests/test_schema.py::test_serializer_dump", "tests/test_schema.py::test_dump_raises_with_dict_of_errors", "tests/test_schema.py::test_dump_mode_raises_error[UserSchema]", "tests/test_schema.py::test_dump_mode_raises_error[UserMetaSchema]", "tests/test_schema.py::test_dump_resets_errors", "tests/test_schema.py::test_load_resets_errors", "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", "tests/test_schema.py::test_dump_validation_error_stores_partially_valid_data", "tests/test_schema.py::test_dump_resets_error_fields", "tests/test_schema.py::test_load_resets_error_fields", "tests/test_schema.py::test_load_resets_error_kwargs", "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", "tests/test_schema.py::test_load_many_stores_error_indices", "tests/test_schema.py::test_dump_many", "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", "tests/test_schema.py::test_dump_many_stores_error_indices", "tests/test_schema.py::test_dump_many_doesnt_stores_error_indices_when_index_errors_is_false", "tests/test_schema.py::test_dump_returns_a_dict", "tests/test_schema.py::test_dumps_returns_a_string", "tests/test_schema.py::test_dumping_single_object_with_collection_schema", "tests/test_schema.py::test_loading_single_object_with_collection_schema", "tests/test_schema.py::test_dumps_many", "tests/test_schema.py::test_load_returns_an_object", "tests/test_schema.py::test_load_many", "tests/test_schema.py::test_loads_returns_a_user", "tests/test_schema.py::test_loads_many", "tests/test_schema.py::test_loads_deserializes_from_json", "tests/test_schema.py::test_serializing_none", "tests/test_schema.py::test_default_many_symmetry", "tests/test_schema.py::test_on_bind_field_hook", "tests/test_schema.py::test_nested_on_bind_field_hook", "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", "tests/test_schema.py::TestValidate::test_validate_many", "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", "tests/test_schema.py::TestValidate::test_validate", "tests/test_schema.py::TestValidate::test_validate_required", "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", "tests/test_schema.py::test_dumps_returns_json", "tests/test_schema.py::test_naive_datetime_field", "tests/test_schema.py::test_datetime_formatted_field", "tests/test_schema.py::test_datetime_iso_field", "tests/test_schema.py::test_tz_datetime_field", "tests/test_schema.py::test_local_datetime_field", "tests/test_schema.py::test_class_variable", "tests/test_schema.py::test_serialize_many[UserSchema]", "tests/test_schema.py::test_serialize_many[UserMetaSchema]", "tests/test_schema.py::test_inheriting_schema", "tests/test_schema.py::test_custom_field", "tests/test_schema.py::test_url_field", "tests/test_schema.py::test_relative_url_field", "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", "tests/test_schema.py::test_email_field[UserSchema]", "tests/test_schema.py::test_email_field[UserMetaSchema]", "tests/test_schema.py::test_stored_invalid_email", "tests/test_schema.py::test_integer_field", "tests/test_schema.py::test_as_string", "tests/test_schema.py::test_method_field[UserSchema]", "tests/test_schema.py::test_method_field[UserMetaSchema]", "tests/test_schema.py::test_function_field", "tests/test_schema.py::test_prefix[UserSchema]", "tests/test_schema.py::test_prefix[UserMetaSchema]", "tests/test_schema.py::test_fields_must_be_declared_as_instances", "tests/test_schema.py::test_serializing_generator[UserSchema]", "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", "tests/test_schema.py::test_serializing_dict", "tests/test_schema.py::test_serializing_dict_with_meta_fields", "tests/test_schema.py::test_exclude_in_init[UserSchema]", "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", "tests/test_schema.py::test_only_in_init[UserSchema]", "tests/test_schema.py::test_only_in_init[UserMetaSchema]", "tests/test_schema.py::test_invalid_only_param", "tests/test_schema.py::test_can_serialize_uuid", "tests/test_schema.py::test_can_serialize_time", "tests/test_schema.py::test_invalid_time", "tests/test_schema.py::test_invalid_date", "tests/test_schema.py::test_invalid_dict_but_okay", "tests/test_schema.py::test_json_module_is_deprecated", "tests/test_schema.py::test_render_module", "tests/test_schema.py::test_custom_error_message", "tests/test_schema.py::test_load_errors_with_many", "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", "tests/test_schema.py::test_nested_only", "tests/test_schema.py::test_nested_only_inheritance", "tests/test_schema.py::test_nested_only_empty_inheritance", "tests/test_schema.py::test_nested_exclude", "tests/test_schema.py::test_nested_exclude_inheritance", "tests/test_schema.py::test_nested_only_and_exclude", "tests/test_schema.py::test_nested_only_then_exclude_inheritance", "tests/test_schema.py::test_nested_exclude_then_only_inheritance", "tests/test_schema.py::test_nested_exclude_and_only_inheritance", "tests/test_schema.py::test_meta_nested_exclude", "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", "tests/test_schema.py::test_deeply_nested_only_and_exclude", "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", "tests/test_schema.py::test_nested_constructor_only_and_exclude", "tests/test_schema.py::test_only_and_exclude", "tests/test_schema.py::test_exclude_invalid_attribute", "tests/test_schema.py::test_only_with_invalid_attribute", "tests/test_schema.py::test_only_bounded_by_fields", "tests/test_schema.py::test_only_empty", "tests/test_schema.py::test_nested_with_sets", "tests/test_schema.py::test_meta_serializer_fields", "tests/test_schema.py::test_meta_fields_mapping", "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", "tests/test_schema.py::test_exclude_fields", "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", "tests/test_schema.py::test_dateformat_option", "tests/test_schema.py::test_default_dateformat", "tests/test_schema.py::test_inherit_meta", "tests/test_schema.py::test_inherit_meta_override", "tests/test_schema.py::test_additional", "tests/test_schema.py::test_cant_set_both_additional_and_fields", "tests/test_schema.py::test_serializing_none_meta", "tests/test_schema.py::TestHandleError::test_dump_with_custom_error_handler", "tests/test_schema.py::TestHandleError::test_load_with_custom_error_handler", "tests/test_schema.py::TestHandleError::test_load_with_custom_error_handler_and_partially_valid_data", "tests/test_schema.py::TestHandleError::test_custom_error_handler_with_validates_decorator", "tests/test_schema.py::TestHandleError::test_custom_error_handler_with_validates_schema_decorator", "tests/test_schema.py::TestHandleError::test_validate_with_custom_error_handler", "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::TestNestedSchema::test_flat_nested", "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", "tests/test_schema.py::TestNestedSchema::test_flat_nested2", "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", "tests/test_schema.py::TestNestedSchema::test_nested_none", "tests/test_schema.py::TestNestedSchema::test_nested", "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", "tests/test_schema.py::TestNestedSchema::test_nested_only", "tests/test_schema.py::TestNestedSchema::test_exclude", "tests/test_schema.py::TestNestedSchema::test_list_field", "tests/test_schema.py::TestNestedSchema::test_nested_load_many", "tests/test_schema.py::TestNestedSchema::test_nested_errors", "tests/test_schema.py::TestNestedSchema::test_nested_dump_errors", "tests/test_schema.py::TestNestedSchema::test_nested_dump", "tests/test_schema.py::TestNestedSchema::test_nested_method_field", "tests/test_schema.py::TestNestedSchema::test_nested_function_field", "tests/test_schema.py::TestNestedSchema::test_nested_prefixed_field", "tests/test_schema.py::TestNestedSchema::test_nested_prefixed_many_field", "tests/test_schema.py::TestNestedSchema::test_invalid_float_field", "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", "tests/test_schema.py::TestNestedSchema::test_dump_validation_error", "tests/test_schema.py::TestSelfReference::test_nesting_schema_within_itself", "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", "tests/test_schema.py::TestSelfReference::test_multiple_nested_self_fields", "tests/test_schema.py::TestSelfReference::test_nested_many", "tests/test_schema.py::test_serialization_with_required_field", "tests/test_schema.py::test_deserialization_with_required_field", "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", "tests/test_schema.py::TestContext::test_context_method", "tests/test_schema.py::TestContext::test_context_method_function", "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", "tests/test_schema.py::TestContext::test_fields_context", "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", "tests/test_schema.py::TestRequiredFields::test_allow_none_param", "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", "tests/test_schema.py::TestDefaults::test_default_and_value_missing", "tests/test_schema.py::TestDefaults::test_loading_none", "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", "tests/test_schema.py::TestLoadOnly::test_load_only", "tests/test_schema.py::TestLoadOnly::test_dump_only", "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false" ]
[]
MIT License
2,555
[ "marshmallow/fields.py" ]
[ "marshmallow/fields.py" ]
marshmallow-code__marshmallow-823
7e19a295e7e23c0ef6dfa730dbf21e67f9408310
2018-05-20 05:27:47
8e217c8d6fefb7049ab3389f31a8d35824fa2d96
lafrech: Nothing really mandatory in my comments. This looks pretty good to me. Thanks @deckar01 for tackling this. lafrech: When this is merged, we can add a test to raise `StringNotCollectionError` if `only` or `exclude` is passed to `Nested` as string, not list of strings. See https://github.com/marshmallow-code/marshmallow/pull/896. sloria: Looks good to me as well. @deckar01 Can you please get this up to date? Once that's done, feel free to merge.
diff --git a/docs/nesting.rst b/docs/nesting.rst index b5afbaf1..06f2f309 100644 --- a/docs/nesting.rst +++ b/docs/nesting.rst @@ -99,32 +99,30 @@ You can represent the attributes of deeply nested objects using dot delimiters. # } # } -.. note:: +You can replace nested data with a single value (or flat list of values if ``many=True``) using the :class:`Pluck <marshmallow.fields.Pluck>` field. - If you pass in a string field name to ``only``, only a single value (or flat list of values if ``many=True``) will be (de)serialized. +.. code-block:: python + :emphasize-lines: 4, 11, 18 - .. code-block:: python - :emphasize-lines: 4, 11, 18 - - class UserSchema(Schema): - name = fields.String() - email = fields.Email() - friends = fields.Nested('self', only='name', many=True) - # ... create ``user`` ... - serialized_data = UserSchema().dump(user) - pprint(serialized_data) - # { - # "name": "Steve", - # "email": "[email protected]", - # "friends": ["Mike", "Joe"] - # } - deserialized_data = UserSchema().load(result) - pprint(deserialized_data) - # { - # "name": "Steve", - # "email": "[email protected]", - # "friends": [{"name": "Mike"}, {"name": "Joe"}] - # } + class UserSchema(Schema): + name = fields.String() + email = fields.Email() + friends = fields.Pluck('self', 'name', many=True) + # ... create ``user`` ... + serialized_data = UserSchema().dump(user) + pprint(serialized_data) + # { + # "name": "Steve", + # "email": "[email protected]", + # "friends": ["Mike", "Joe"] + # } + deserialized_data = UserSchema().load(result) + pprint(deserialized_data) + # { + # "name": "Steve", + # "email": "[email protected]", + # "friends": [{"name": "Mike"}, {"name": "Joe"}] + # } You can also exclude fields by passing in an ``exclude`` list. This argument also allows representing the attributes of deeply nested objects using dot delimiters. diff --git a/docs/upgrading.rst b/docs/upgrading.rst index ad0bee81..71e8eb20 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -569,6 +569,24 @@ Processors that mutate the data should be updated to also return it. in_data['slug'] = in_data['slug'].lower().strip().replace(' ', '-') return in_data +The Nested field no longer supports plucking +******************************************** + +In marshmallow 2.x, when a string was passed to a ``Nested`` field's ```only`` parameter, the field would be plucked. In marshmallow 3.x, the ``Pluck`` field must be used instead. + + +.. code-block:: python + + # 2.x + class UserSchema(Schema): + name = fields.Str() + friends = fields.Nested('self', many=True, only='name') + + # 3.x + class UserSchema(Schema): + name = fields.Str() + friends = fields.Pluck('self', 'name', many=True) + Upgrading to 2.3 diff --git a/marshmallow/fields.py b/marshmallow/fields.py index d04bbedc..7b734697 100755 --- a/marshmallow/fields.py +++ b/marshmallow/fields.py @@ -349,7 +349,7 @@ class Nested(Field): user = fields.Nested(UserSchema) user2 = fields.Nested('UserSchema') # Equivalent to above - collaborators = fields.Nested(UserSchema, many=True, only='id') + collaborators = fields.Nested(UserSchema, many=True, only=('id',)) parent = fields.Nested('self') When passing a `Schema <marshmallow.Schema>` instance as the first argument, @@ -401,45 +401,29 @@ class Nested(Field): Renamed from `serializer` to `schema` """ if not self.__schema: - # Ensure that only parameter is a tuple - if isinstance(self.only, basestring): - only = (self.only,) - else: - only = self.only - # Inherit context from parent. context = getattr(self.parent, 'context', {}) if isinstance(self.nested, SchemaABC): self.__schema = self.nested self.__schema.context.update(context) - elif isinstance(self.nested, type) and \ - issubclass(self.nested, SchemaABC): - self.__schema = self.nested( + else: + if isinstance(self.nested, type) and issubclass(self.nested, SchemaABC): + schema_class = self.nested + elif not isinstance(self.nested, basestring): + raise ValueError( + 'Nested fields must be passed a ' + 'Schema, not {0}.'.format(self.nested.__class__), + ) + elif self.nested == 'self': + schema_class = self.parent.__class__ + else: + schema_class = class_registry.get_class(self.nested) + self.__schema = schema_class( many=self.many, - only=only, exclude=self.exclude, context=context, + only=self.only, exclude=self.exclude, context=context, load_only=self._nested_normalized_option('load_only'), dump_only=self._nested_normalized_option('dump_only'), ) - elif isinstance(self.nested, basestring): - if self.nested == 'self': - parent_class = self.parent.__class__ - self.__schema = parent_class( - many=self.many, only=only, - exclude=self.exclude, context=context, - load_only=self._nested_normalized_option('load_only'), - dump_only=self._nested_normalized_option('dump_only'), - ) - else: - schema_class = class_registry.get_class(self.nested) - self.__schema = schema_class( - many=self.many, - only=only, exclude=self.exclude, context=context, - load_only=self._nested_normalized_option('load_only'), - dump_only=self._nested_normalized_option('dump_only'), - ) - else: - raise ValueError('Nested fields must be passed a ' - 'Schema, not {0}.'.format(self.nested.__class__)) self.__schema.ordered = getattr(self.parent, 'ordered', False) return self.__schema @@ -459,37 +443,65 @@ class Nested(Field): schema._update_fields(obj=nested_obj, many=self.many) self.__updated_fields = True try: - ret = schema.dump( + return schema.dump( nested_obj, many=self.many, update_fields=not self.__updated_fields, ) except ValidationError as exc: raise ValidationError(exc.messages, data=obj, valid_data=exc.valid_data) - finally: - if isinstance(self.only, basestring): # self.only is a field name - only_field = self.schema.fields[self.only] - key = only_field.data_key or self.only - if self.many: - return utils.pluck(ret, key=key) - else: - return ret[key] - return ret - def _deserialize(self, value, attr, data): + def _test_collection(self, value): if self.many and not utils.is_collection(value): self.fail('type', input=value, type=value.__class__.__name__) - if isinstance(self.only, basestring): # self.only is a field name - if self.many: - value = [{self.only: v} for v in value] - else: - value = {self.only: value} + def _load(self, value, data): try: valid_data = self.schema.load(value, unknown=self.unknown) except ValidationError as exc: raise ValidationError(exc.messages, data=data, valid_data=exc.valid_data) return valid_data + def _deserialize(self, value, attr, data): + self._test_collection(value) + return self._load(value, data) + + +class Pluck(Nested): + """Allows you to replace nested data with one of the data's fields. + + Examples: :: + + user = fields.Pluck(UserSchema, 'name') + collaborators = fields.Pluck(UserSchema, 'id', many=True) + parent = fields.Pluck('self', 'name') + + :param Schema nested: The Schema class or class name (string) + to nest, or ``"self"`` to nest the :class:`Schema` within itself. + :param str field_name: + :param kwargs: The same keyword arguments that :class:`Nested` receives. + """ + def __init__(self, nested, field_name, **kwargs): + super(Pluck, self).__init__(nested, only=(field_name,), **kwargs) + self.field_name = field_name + + def _serialize(self, nested_obj, attr, obj): + ret = super(Pluck, self)._serialize(nested_obj, attr, obj) + only_field = self.schema.fields[self.field_name] + data_key = only_field.data_key or self.field_name + key = ''.join([self.schema.prefix or '', data_key]) + if self.many: + return utils.pluck(ret, key=key) + else: + return ret[key] + + def _deserialize(self, value, attr, data): + self._test_collection(value) + if self.many: + value = [{self.field_name: v} for v in value] + else: + value = {self.field_name: value} + return self._load(value, data) + class List(Field): """A list field, composed with another `Field` class or
Nested single string 'only' behavior edge case When using Nested fields, passing a single string field to `only` does not work as expected when applying a transform with `on_bind_field` ```python from marshmallow import fields, Schema def test_nested_only_on_bind_field(): def to_camel_case(snake_str): components = snake_str.split('_') return components[0] + ''.join(x.title() for x in components[1:]) class CamelCaseSchema(Schema): def on_bind_field(self, field_name, field_obj): field_obj.data_key = to_camel_case(field_name) class UserRoleSchema(CamelCaseSchema): user_id = fields.Number() role_name = fields.String() class UserSchema(CamelCaseSchema): id = fields.Number() roles = fields.Nested(UserRoleSchema, many=True, only='role_name') user = { 'id': 1, 'roles': [ {'user_id': 1, 'role_name': 'admin'}, {'user_id': 1, 'role_name': 'test'}, ] } serialized_user = UserSchema().dumps(user) assert serialized_user == {"id": 1, "roles": ["admin", "test"]} ``` This results in the following error: ``` /env/lib/python3.6/site-packages/marshmallow/schema.py:476: in dumps serialized = self.dump(obj, many=many, update_fields=update_fields) /env/lib/python3.6/site-packages/marshmallow/schema.py:428: in dump **kwargs /env/lib/python3.6/site-packages/marshmallow/marshalling.py:147: in serialize index=(index if index_errors else None) /env/lib/python3.6/site-packages/marshmallow/marshalling.py:68: in call_and_store value = getter_func(data) /env/lib/python3.6/site-packages/marshmallow/marshalling.py:141: in <lambda> getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor) /env/lib/python3.6/site-packages/marshmallow/fields.py:250: in serialize return self._serialize(value, attr, obj) /env/lib/python3.6/site-packages/marshmallow/fields.py:455: in _serialize return utils.pluck(ret, key=self.only) /env/lib/python3.6/site-packages/marshmallow/utils.py:318: in pluck return [d[key] for d in dictlist] KeyError: 'role_name' ``` This seems to be only affecting the single string case, as passing `only=['role_name']` works as expected.
marshmallow-code/marshmallow
diff --git a/tests/test_deserialization.py b/tests/test_deserialization.py index d842fc5d..54f643b2 100644 --- a/tests/test_deserialization.py +++ b/tests/test_deserialization.py @@ -1026,7 +1026,7 @@ class TestSchemaDeserialization: class MainSchema(Schema): pk = fields.Str() - child = fields.Nested(ANestedSchema, only='pk') + child = fields.Pluck(ANestedSchema, 'pk') sch = MainSchema() result = sch.load({'pk': '123', 'child': '456'}) @@ -1038,7 +1038,7 @@ class TestSchemaDeserialization: class MainSchema(Schema): pk = fields.Str() - children = fields.Nested(ANestedSchema, only='pk', many=True) + children = fields.Pluck(ANestedSchema, 'pk', many=True) sch = MainSchema() result = sch.load({'pk': '123', 'children': ['456', '789']}) diff --git a/tests/test_schema.py b/tests/test_schema.py index 01f2e318..34474580 100755 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1717,23 +1717,6 @@ class TestNestedSchema: ) return blog - def test_flat_nested(self, blog): - class FlatBlogSchema(Schema): - name = fields.String() - user = fields.Nested(UserSchema, only='name') - collaborators = fields.Nested(UserSchema, only='name', many=True) - s = FlatBlogSchema() - data = s.dump(blog) - assert data['user'] == blog.user.name - for i, name in enumerate(data['collaborators']): - assert name == blog.collaborators[i].name - - # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 - def test_flat_nested_with_data_key(self, blog): - class UserSchema(Schema): - name = fields.String(data_key='username') - age = fields.Int() - class FlatBlogSchema(Schema): name = fields.String() user = fields.Nested(UserSchema, only='name') @@ -1772,15 +1755,6 @@ class TestNestedSchema: result2 = s2.dump({'foo': None}) assert result2['foo'] is None - def test_flat_nested2(self, blog): - class FlatBlogSchema(Schema): - name = fields.String() - collaborators = fields.Nested(UserSchema, many=True, only='uid') - - s = FlatBlogSchema() - data = s.dump(blog) - assert data['collaborators'][0] == str(blog.collaborators[0].uid) - def test_nested_field_does_not_validate_required(self): class BlogRequiredSchema(Schema): user = fields.Nested(UserSchema, required=True) @@ -1998,6 +1972,44 @@ class TestNestedSchema: assert errors == {'foo': {'foo': ['Not a valid integer.']}} +class TestPluckSchema: + + def blog(self): + user = User(name='Monty', age=81) + col1 = User(name='Mick', age=123) + col2 = User(name='Keith', age=456) + blog = Blog( + user=user, categories=['humor', 'violence'], + collaborators=[col1, col2], + ) + return blog + + def test_pluck(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, 'name') + collaborators = fields.Pluck(UserSchema, 'name', many=True) + s = FlatBlogSchema() + data = s.dump(blog) + assert data['user'] == blog.user.name + for i, name in enumerate(data['collaborators']): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key='username') + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, 'name') + collaborators = fields.Pluck(UserSchema, 'name', many=True) + s = FlatBlogSchema() + data = s.dump(blog) + assert data['user'] == blog.user.name + for i, name in enumerate(data['collaborators']): + assert name == blog.collaborators[i].name + + class TestSelfReference: @pytest.fixture @@ -2054,13 +2066,10 @@ class TestSelfReference: assert data['employer']['name'] == employer.name assert 'age' not in data['employer'] - def test_multiple_nested_self_fields(self, user): + def test_multiple_pluck_self_field(self, user): class MultipleSelfSchema(Schema): - emp = fields.Nested('self', only='name', attribute='employer') - rels = fields.Nested( - 'self', only='name', - many=True, attribute='relatives', - ) + emp = fields.Pluck('self', 'name', attribute='employer') + rels = fields.Pluck('self', 'name', many=True, attribute='relatives') class Meta: fields = ('name', 'emp', 'rels')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 3 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[reco]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio", "pytest" ], "pre_install": [], "python": "3.9", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aspy.yaml==1.3.0 atomicwrites==1.4.1 attrs==25.3.0 cached-property==2.0.1 cachetools==5.5.2 cfgv==3.4.0 chardet==5.2.0 colorama==0.4.6 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 flake8==3.5.0 identify==2.6.9 iniconfig==2.1.0 invoke==1.1.1 -e git+https://github.com/marshmallow-code/marshmallow.git@7e19a295e7e23c0ef6dfa730dbf21e67f9408310#egg=marshmallow mccabe==0.6.1 more-itertools==10.6.0 nodeenv==1.9.1 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 pre-commit==1.10.5 py==1.11.0 pycodestyle==2.3.1 pyflakes==1.6.0 pyproject-api==1.9.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.7.3 pytz==2018.5 PyYAML==6.0.2 simplejson==3.16.0 six==1.17.0 -e git+ssh://[email protected]/nebius/swebench_matterhorn.git@ae4d15b4472bd322342107dd10c47d793189f5b2#egg=swebench_matterhorn toml==0.10.2 tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 virtualenv==20.29.3
name: marshmallow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aspy-yaml==1.3.0 - atomicwrites==1.4.1 - attrs==25.3.0 - cached-property==2.0.1 - cachetools==5.5.2 - cfgv==3.4.0 - chardet==5.2.0 - colorama==0.4.6 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - flake8==3.5.0 - identify==2.6.9 - iniconfig==2.1.0 - invoke==1.1.1 - mccabe==0.6.1 - more-itertools==10.6.0 - nodeenv==1.9.1 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==1.10.5 - py==1.11.0 - pycodestyle==2.3.1 - pyflakes==1.6.0 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.7.3 - pytz==2018.5 - pyyaml==6.0.2 - simplejson==3.16.0 - six==1.17.0 - toml==0.10.2 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/marshmallow
[ "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", "tests/test_schema.py::TestPluckSchema::test_pluck", "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_field" ]
[]
[ "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[LocalDateTime]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FormattedString]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[LocalDateTime]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FormattedString]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_empty_list", "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value3]", "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_passed_year_is_invalid", "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_passed_date_is_invalid", "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_rfc_datetime_field_deserialization[rfc]", "tests/test_deserialization.py::TestFieldDeserialization::test_rfc_datetime_field_deserialization[rfc822]", "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[iso]", "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[iso8601]", "tests/test_deserialization.py::TestFieldDeserialization::test_localdatetime_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_non_utf8_value", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", "tests/test_deserialization.py::TestValidation::test_integer_with_validator", "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", "tests/test_deserialization.py::TestValidation::test_string_validator", "tests/test_deserialization.py::TestValidation::test_function_validator", "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", "tests/test_deserialization.py::TestValidation::test_method_validator", "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", "tests/test_deserialization.py::TestValidation::test_false_value_validation", "tests/test_deserialization.py::test_required_field_failure[String]", "tests/test_deserialization.py::test_required_field_failure[Integer]", "tests/test_deserialization.py::test_required_field_failure[Boolean]", "tests/test_deserialization.py::test_required_field_failure[Float]", "tests/test_deserialization.py::test_required_field_failure[Number]", "tests/test_deserialization.py::test_required_field_failure[DateTime]", "tests/test_deserialization.py::test_required_field_failure[LocalDateTime]", "tests/test_deserialization.py::test_required_field_failure[Time]", "tests/test_deserialization.py::test_required_field_failure[Date]", "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", "tests/test_deserialization.py::test_required_field_failure[Dict]", "tests/test_deserialization.py::test_required_field_failure[Url]", "tests/test_deserialization.py::test_required_field_failure[Email]", "tests/test_deserialization.py::test_required_field_failure[UUID]", "tests/test_deserialization.py::test_required_field_failure[Decimal]", "tests/test_deserialization.py::test_required_message_can_be_changed[My", "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", "tests/test_schema.py::test_serializing_basic_object[UserSchema]", "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", "tests/test_schema.py::test_serializer_dump", "tests/test_schema.py::test_dump_raises_with_dict_of_errors", "tests/test_schema.py::test_dump_mode_raises_error[UserSchema]", "tests/test_schema.py::test_dump_mode_raises_error[UserMetaSchema]", "tests/test_schema.py::test_dump_resets_errors", "tests/test_schema.py::test_load_resets_errors", "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", "tests/test_schema.py::test_dump_validation_error_stores_partially_valid_data", "tests/test_schema.py::test_dump_resets_error_fields", "tests/test_schema.py::test_load_resets_error_fields", "tests/test_schema.py::test_load_resets_error_kwargs", "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", "tests/test_schema.py::test_load_many_stores_error_indices", "tests/test_schema.py::test_dump_many", "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", "tests/test_schema.py::test_dump_many_stores_error_indices", "tests/test_schema.py::test_dump_many_doesnt_stores_error_indices_when_index_errors_is_false", "tests/test_schema.py::test_dump_returns_a_dict", "tests/test_schema.py::test_dumps_returns_a_string", "tests/test_schema.py::test_dumping_single_object_with_collection_schema", "tests/test_schema.py::test_loading_single_object_with_collection_schema", "tests/test_schema.py::test_dumps_many", "tests/test_schema.py::test_load_returns_an_object", "tests/test_schema.py::test_load_many", "tests/test_schema.py::test_loads_returns_a_user", "tests/test_schema.py::test_loads_many", "tests/test_schema.py::test_loads_deserializes_from_json", "tests/test_schema.py::test_serializing_none", "tests/test_schema.py::test_default_many_symmetry", "tests/test_schema.py::test_on_bind_field_hook", "tests/test_schema.py::test_nested_on_bind_field_hook", "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", "tests/test_schema.py::TestValidate::test_validate_many", "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", "tests/test_schema.py::TestValidate::test_validate", "tests/test_schema.py::TestValidate::test_validate_required", "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", "tests/test_schema.py::test_dumps_returns_json", "tests/test_schema.py::test_naive_datetime_field", "tests/test_schema.py::test_datetime_formatted_field", "tests/test_schema.py::test_datetime_iso_field", "tests/test_schema.py::test_tz_datetime_field", "tests/test_schema.py::test_local_datetime_field", "tests/test_schema.py::test_class_variable", "tests/test_schema.py::test_serialize_many[UserSchema]", "tests/test_schema.py::test_serialize_many[UserMetaSchema]", "tests/test_schema.py::test_inheriting_schema", "tests/test_schema.py::test_custom_field", "tests/test_schema.py::test_url_field", "tests/test_schema.py::test_relative_url_field", "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", "tests/test_schema.py::test_email_field[UserSchema]", "tests/test_schema.py::test_email_field[UserMetaSchema]", "tests/test_schema.py::test_stored_invalid_email", "tests/test_schema.py::test_integer_field", "tests/test_schema.py::test_as_string", "tests/test_schema.py::test_method_field[UserSchema]", "tests/test_schema.py::test_method_field[UserMetaSchema]", "tests/test_schema.py::test_function_field", "tests/test_schema.py::test_prefix[UserSchema]", "tests/test_schema.py::test_prefix[UserMetaSchema]", "tests/test_schema.py::test_fields_must_be_declared_as_instances", "tests/test_schema.py::test_serializing_generator[UserSchema]", "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", "tests/test_schema.py::test_serializing_dict", "tests/test_schema.py::test_serializing_dict_with_meta_fields", "tests/test_schema.py::test_exclude_in_init[UserSchema]", "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", "tests/test_schema.py::test_only_in_init[UserSchema]", "tests/test_schema.py::test_only_in_init[UserMetaSchema]", "tests/test_schema.py::test_invalid_only_param", "tests/test_schema.py::test_can_serialize_uuid", "tests/test_schema.py::test_can_serialize_time", "tests/test_schema.py::test_invalid_time", "tests/test_schema.py::test_invalid_date", "tests/test_schema.py::test_invalid_dict_but_okay", "tests/test_schema.py::test_json_module_is_deprecated", "tests/test_schema.py::test_render_module", "tests/test_schema.py::test_custom_error_message", "tests/test_schema.py::test_load_errors_with_many", "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", "tests/test_schema.py::test_nested_only", "tests/test_schema.py::test_nested_only_inheritance", "tests/test_schema.py::test_nested_only_empty_inheritance", "tests/test_schema.py::test_nested_exclude", "tests/test_schema.py::test_nested_exclude_inheritance", "tests/test_schema.py::test_nested_only_and_exclude", "tests/test_schema.py::test_nested_only_then_exclude_inheritance", "tests/test_schema.py::test_nested_exclude_then_only_inheritance", "tests/test_schema.py::test_nested_exclude_and_only_inheritance", "tests/test_schema.py::test_meta_nested_exclude", "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", "tests/test_schema.py::test_deeply_nested_only_and_exclude", "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", "tests/test_schema.py::test_nested_constructor_only_and_exclude", "tests/test_schema.py::test_only_and_exclude", "tests/test_schema.py::test_only_and_exclude_with_fields", "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", "tests/test_schema.py::test_only_and_exclude_with_additional", "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", "tests/test_schema.py::test_exclude_invalid_attribute", "tests/test_schema.py::test_only_bounded_by_fields", "tests/test_schema.py::test_only_bounded_by_additional", "tests/test_schema.py::test_only_empty", "tests/test_schema.py::test_only_and_exclude_as_string[only]", "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", "tests/test_schema.py::test_nested_with_sets", "tests/test_schema.py::test_meta_serializer_fields", "tests/test_schema.py::test_meta_fields_mapping", "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", "tests/test_schema.py::test_exclude_fields", "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", "tests/test_schema.py::test_dateformat_option", "tests/test_schema.py::test_default_dateformat", "tests/test_schema.py::test_inherit_meta", "tests/test_schema.py::test_inherit_meta_override", "tests/test_schema.py::test_additional", "tests/test_schema.py::test_cant_set_both_additional_and_fields", "tests/test_schema.py::test_serializing_none_meta", "tests/test_schema.py::TestHandleError::test_dump_with_custom_error_handler", "tests/test_schema.py::TestHandleError::test_load_with_custom_error_handler", "tests/test_schema.py::TestHandleError::test_load_with_custom_error_handler_and_partially_valid_data", "tests/test_schema.py::TestHandleError::test_custom_error_handler_with_validates_decorator", "tests/test_schema.py::TestHandleError::test_custom_error_handler_with_validates_schema_decorator", "tests/test_schema.py::TestHandleError::test_validate_with_custom_error_handler", "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", "tests/test_schema.py::TestNestedSchema::test_nested_none", "tests/test_schema.py::TestNestedSchema::test_nested", "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", "tests/test_schema.py::TestNestedSchema::test_nested_only", "tests/test_schema.py::TestNestedSchema::test_exclude", "tests/test_schema.py::TestNestedSchema::test_list_field", "tests/test_schema.py::TestNestedSchema::test_nested_load_many", "tests/test_schema.py::TestNestedSchema::test_nested_errors", "tests/test_schema.py::TestNestedSchema::test_nested_dump_errors", "tests/test_schema.py::TestNestedSchema::test_nested_dump", "tests/test_schema.py::TestNestedSchema::test_nested_method_field", "tests/test_schema.py::TestNestedSchema::test_nested_function_field", "tests/test_schema.py::TestNestedSchema::test_nested_prefixed_field", "tests/test_schema.py::TestNestedSchema::test_nested_prefixed_many_field", "tests/test_schema.py::TestNestedSchema::test_invalid_float_field", "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", "tests/test_schema.py::TestNestedSchema::test_dump_validation_error", "tests/test_schema.py::TestSelfReference::test_nesting_schema_within_itself", "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", "tests/test_schema.py::TestSelfReference::test_nested_many", "tests/test_schema.py::test_serialization_with_required_field", "tests/test_schema.py::test_deserialization_with_required_field", "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", "tests/test_schema.py::TestContext::test_context_method", "tests/test_schema.py::TestContext::test_context_method_function", "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", "tests/test_schema.py::TestContext::test_fields_context", "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", "tests/test_schema.py::TestRequiredFields::test_allow_none_param", "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", "tests/test_schema.py::TestDefaults::test_default_and_value_missing", "tests/test_schema.py::TestDefaults::test_loading_none", "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", "tests/test_schema.py::TestLoadOnly::test_load_only", "tests/test_schema.py::TestLoadOnly::test_dump_only", "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false" ]
[]
MIT License
2,556
[ "docs/nesting.rst", "docs/upgrading.rst", "marshmallow/fields.py" ]
[ "docs/nesting.rst", "docs/upgrading.rst", "marshmallow/fields.py" ]
tornadoweb__tornado-2397
6410cd98c1a5e938246a17cac0769f689ed471c5
2018-05-20 18:39:50
6410cd98c1a5e938246a17cac0769f689ed471c5
ploxiln: functionally looks great
diff --git a/tornado/curl_httpclient.py b/tornado/curl_httpclient.py index 54fc5b36..ef98225c 100644 --- a/tornado/curl_httpclient.py +++ b/tornado/curl_httpclient.py @@ -348,8 +348,8 @@ class CurlAsyncHTTPClient(AsyncHTTPClient): curl.setopt(pycurl.PROXY, request.proxy_host) curl.setopt(pycurl.PROXYPORT, request.proxy_port) if request.proxy_username: - credentials = '%s:%s' % (request.proxy_username, - request.proxy_password) + credentials = httputil.encode_username_password(request.proxy_username, + request.proxy_password) curl.setopt(pycurl.PROXYUSERPWD, credentials) if (request.proxy_auth_mode is None or @@ -441,8 +441,6 @@ class CurlAsyncHTTPClient(AsyncHTTPClient): curl.setopt(pycurl.INFILESIZE, len(request.body or '')) if request.auth_username is not None: - userpwd = "%s:%s" % (request.auth_username, request.auth_password or '') - if request.auth_mode is None or request.auth_mode == "basic": curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC) elif request.auth_mode == "digest": @@ -450,7 +448,9 @@ class CurlAsyncHTTPClient(AsyncHTTPClient): else: raise ValueError("Unsupported auth_mode %s" % request.auth_mode) - curl.setopt(pycurl.USERPWD, native_str(userpwd)) + userpwd = httputil.encode_username_password(request.auth_username, + request.auth_password) + curl.setopt(pycurl.USERPWD, userpwd) curl_log.debug("%s %s (username: %r)", request.method, request.url, request.auth_username) else: diff --git a/tornado/httputil.py b/tornado/httputil.py index 22a64c31..d1ace5a8 100644 --- a/tornado/httputil.py +++ b/tornado/httputil.py @@ -29,11 +29,12 @@ import email.utils import numbers import re import time +import unicodedata import warnings from tornado.escape import native_str, parse_qs_bytes, utf8 from tornado.log import gen_log -from tornado.util import ObjectDict, PY3 +from tornado.util import ObjectDict, PY3, unicode_type if PY3: import http.cookies as Cookie @@ -949,6 +950,20 @@ def _encode_header(key, pdict): return '; '.join(out) +def encode_username_password(username, password): + """Encodes a username/password pair in the format used by HTTP auth. + + The return value is a byte string in the form ``username:password``. + + .. versionadded:: 5.1 + """ + if isinstance(username, unicode_type): + username = unicodedata.normalize('NFC', username) + if isinstance(password, unicode_type): + password = unicodedata.normalize('NFC', password) + return utf8(username) + b":" + utf8(password) + + def doctests(): import doctest return doctest.DocTestSuite() diff --git a/tornado/simple_httpclient.py b/tornado/simple_httpclient.py index 4df4898a..35c71936 100644 --- a/tornado/simple_httpclient.py +++ b/tornado/simple_httpclient.py @@ -1,6 +1,6 @@ from __future__ import absolute_import, division, print_function -from tornado.escape import utf8, _unicode +from tornado.escape import _unicode from tornado import gen from tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy from tornado import httputil @@ -308,9 +308,9 @@ class _HTTPConnection(httputil.HTTPMessageDelegate): if self.request.auth_mode not in (None, "basic"): raise ValueError("unsupported auth_mode %s", self.request.auth_mode) - auth = utf8(username) + b":" + utf8(password) - self.request.headers["Authorization"] = (b"Basic " + - base64.b64encode(auth)) + self.request.headers["Authorization"] = ( + b"Basic " + base64.b64encode( + httputil.encode_username_password(username, password))) if self.request.user_agent: self.request.headers["User-Agent"] = self.request.user_agent if not self.request.allow_nonstandard_methods:
Unable to use non-ascii characters in user/password for basic auth in curl_httpclient Steps to reproduce (Python 3.4): 1. Create tornado.httpclient.HTTPRequest with auth_username or auth_password which contains non-ascii (lower range, 0-128), for example pound sterling £ (which is 153 in ascii). 2. Execute curl_httpclient fetch using that request Expected result: 1. The request is successfully completed Actual result: 2. HTTP 599 is returned and internal exception is: 'ascii' codec can't encode character '\xa3' in position 55: ordinal not in range(128) I am not sure if I am not aware of the proper solution, but I have tried providing bytes as auth_password, but it does not solve the issue because https://github.com/tornadoweb/tornado/blob/master/tornado/curl_httpclient.py#L438 internally uses string formatting. Reading through pycurl docs (http://pycurl.io/docs/latest/unicode.html) suggests that for Python3 bytes array should be used when using curl setopt. It seems like Python3 vs Python2 issue?
tornadoweb/tornado
diff --git a/tornado/test/curl_httpclient_test.py b/tornado/test/curl_httpclient_test.py index b7a85952..4230d4cd 100644 --- a/tornado/test/curl_httpclient_test.py +++ b/tornado/test/curl_httpclient_test.py @@ -32,13 +32,15 @@ class CurlHTTPClientCommonTestCase(httpclient_test.HTTPClientCommonTestCase): class DigestAuthHandler(RequestHandler): + def initialize(self, username, password): + self.username = username + self.password = password + def get(self): realm = 'test' opaque = 'asdf' # Real implementations would use a random nonce. nonce = "1234" - username = 'foo' - password = 'bar' auth_header = self.request.headers.get('Authorization', None) if auth_header is not None: @@ -53,9 +55,9 @@ class DigestAuthHandler(RequestHandler): assert param_dict['realm'] == realm assert param_dict['opaque'] == opaque assert param_dict['nonce'] == nonce - assert param_dict['username'] == username + assert param_dict['username'] == self.username assert param_dict['uri'] == self.request.path - h1 = md5(utf8('%s:%s:%s' % (username, realm, password))).hexdigest() + h1 = md5(utf8('%s:%s:%s' % (self.username, realm, self.password))).hexdigest() h2 = md5(utf8('%s:%s' % (self.request.method, self.request.path))).hexdigest() digest = md5(utf8('%s:%s:%s' % (h1, nonce, h2))).hexdigest() @@ -88,7 +90,8 @@ class CurlHTTPClientTestCase(AsyncHTTPTestCase): def get_app(self): return Application([ - ('/digest', DigestAuthHandler), + ('/digest', DigestAuthHandler, {'username': 'foo', 'password': 'bar'}), + ('/digest_non_ascii', DigestAuthHandler, {'username': 'foo', 'password': 'barユ£'}), ('/custom_reason', CustomReasonHandler), ('/custom_fail_reason', CustomFailReasonHandler), ]) @@ -143,3 +146,8 @@ class CurlHTTPClientTestCase(AsyncHTTPTestCase): # during the setup phase doesn't lead the request to # be dropped on the floor. response = self.fetch(u'/ユニコード', raise_error=True) + + def test_digest_auth_non_ascii(self): + response = self.fetch('/digest_non_ascii', auth_mode='digest', + auth_username='foo', auth_password='barユ£') + self.assertEqual(response.body, b'ok') diff --git a/tornado/test/httpclient_test.py b/tornado/test/httpclient_test.py index 60c8f490..fb8b12d5 100644 --- a/tornado/test/httpclient_test.py +++ b/tornado/test/httpclient_test.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import base64 @@ -8,6 +9,7 @@ import sys import threading import datetime from io import BytesIO +import unicodedata from tornado.escape import utf8, native_str from tornado import gen @@ -237,6 +239,7 @@ Transfer-Encoding: chunked self.assertIs(exc_info[0][0], ZeroDivisionError) def test_basic_auth(self): + # This test data appears in section 2 of RFC 7617. self.assertEqual(self.fetch("/auth", auth_username="Aladdin", auth_password="open sesame").body, b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==") @@ -247,6 +250,20 @@ Transfer-Encoding: chunked auth_mode="basic").body, b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==") + def test_basic_auth_unicode(self): + # This test data appears in section 2.1 of RFC 7617. + self.assertEqual(self.fetch("/auth", auth_username="test", + auth_password="123£").body, + b"Basic dGVzdDoxMjPCow==") + + # The standard mandates NFC. Give it a decomposed username + # and ensure it is normalized to composed form. + username = unicodedata.normalize("NFD", u"josé") + self.assertEqual(self.fetch("/auth", + auth_username=username, + auth_password="səcrət").body, + b"Basic am9zw6k6c8mZY3LJmXQ=") + def test_unsupported_auth_mode(self): # curl and simple clients handle errors a bit differently; the # important thing is that they don't fall back to basic auth
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 3 }
5.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 flake8==5.0.4 importlib-metadata==4.2.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pycodestyle==2.9.1 pyflakes==2.5.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work -e git+https://github.com/tornadoweb/tornado.git@6410cd98c1a5e938246a17cac0769f689ed471c5#egg=tornado typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: tornado channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - flake8==5.0.4 - importlib-metadata==4.2.0 - mccabe==0.7.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 prefix: /opt/conda/envs/tornado
[ "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_basic_auth_unicode" ]
[]
[ "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_304_with_content_length", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_all_methods", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_basic_auth", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_basic_auth_explicit_mode", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_body_encoding", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_body_sanity_checks", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_chunked", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_chunked_close", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_configure_defaults", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_credentials_in_url", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_final_callback_stack_context", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_follow_redirect", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_http_error", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_http_error_no_raise", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_future_interface", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_callback", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_callback_stack_context", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_header_types", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_hello_world", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_multi_line_headers", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_non_ascii_header", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_patch_receives_payload", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_post", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_put_307", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_reuse_request_from_response", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_streaming_callback", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_streaming_stack_context", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_types", "tornado/test/httpclient_test.py::HTTPClientCommonTestCase::test_unsupported_auth_mode", "tornado/test/httpclient_test.py::RequestProxyTest::test_bad_attribute", "tornado/test/httpclient_test.py::RequestProxyTest::test_both_set", "tornado/test/httpclient_test.py::RequestProxyTest::test_default_set", "tornado/test/httpclient_test.py::RequestProxyTest::test_defaults_none", "tornado/test/httpclient_test.py::RequestProxyTest::test_neither_set", "tornado/test/httpclient_test.py::RequestProxyTest::test_request_set", "tornado/test/httpclient_test.py::HTTPResponseTestCase::test_str", "tornado/test/httpclient_test.py::SyncHTTPClientTest::test_sync_client", "tornado/test/httpclient_test.py::SyncHTTPClientTest::test_sync_client_error", "tornado/test/httpclient_test.py::HTTPRequestTestCase::test_body", "tornado/test/httpclient_test.py::HTTPRequestTestCase::test_body_setter", "tornado/test/httpclient_test.py::HTTPRequestTestCase::test_headers", "tornado/test/httpclient_test.py::HTTPRequestTestCase::test_headers_setter", "tornado/test/httpclient_test.py::HTTPRequestTestCase::test_if_modified_since", "tornado/test/httpclient_test.py::HTTPRequestTestCase::test_null_headers_setter", "tornado/test/httpclient_test.py::HTTPErrorTestCase::test_copy", "tornado/test/httpclient_test.py::HTTPErrorTestCase::test_error_with_response", "tornado/test/httpclient_test.py::HTTPErrorTestCase::test_plain_error" ]
[]
Apache License 2.0
2,559
[ "tornado/curl_httpclient.py", "tornado/httputil.py", "tornado/simple_httpclient.py" ]
[ "tornado/curl_httpclient.py", "tornado/httputil.py", "tornado/simple_httpclient.py" ]
akolar__ogn-lib-21
695f77174bd5a1ef7bdba53c03e3e905aaaec521
2018-05-21 10:11:40
695f77174bd5a1ef7bdba53c03e3e905aaaec521
diff --git a/ogn_lib/parser.py b/ogn_lib/parser.py index f3b51ae..5842f01 100644 --- a/ogn_lib/parser.py +++ b/ogn_lib/parser.py @@ -778,3 +778,44 @@ class Capturs(Parser): @staticmethod def _preprocess_message(message): return message.strip('/') + + +class Fanet(Parser): + """ + Parser for Fanet-formatted APRS messages. + """ + + __destto__ = ['OGNFNT', 'OGNFNT-1'] + + @staticmethod + def _parse_protocol_specific(comment): + """ + Parses the comment string from Fanet's APRS messages. + :param str comment: comment string + :return: parsed comment + :rtype: dict + """ + + fields = comment.split(' ') + + if len(fields) != 3: + raise exceptions.ParseError('Fanet comment incorrectly formatted:' + ' received {}'.format(comment)) + + lat_dig = int(fields[0][2]) + lon_dig = int(fields[0][3]) + update_position = [ + { + 'target': 'latitude', + 'function': Parser._get_location_update_func(lat_dig) + }, { + 'target': 'longitude', + 'function': Parser._get_location_update_func(lon_dig) + } + ] + + return { + '_update': update_position, + 'id': fields[1], + 'vertical_speed': Parser._convert_fpm_to_ms(fields[2]) + }
Add support for Fanet (OGNFNT) See https://github.com/glidernet/ogn-aprs-protocol/pull/5/commits/1be92993c4d50db4329371d18385a29782ddc4fa for detailed message format.
akolar/ogn-lib
diff --git a/tests/messages.txt b/tests/messages.txt index 72b0c93..18ce385 100644 --- a/tests/messages.txt +++ b/tests/messages.txt @@ -80,3 +80,8 @@ FLRDDF944>OGSPID,qAS,SPIDER:/213930h3322.17S/07033.97W'332/028/A=003428 id300234 ICA3E7540>OGSPOT,qAS,SPOT:/161427h1448.35S/04610.86W'000/000/A=008677 id0-2860357 SPOT3 GOOD ICA3E7540>OGSPOT,qAS,SPOT:/162923h1431.99S/04604.33W'000/000/A=006797 id0-2860357 SPOT3 GOOD ICA3E7540>OGSPOT,qAS,SPOT:/163421h1430.38S/04604.43W'000/000/A=007693 id0-2860357 SPOT3 GOOD +FNT1103CE>OGNFNT,qAS,FNB1103CE:/183727h5057.94N/00801.00Eg355/002/A=001042 !W10! id1E1103CE +03fpm +FNT1103CE>OGNFNT,qAS,FNB1103CE:/183729h5057.94N/00801.00Eg354/001/A=001042 !W10! id1E1103CE +07fpm +FNT1103CE>OGNFNT,qAS,FNB1103CE:/183731h5057.94N/00801.00Eg354/001/A=001042 !W10! id1E1103CE +05fpm +FNT1103CE>OGNFNT,qAS,FNB1103CE:/183734h5057.94N/00801.00Eg354/001/A=001042 !W30! id1E1103CE -10fpm +FNT1103CE>OGNFNT,qAS,FNB1103CE:/183736h5057.94N/00801.00Eg354/001/A=001042 !W40! id1E1103CE -02fpm diff --git a/tests/test_parser.py b/tests/test_parser.py index 937c193..ca88c62 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -580,6 +580,32 @@ class TestCapturs: parser.Capturs._preprocess_message.assert_called_once_with(msg) +class TestFanet: + + def test_parse_protocol_specific(self): + data = parser.Fanet._parse_protocol_specific('!W30! id1E1103CE 180fpm') + + assert data['id'] == 'id1E1103CE' + assert abs(data['vertical_speed'] - 0.9144) < 0.01 + assert (list(map(lambda x: x['target'], data['_update'])) == + ['latitude', 'longitude']) + + def test_parse_protocol_specific_fail(self): + with pytest.raises(exceptions.ParseError): + parser.Fanet._parse_protocol_specific('id1E1103CE') + + with pytest.raises(exceptions.ParseError): + parser.Fanet._parse_protocol_specific( + '!W30! id1E1103CE -02fpm x') + + def test_registered(self, mocker): + mocker.spy(parser.Fanet, '_parse_protocol_specific') + parser.Parser('FNT1103CE>OGNFNT,qAS,FNB1103CE:/183734h5057.94N/' + '00801.00Eg354/001/A=001042 !W30! id1E1103CE -10fpm') + parser.Fanet._parse_protocol_specific.assert_called_once_with( + '!W30! id1E1103CE -10fpm') + + class TestServerParser: def test_parse_message_beacon(self, mocker):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work -e git+https://github.com/akolar/ogn-lib.git@695f77174bd5a1ef7bdba53c03e3e905aaaec521#egg=ogn_lib packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: ogn-lib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/ogn-lib
[ "tests/test_parser.py::TestFanet::test_parse_protocol_specific", "tests/test_parser.py::TestFanet::test_parse_protocol_specific_fail" ]
[]
[ "tests/test_parser.py::TestParserBase::test_new_no_id", "tests/test_parser.py::TestParserBase::test_new_single_id", "tests/test_parser.py::TestParserBase::test_new_multi_id", "tests/test_parser.py::TestParserBase::test_no_destto", "tests/test_parser.py::TestParserBase::test_new_wrong_id", "tests/test_parser.py::TestParserBase::test_set_default", "tests/test_parser.py::TestParserBase::test_call_no_parser", "tests/test_parser.py::TestParser::test_pattern_header", "tests/test_parser.py::TestParser::test_pattern_header_matches_all", "tests/test_parser.py::TestParser::test_pattern_location", "tests/test_parser.py::TestParser::test_pattern_location_matches_all", "tests/test_parser.py::TestParser::test_pattern_comment_common", "tests/test_parser.py::TestParser::test_pattern_comment_common_matches_all", "tests/test_parser.py::TestParser::test_pattern_all", "tests/test_parser.py::TestParser::test_pattern_all_matches_all", "tests/test_parser.py::TestParser::test_parse_msg_no_match", "tests/test_parser.py::TestParser::test_preprocess_message", "tests/test_parser.py::TestParser::test_parse_digipeaters", "tests/test_parser.py::TestParser::test_parse_digipeaters_relayed", "tests/test_parser.py::TestParser::test_parse_digipeaters_unknown_format", "tests/test_parser.py::TestParser::test_parse_heading_speed", "tests/test_parser.py::TestParser::test_parse_heading_speed_both_missing", "tests/test_parser.py::TestParser::test_parse_heading_speed_null_input", "tests/test_parser.py::TestParser::test_parse_altitude", "tests/test_parser.py::TestParser::test_parse_altitude_missing", "tests/test_parser.py::TestParser::test_parse_attrs", "tests/test_parser.py::TestParser::test_parse_time_past", "tests/test_parser.py::TestParser::test_parse_time_future", "tests/test_parser.py::TestParser::test_parse_datetime", "tests/test_parser.py::TestParser::test_parse_location_sign", "tests/test_parser.py::TestParser::test_parse_location_value", "tests/test_parser.py::TestParser::test_parse_protocol_specific", "tests/test_parser.py::TestParser::test_conv_fpm_to_ms", "tests/test_parser.py::TestParser::test_conv_fpm_to_ms_sign", "tests/test_parser.py::TestParser::test_get_location_update_func", "tests/test_parser.py::TestParser::test_update_location_decimal_same", "tests/test_parser.py::TestParser::test_update_location_decimal_positive", "tests/test_parser.py::TestParser::test_update_location_decimal_negative", "tests/test_parser.py::TestParser::test_update_data", "tests/test_parser.py::TestParser::test_update_data_missing", "tests/test_parser.py::TestAPRS::test_parse_protocol_specific", "tests/test_parser.py::TestAPRS::test_parse_id_string", "tests/test_parser.py::TestNaviter::test_parse_protocol_specific", "tests/test_parser.py::TestNaviter::test_parse_id_string", "tests/test_parser.py::TestSpot::test_parse_protocol_specific", "tests/test_parser.py::TestSpot::test_parse_protocol_specific_fail", "tests/test_parser.py::TestSpider::test_parse_protocol_specific", "tests/test_parser.py::TestSpider::test_parse_protocol_specific_fail", "tests/test_parser.py::TestSkylines::test_parse_protocol_specific", "tests/test_parser.py::TestSkylines::test_parse_protocol_specific_fail", "tests/test_parser.py::TestLT24::test_parse_protocol_specific", "tests/test_parser.py::TestLT24::test_parse_protocol_specific_fail", "tests/test_parser.py::TestCapturs::test_process", "tests/test_parser.py::TestCapturs::test_preprocess" ]
[]
MIT License
2,561
[ "ogn_lib/parser.py" ]
[ "ogn_lib/parser.py" ]
discos__simulators-144
41d9506ba64a92ca6d5e81737180f4f7220acea9
2018-05-21 15:43:22
41d9506ba64a92ca6d5e81737180f4f7220acea9
coveralls: [![Coverage Status](https://coveralls.io/builds/17087856/badge)](https://coveralls.io/builds/17087856) Coverage decreased (-0.02%) to 99.101% when pulling **b5ea4d0cdb68bea0d08f88d50d8a93d89619f6a4 on fix-issue-142** into **41d9506ba64a92ca6d5e81737180f4f7220acea9 on master**.
diff --git a/scripts/discos-simulator b/scripts/discos-simulator index b9450ee..9d64de8 100755 --- a/scripts/discos-simulator +++ b/scripts/discos-simulator @@ -15,8 +15,7 @@ def system_from_arg(system_name): try: return importlib.import_module('simulators.%s' % system_name) except ImportError: - raise ArgumentTypeError('system "%s" unavailable' % system_name) - + raise ArgumentTypeError('System "%s" unavailable.' % system_name) parser = ArgumentParser() parser.add_argument( @@ -25,12 +24,33 @@ parser.add_argument( required=True, help='System name: active_surface, acu, ...', ) +parser.add_argument( + '-t', '--type', + required=False, + help='System configuration type: IFD_14_channels for if_distributor, ...', +) parser.add_argument( 'action', - choices=['start', 'stop']) -args = parser.parse_args() + choices=['start', 'stop'] +) +args = parser.parse_args() +if args.type: + try: + systems = getattr(args.system, 'systems') + except AttributeError: + raise ArgumentTypeError( + ('System %s has no configurations other than the default one. ' + % args.system.__name__.rsplit('.', 1)[1]) + + "Omit the '--type' flag to start the simulator properly." + ) + if args.type not in systems: + raise ArgumentTypeError( + 'Configuration %s for system %s not found.' + % (args.type, args.system.__name__.rsplit('.', 1)[1]) + ) + args.system.system_type = args.type simulator = Simulator(args.system) if args.action == 'start': diff --git a/simulators/if_distributor/IFD_14_channels.py b/simulators/if_distributor/IFD_14_channels.py new file mode 100644 index 0000000..a8a1581 --- /dev/null +++ b/simulators/if_distributor/IFD_14_channels.py @@ -0,0 +1,131 @@ +from simulators.common import ListeningSystem + + +class System(ListeningSystem): + + header = b'#' + tail = b'\n' + max_msg_length = 12 # b'#AAA 99 999\n' + # The dictionary devices has the device types as keys, + # and a dictionary as value. The value has the address as + # key and the allowed values as value + allowed_commands = ['ATT', 'SWT'] + max_channels = 96 + max_att = 31.75 + att_step = 0.25 + max_att_multiplier = max_att / att_step + channels = [max_att_multiplier] * max_channels + switched = False + version = b'SRT IF Distributor Simulator 1.0' + + def __init__(self): + self.ciao = 'ciao' + self.msg = b'' + self._set_default() + + def _set_default(self): + self.channels = [self.max_att_multiplier] * self.max_channels + self.switched = False + + def parse(self, byte): + self.msg += byte + if len(self.msg) == 1: + if byte == self.header: + return True # Got the header + else: + self.msg = b'' + return False + elif len(self.msg) < self.max_msg_length: + if byte != self.tail: + return True + elif len(self.msg) == self.max_msg_length: + if byte != self.tail: + self.msg = b'' + raise ValueError( + 'message too long: max length should be %d.' % + self.max_msg_length + ) + + msg = self.msg[1:-1] # Remove the header and tail + self.msg = b'' + return self._execute(msg) + + def _execute(self, msg): + if b' ' in msg and b'?' not in msg: # Setup request + try: + command, channel, value = msg.split() + except ValueError: + raise ValueError( + 'the setup message must have three items: ' + 'command, channel, and value.' + ) + + if command not in self.allowed_commands: + raise ValueError( + 'command %s not in %s' + % (command, self.allowed_commands) + ) + + try: + channel = int(channel) + except ValueError: + raise ValueError('the channel ID must be an integer.') + + if channel >= self.max_channels or channel < 0: + raise ValueError( + 'channel %d does not exist.' % channel) + + try: + value = int(value) + except ValueError: + raise ValueError('the command value must be an integer.') + + if command == 'ATT': + if value < 0 or value >= self.max_att_multiplier: + raise ValueError('value %d not allowed' % value) + else: + self.channels[channel] = value + elif command == 'SWT': + if value == 0: + self.switched = False + elif value == 1: + self.switched = True + else: + raise ValueError( + 'SWT command accepts only values 00 or 01') + return b'' + elif b' ' in msg and b'?' in msg: # Get request + msg = msg.rstrip('?') + try: + command, channel = msg.split() + except ValueError: + raise ValueError( + 'the get message must have two items: ' + 'command and channel.' + ) + + try: + channel = int(channel) + except ValueError: + raise ValueError('the channel ID must be an integer.') + + if channel >= self.max_channels or channel < 0: + raise ValueError( + 'channel %d does not exist.' % channel) + else: + if command == 'ATT': + return b'#%s\n' % str( + self.channels[channel] * self.att_step) + elif command == 'SWT': + return b'#%s\n' % (1 if self.switched else 0) + else: + raise ValueError( + 'command %s not in %s' + % (command, self.allowed_commands)) + elif msg == b'*IDN?': # IDN request + return self.version + elif msg == b'*RST': # RST command + self._set_default() + return None + else: # Not expected command + return b'#COMMAND UNKNOWN\n' diff --git a/simulators/if_distributor/__init__.py b/simulators/if_distributor/__init__.py index a73b277..ba0f9a2 100644 --- a/simulators/if_distributor/__init__.py +++ b/simulators/if_distributor/__init__.py @@ -1,5 +1,4 @@ -from simulators.common import ListeningSystem - +from simulators import utils # Each system module (like active_surface.py, acu.py, etc.) has to # define a list called servers.s This list contains tuples @@ -9,131 +8,18 @@ from simulators.common import ListeningSystem # get_message method, while args is a tuple of optional extra arguments. servers = [(('127.0.0.1', 12000), (), ())] +systems = utils.get_systems() +default_system_type = 'IFD_14_channels' +system_type = default_system_type -class System(ListeningSystem): - - header = b'#' - tail = b'\n' - max_msg_length = 12 # b'#AAA 99 999\n' - # The dictionary devices has the device types as keys, - # and a dictionary as value. The value has the address as - # key and the allowed values as value - allowed_commands = ['ATT', 'SWT'] - max_channels = 96 - max_att = 31.75 - att_step = 0.25 - max_att_multiplier = max_att / att_step - channels = [max_att_multiplier] * max_channels - switched = False - version = b'SRT IF Distributor Simulator 1.0' - - def __init__(self): - self.msg = b'' - self._set_default() - - def _set_default(self): - self.channels = [self.max_att_multiplier] * self.max_channels - self.switched = False - - def parse(self, byte): - self.msg += byte - if len(self.msg) == 1: - if byte == self.header: - return True # Got the header - else: - self.msg = b'' - return False - elif len(self.msg) < self.max_msg_length: - if byte != self.tail: - return True - elif len(self.msg) == self.max_msg_length: - if byte != self.tail: - self.msg = b'' - raise ValueError( - 'message too long: max length should be %d.' % - self.max_msg_length - ) - - msg = self.msg[1:-1] # Remove the header and tail - self.msg = b'' - return self._execute(msg) - - def _execute(self, msg): - if b' ' in msg and b'?' not in msg: # Setup request - try: - command, channel, value = msg.split() - except ValueError: - raise ValueError( - 'the setup message must have three items: ' - 'command, channel, and value.' - ) - - if command not in self.allowed_commands: - raise ValueError( - 'command %s not in %s' - % (command, self.allowed_commands) - ) - - try: - channel = int(channel) - except ValueError: - raise ValueError('the channel ID must be an integer.') - - if channel >= self.max_channels or channel < 0: - raise ValueError( - 'channel %d does not exist.' % channel) - - try: - value = int(value) - except ValueError: - raise ValueError('the command value must be an integer.') - if command == 'ATT': - if value < 0 or value >= self.max_att_multiplier: - raise ValueError('value %d not allowed' % value) - else: - self.channels[channel] = value - elif command == 'SWT': - if value == 0: - self.switched = False - elif value == 1: - self.switched = True - else: - raise ValueError( - 'SWT command accepts only values 00 or 01') - return b'' - elif b' ' in msg and b'?' in msg: # Get request - msg = msg.rstrip('?') - try: - command, channel = msg.split() - except ValueError: - raise ValueError( - 'the get message must have two items: ' - 'command and channel.' - ) +class System(object): - try: - channel = int(channel) - except ValueError: - raise ValueError('the channel ID must be an integer.') + def __new__(cls, *args): + if system_type not in systems: + raise ValueError( + 'Configuration %s for system if_distributor not found.' + % system_type + ) - if channel >= self.max_channels or channel < 0: - raise ValueError( - 'channel %d does not exist.' % channel) - else: - if command == 'ATT': - return b'#%s\n' % str( - self.channels[channel] * self.att_step) - elif command == 'SWT': - return b'#%s\n' % (1 if self.switched else 0) - else: - raise ValueError( - 'command %s not in %s' - % (command, self.allowed_commands)) - elif msg == b'*IDN?': # IDN request - return self.version - elif msg == b'*RST': # RST command - self._set_default() - return None - else: # Not expected command - return b'#COMMAND UNKNOWN\n' + return systems[system_type].System(*args) diff --git a/simulators/utils.py b/simulators/utils.py index a359a16..d5765ef 100644 --- a/simulators/utils.py +++ b/simulators/utils.py @@ -1,7 +1,11 @@ #!/usr/bin/python import math import struct +import importlib +import inspect +import os from datetime import datetime, timedelta +from simulators.common import BaseSystem def checksum(msg): @@ -442,6 +446,24 @@ def day_percentage(date=None): return float(microseconds) / 86400000000 +def get_systems(): + module = inspect.getmodule(inspect.stack()[1][0]) + module_path = module.__file__.rsplit('/', 1)[0] + '/' + systems = {} + for f in os.listdir(os.path.dirname(module_path)): + if f[-3:] == '.py' and f != '__init__.py': + mod = importlib.import_module( + '%s.%s' % (module.__name__, f[:-3]) + ) + for _, obj in inspect.getmembers(mod): + if (inspect.isclass(obj) + and obj is not BaseSystem + and issubclass(obj, BaseSystem) + and BaseSystem not in obj.__bases__): + systems[mod.__name__.rsplit('.', 1)[1]] = mod + return systems + + if __name__ == '__main__': import doctest doctest.testmod()
Extend the `discos-simulator` script and make it able to launch different system configurations. In order to develop the new `if_distributor` simulator it could be useful if the `discos-simulator` script can launch different configurations of a system instead of writing another system with a slightly different name.
discos/simulators
diff --git a/tests/test_if_distributor.py b/tests/test_if_distributor.py index a663a11..95c624a 100644 --- a/tests/test_if_distributor.py +++ b/tests/test_if_distributor.py @@ -2,8 +2,15 @@ import unittest from simulators import if_distributor +class TestIFDistributorUnknownType(unittest.TestCase): -class TestIFDistributorParse(unittest.TestCase): + def test_unknown_type(self): + if_distributor.system_type = 'unknown' + with self.assertRaises(ValueError): + self.system = if_distributor.System() + + +class TestIFDistributor14Channels(unittest.TestCase): def setUp(self): self.system = if_distributor.System()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "coverage", "prospector", "sphinx", "sphinx_rtd_theme", "tox", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 astroid==3.3.9 babel==2.17.0 cachetools==5.5.2 certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 colorama==0.4.6 coverage==7.8.0 dill==0.3.9 -e git+https://github.com/discos/simulators.git@41d9506ba64a92ca6d5e81737180f4f7220acea9#egg=discos_simulators distlib==0.3.9 docutils==0.21.2 dodgy==0.2.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 flake8==7.2.0 flake8-polyfill==1.0.2 gitdb==4.0.12 GitPython==3.1.44 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work isort==6.0.1 Jinja2==3.1.6 MarkupSafe==3.0.2 mccabe==0.7.0 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pep8-naming==0.10.0 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work prospector==1.16.1 pycodestyle==2.13.0 pydocstyle==6.3.0 pyflakes==3.3.2 Pygments==2.19.1 pylint==3.3.6 pylint-celery==0.3 pylint-django==2.6.1 pylint-plugin-utils==0.8.2 pyproject-api==1.9.0 pytest @ file:///croot/pytest_1738938843180/work PyYAML==6.0.2 requests==2.32.3 requirements-detector==1.3.2 scipy==1.13.1 semver==3.0.4 setoptconf-tmp==0.3.1 smmap==5.0.2 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 toml==0.10.2 tomli==2.2.1 tomlkit==0.13.2 tox==4.25.0 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3 zipp==3.21.0
name: simulators channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - astroid==3.3.9 - babel==2.17.0 - cachetools==5.5.2 - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - colorama==0.4.6 - coverage==7.8.0 - dill==0.3.9 - distlib==0.3.9 - docutils==0.21.2 - dodgy==0.2.1 - filelock==3.18.0 - flake8==7.2.0 - flake8-polyfill==1.0.2 - gitdb==4.0.12 - gitpython==3.1.44 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - isort==6.0.1 - jinja2==3.1.6 - markupsafe==3.0.2 - mccabe==0.7.0 - numpy==2.0.2 - pep8-naming==0.10.0 - platformdirs==4.3.7 - prospector==1.16.1 - pycodestyle==2.13.0 - pydocstyle==6.3.0 - pyflakes==3.3.2 - pygments==2.19.1 - pylint==3.3.6 - pylint-celery==0.3 - pylint-django==2.6.1 - pylint-plugin-utils==0.8.2 - pyproject-api==1.9.0 - pyyaml==6.0.2 - requests==2.32.3 - requirements-detector==1.3.2 - scipy==1.13.1 - semver==3.0.4 - setoptconf-tmp==0.3.1 - smmap==5.0.2 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - toml==0.10.2 - tomli==2.2.1 - tomlkit==0.13.2 - tox==4.25.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - virtualenv==20.29.3 - zipp==3.21.0 prefix: /opt/conda/envs/simulators
[ "tests/test_if_distributor.py::TestIFDistributorUnknownType::test_unknown_type" ]
[ "tests/test_if_distributor.py::TestIFDistributor14Channels::test_enable_and_disable_switch", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_get_channel_not_allowed", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_get_channel_not_integer", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_get_switch", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_idn_command", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_max_msg_length_reached", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_rst", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_set_and_get_switch", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_set_and_get_value", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_set_switch", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_set_wrong_switch", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_setup_channel_not_allowed", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_setup_channel_not_integer", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_setup_sets_the_value", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_setup_value_not_allowed", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_setup_value_not_integer", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_wrong_command", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_wrong_get_channel", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_wrong_number_of_get_items", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_wrong_number_of_setup_items", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_wrong_setup_command" ]
[]
[ "tests/test_if_distributor.py::TestIFDistributor14Channels::test_default_setup", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_get_header", "tests/test_if_distributor.py::TestIFDistributor14Channels::test_wrong_header" ]
null
2,562
[ "scripts/discos-simulator", "simulators/if_distributor/IFD_14_channels.py", "simulators/if_distributor/__init__.py", "simulators/utils.py" ]
[ "scripts/discos-simulator", "simulators/if_distributor/IFD_14_channels.py", "simulators/if_distributor/__init__.py", "simulators/utils.py" ]
great-expectations__great_expectations-296
abb6d090c69a7793b98d4c8d3cbd048d614fc657
2018-05-21 16:06:25
10e1792ae5f9d250d5393bc14b488e189358cccc
diff --git a/great_expectations/dataset/pandas_dataset.py b/great_expectations/dataset/pandas_dataset.py index 5b3b5447e..c53c23a11 100644 --- a/great_expectations/dataset/pandas_dataset.py +++ b/great_expectations/dataset/pandas_dataset.py @@ -250,7 +250,7 @@ class PandasDataset(MetaPandasDataset, pd.DataFrame): @property def _constructor(self): - return PandasDataset + return self.__class__ # Do we need to define _constructor_sliced and/or _constructor_expanddim? See http://pandas.pydata.org/pandas-docs/stable/internals.html#subclassing-pandas-data-structures
When calling groupby on subclassed PandasDataset, groups revert to PandasDataset It's possible I'm doing something wrong when subclassing, but: I'm subclassing PandasDataset to create custom expectations. When calling the groupby method on these custom datasets, the groups revert to the base PandasDataset type (and lose the custom expectation methods). ``` import great_expectations as ge import pandas as pd from great_expectations.dataset import Dataset, PandasDataset class SubclassPandasDataset(PandasDataset, pd.DataFrame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) df = pd.DataFrame([{'a': 1}, {'a': 2}, {'a':1}]) sdf = ge._convert_to_dataset_class(df, SubclassPandasDataset) print(type(sdf)) for ix, g in sdf.groupby('a'): print(type(g)) ``` output: <class '__main__.SubclassPandasDataset'> <class 'great_expectations.dataset.pandas_dataset.PandasDataset'> <class 'great_expectations.dataset.pandas_dataset.PandasDataset'>
great-expectations/great_expectations
diff --git a/tests/test_pandas_dataset.py b/tests/test_pandas_dataset.py index 250c1e6e5..1bd3cc4c4 100644 --- a/tests/test_pandas_dataset.py +++ b/tests/test_pandas_dataset.py @@ -1032,5 +1032,30 @@ class TestPandasDataset(unittest.TestCase): self.assertIsInstance(sub1, ge.dataset.PandasDataset) self.assertEqual(sub1.find_expectations(), exp1) + def test_subclass_pandas_subset_retains_subclass(self): + """A subclass of PandasDataset should still be that subclass after a Pandas subsetting operation""" + class CustomPandasDataset(ge.dataset.PandasDataset): + + @ge.dataset.MetaPandasDataset.column_map_expectation + def expect_column_values_to_be_odd(self, column): + return column.map(lambda x: x % 2 ) + + @ge.dataset.MetaPandasDataset.column_map_expectation + def expectation_that_crashes_on_sixes(self, column): + return column.map(lambda x: (x-6)/0 != "duck") + + df = CustomPandasDataset({ + 'all_odd': [1, 3, 5, 5, 5, 7, 9, 9, 9, 11], + 'mostly_odd': [1, 3, 5, 7, 9, 2, 4, 1, 3, 5], + 'all_even': [2, 4, 4, 6, 6, 6, 8, 8, 8, 8], + 'odd_missing': [1, 3, 5, None, None, None, None, 1, 3, None], + 'mixed_missing': [1, 3, 5, None, None, 2, 4, 1, 3, None], + 'all_missing': [None, None, None, None, None, None, None, None, None, None] + }) + + df2 = df.sample(frac=0.5) + self.assertTrue(type(df2) == type(df)) + + if __name__ == "__main__": unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alembic==1.7.7 anyio==3.6.2 apache-airflow==2.2.5 apache-airflow-providers-amazon==3.0.0 apache-airflow-providers-ftp==2.1.0 apache-airflow-providers-http==2.1.0 apache-airflow-providers-imap==2.2.1 apache-airflow-providers-sqlite==2.1.1 apispec==3.3.2 argcomplete==2.1.2 argh==0.27.2 asn1crypto==1.5.1 async-generator==1.10 attrs==20.3.0 Babel==2.11.0 beautifulsoup4==4.12.3 blinker==1.5 boto3==1.23.10 botocore==1.26.10 cached-property==1.5.2 cachelib==0.6.0 cattrs==1.0.0 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 click==7.1.2 clickclick==20.10.2 colorama==0.4.5 colorlog==6.9.0 commonmark==0.9.1 connexion==2.14.2 contextvars==2.4 coverage==6.2 croniter==6.0.0 cryptography==40.0.2 dataclasses==0.8 defusedxml==0.7.1 Deprecated==1.2.18 dill==0.3.4 dnspython==2.2.1 docutils==0.16 email-validator==1.3.1 Flask==1.1.4 Flask-AppBuilder==3.4.5 Flask-Babel==2.0.0 Flask-Caching==1.10.1 Flask-JWT-Extended==3.25.1 Flask-Login==0.4.1 Flask-OpenID==1.3.1 Flask-Session==0.4.0 Flask-SQLAlchemy==2.5.1 Flask-WTF==0.14.3 graphviz==0.19.1 -e git+https://github.com/great-expectations/great_expectations.git@abb6d090c69a7793b98d4c8d3cbd048d614fc657#egg=great_expectations gunicorn==21.2.0 h11==0.12.0 httpcore==0.14.7 httpx==0.22.0 idna==3.10 immutables==0.19 importlib-metadata==4.8.3 importlib-resources==5.4.0 inflection==0.5.1 iniconfig==1.1.1 iso8601==1.1.0 itsdangerous==1.1.0 Jinja2==2.11.3 jmespath==0.10.0 jsonpath-ng==1.7.0 jsonschema==3.2.0 lazy-object-proxy==1.7.1 lockfile==0.12.2 lxml==5.3.1 Mako==1.1.6 Markdown==3.3.7 MarkupSafe==2.0.1 marshmallow==3.14.1 marshmallow-enum==1.5.1 marshmallow-oneofschema==3.0.1 marshmallow-sqlalchemy==0.26.1 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pendulum==2.1.2 pep562==1.1 pluggy==1.0.0 ply==3.11 prison==0.2.1 psutil==5.9.8 py==1.11.0 pycparser==2.21 Pygments==2.14.0 PyJWT==1.7.1 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-daemon==2.3.2 python-dateutil==2.9.0.post0 python-nvd3==0.15.0 python-slugify==4.0.1 python3-openid==3.2.0 pytz==2025.2 pytzdata==2020.1 PyYAML==6.0.1 redshift-connector==2.0.918 requests==2.27.1 rfc3986==1.5.0 rich==12.6.0 s3transfer==0.5.2 scipy==1.5.4 scramp==1.4.1 setproctitle==1.2.3 six==1.17.0 sniffio==1.2.0 soupsieve==2.3.2.post1 SQLAlchemy==1.3.24 SQLAlchemy-JSONField==1.0.0 sqlalchemy-redshift==0.8.14 SQLAlchemy-Utils==0.41.1 swagger-ui-bundle==0.0.9 tabulate==0.8.10 tenacity==8.2.2 termcolor==1.1.0 text-unidecode==1.3 tomli==1.2.3 typing==3.7.4.3 typing_extensions==4.1.1 unicodecsv==0.14.1 urllib3==1.26.20 watchtower==2.0.1 Werkzeug==1.0.1 wrapt==1.16.0 WTForms==2.3.3 zipp==3.6.0
name: great_expectations channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alembic==1.7.7 - anyio==3.6.2 - apache-airflow==2.2.5 - apache-airflow-providers-amazon==3.0.0 - apache-airflow-providers-ftp==2.1.0 - apache-airflow-providers-http==2.1.0 - apache-airflow-providers-imap==2.2.1 - apache-airflow-providers-sqlite==2.1.1 - apispec==3.3.2 - argcomplete==2.1.2 - argh==0.27.2 - asn1crypto==1.5.1 - async-generator==1.10 - attrs==20.3.0 - babel==2.11.0 - beautifulsoup4==4.12.3 - blinker==1.5 - boto3==1.23.10 - botocore==1.26.10 - cached-property==1.5.2 - cachelib==0.6.0 - cattrs==1.0.0 - cffi==1.15.1 - charset-normalizer==2.0.12 - click==7.1.2 - clickclick==20.10.2 - colorama==0.4.5 - colorlog==6.9.0 - commonmark==0.9.1 - connexion==2.14.2 - contextvars==2.4 - coverage==6.2 - croniter==6.0.0 - cryptography==40.0.2 - dataclasses==0.8 - defusedxml==0.7.1 - deprecated==1.2.18 - dill==0.3.4 - dnspython==2.2.1 - docutils==0.16 - email-validator==1.3.1 - flask==1.1.4 - flask-appbuilder==3.4.5 - flask-babel==2.0.0 - flask-caching==1.10.1 - flask-jwt-extended==3.25.1 - flask-login==0.4.1 - flask-openid==1.3.1 - flask-session==0.4.0 - flask-sqlalchemy==2.5.1 - flask-wtf==0.14.3 - graphviz==0.19.1 - gunicorn==21.2.0 - h11==0.12.0 - httpcore==0.14.7 - httpx==0.22.0 - idna==3.10 - immutables==0.19 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - inflection==0.5.1 - iniconfig==1.1.1 - iso8601==1.1.0 - itsdangerous==1.1.0 - jinja2==2.11.3 - jmespath==0.10.0 - jsonpath-ng==1.7.0 - jsonschema==3.2.0 - lazy-object-proxy==1.7.1 - lockfile==0.12.2 - lxml==5.3.1 - mako==1.1.6 - markdown==3.3.7 - markupsafe==2.0.1 - marshmallow==3.14.1 - marshmallow-enum==1.5.1 - marshmallow-oneofschema==3.0.1 - marshmallow-sqlalchemy==0.26.1 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pendulum==2.1.2 - pep562==1.1 - pluggy==1.0.0 - ply==3.11 - prison==0.2.1 - psutil==5.9.8 - py==1.11.0 - pycparser==2.21 - pygments==2.14.0 - pyjwt==1.7.1 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-daemon==2.3.2 - python-dateutil==2.9.0.post0 - python-nvd3==0.15.0 - python-slugify==4.0.1 - python3-openid==3.2.0 - pytz==2025.2 - pytzdata==2020.1 - pyyaml==6.0.1 - redshift-connector==2.0.918 - requests==2.27.1 - rfc3986==1.5.0 - rich==12.6.0 - s3transfer==0.5.2 - scipy==1.5.4 - scramp==1.4.1 - setproctitle==1.2.3 - six==1.17.0 - sniffio==1.2.0 - soupsieve==2.3.2.post1 - sqlalchemy==1.3.24 - sqlalchemy-jsonfield==1.0.0 - sqlalchemy-redshift==0.8.14 - sqlalchemy-utils==0.41.1 - swagger-ui-bundle==0.0.9 - tabulate==0.8.10 - tenacity==8.2.2 - termcolor==1.1.0 - text-unidecode==1.3 - tomli==1.2.3 - typing==3.7.4.3 - typing-extensions==4.1.1 - unicodecsv==0.14.1 - urllib3==1.26.20 - watchtower==2.0.1 - werkzeug==1.0.1 - wrapt==1.16.0 - wtforms==2.3.3 - zipp==3.6.0 prefix: /opt/conda/envs/great_expectations
[ "tests/test_pandas_dataset.py::TestPandasDataset::test_subclass_pandas_subset_retains_subclass" ]
[]
[ "tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_dateutil_parseable", "tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_in_type_list", "tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_json_parseable", "tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_be_of_type", "tests/test_pandas_dataset.py::TestPandasDataset::test_expect_column_values_to_match_strftime_format", "tests/test_pandas_dataset.py::TestPandasDataset::test_expectation_decorator_summary_mode", "tests/test_pandas_dataset.py::TestPandasDataset::test_from_pandas", "tests/test_pandas_dataset.py::TestPandasDataset::test_from_pandas_expectations_config", "tests/test_pandas_dataset.py::TestPandasDataset::test_ge_pandas_automatic_failure_removal", "tests/test_pandas_dataset.py::TestPandasDataset::test_ge_pandas_concatenating", "tests/test_pandas_dataset.py::TestPandasDataset::test_ge_pandas_joining", "tests/test_pandas_dataset.py::TestPandasDataset::test_ge_pandas_merging", "tests/test_pandas_dataset.py::TestPandasDataset::test_ge_pandas_sampling", "tests/test_pandas_dataset.py::TestPandasDataset::test_ge_pandas_subsetting", "tests/test_pandas_dataset.py::TestPandasDataset::test_positional_arguments", "tests/test_pandas_dataset.py::TestPandasDataset::test_result_format_argument_in_decorators" ]
[]
Apache License 2.0
2,563
[ "great_expectations/dataset/pandas_dataset.py" ]
[ "great_expectations/dataset/pandas_dataset.py" ]
catmaid__catpy-25
ab4f858dda1144bec732738f406054248af7103d
2018-05-21 18:56:37
ab4f858dda1144bec732738f406054248af7103d
diff --git a/catpy/__init__.py b/catpy/__init__.py index feba40e..895073e 100644 --- a/catpy/__init__.py +++ b/catpy/__init__.py @@ -10,3 +10,5 @@ __all__ = ['client'] from catpy.client import CatmaidClient, CoordinateTransformer, CatmaidUrl # noqa +from catpy import image # noqa +from catpy import export # noqa diff --git a/catpy/image.py b/catpy/image.py index a601889..cd25378 100644 --- a/catpy/image.py +++ b/catpy/image.py @@ -5,6 +5,8 @@ from __future__ import division, unicode_literals import logging from io import BytesIO from collections import OrderedDict + +from requests import HTTPError from timeit import timeit import itertools from warnings import warn @@ -392,6 +394,12 @@ class Stack(object): class ProjectStack(Stack): + orientation_choices = { + 0: "xy", + 1: "xz", + 2: "zy", + } + def __init__(self, dimension, translation, resolution, orientation, broken_slices=None, canary_location=None): """ Representation of an image stack as it pertains to a CATMAID project @@ -430,7 +438,8 @@ class ProjectStack(Stack): """ stack = cls( stack_info['dimension'], stack_info['translation'], stack_info['resolution'], - stack_info['orientation'], stack_info['broken_slices'], stack_info['canary_location'] + cls.orientation_choices[stack_info['orientation']], stack_info['broken_slices'], + stack_info['canary_location'] ) mirrors = [StackMirror.from_dict(d) for d in stack_info['mirrors']] @@ -670,6 +679,12 @@ class ImageFetcher(object): raise ValueError('Unknown dimension of volume: should be 2D or 3D') return np.moveaxis(arr, (0, 1, 2), self._dimension_mappings) + def _make_empty_tile(self, width, height=None): + height = height or width + tile = np.empty((height, width), dtype=np.uint8) + tile.fill(self.cval) + return tile + def _get_tile(self, tile_index): """ Get the tile from the cache, handle broken slices, or fetch. @@ -689,9 +704,7 @@ class ImageFetcher(object): if tile_index.depth in self.stack.broken_slices: if self.broken_slice_handling == BrokenSliceHandling.FILL and self.cval is not None: - tile = np.empty((tile_index.width, tile_index.height)) - tile.fill(self.cval) - return tile + return self._make_empty_tile(tile_index.width, tile_index.height) else: raise NotImplementedError( "'fill' with a non-None cval is the only implemented broken slice handling mode" @@ -813,7 +826,14 @@ class ImageFetcher(object): Future of np.ndarray in source orientation """ url = self.mirror.generate_url(tile_index) - return response_to_array(self._session.get(url, timeout=self.timeout)) + try: + return response_to_array(self._session.get(url, timeout=self.timeout)) + except HTTPError as e: + if e.response.status_code == 404: + logger.warning("Tile not found at %s (error 404), returning blank tile", url) + return self._make_empty_tile(tile_index.width, tile_index.height) + else: + raise def _reorient_roi_tgt_to_src(self, roi_tgt): return roi_tgt[:, self._dimension_mappings]
Instantiating ImageFetcher from CatMaid fails due to integer orientation
catmaid/catpy
diff --git a/tests/test_image.py b/tests/test_image.py index 7c02cf8..b73fa41 100644 --- a/tests/test_image.py +++ b/tests/test_image.py @@ -6,6 +6,7 @@ import requests from PIL import Image from io import BytesIO from concurrent.futures import Future +from requests import HTTPError try: import mock @@ -508,7 +509,7 @@ def test_imagefetcher_set_mirror_title_warns_no_match(min_fetcher): def test_imagefetcher_set_mirror_title_warns_too_many(min_fetcher): min_fetcher.stack.mirrors.append(StackMirror(IMAGE_BASE, 1, 1, TILE_SOURCE_TYPE, 'png', 'title0', 10)) - with pytest.warns(UserWarning, match='does not exist'): + with pytest.warns(UserWarning, match='ore than one'): min_fetcher.mirror = 'title0' assert min_fetcher._mirror == min_fetcher.stack.mirrors[0] @@ -746,3 +747,17 @@ def test_imagefetcher_get_wrappers(min_fetcher, space): min_fetcher.get = mock.Mock() getattr(min_fetcher, 'get_{}_space'.format(space.value))('roi', 'zoom_level') min_fetcher.get.assert_called_with('roi', space, 'zoom_level', None) + + +def test_404_handled_correctly(min_fetcher): + idx = TileIndex(0, 0, 0, 0, 100, 100) + min_fetcher._session.get = mock.Mock(side_effect=HTTPError(response=mock.Mock(status_code=404))) + with mock.patch('catpy.image.response_to_array', mock.Mock()): + tile = min_fetcher._fetch(idx) + assert tile.shape == (100, 100) + assert (tile == 0).sum() == tile.size + + [email protected](reason="404 handling not implemented for threaded fetcher") +def test_404_handled_correctly_threaded(min_fetcher): + assert False
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements/prod.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 -e git+https://github.com/catmaid/catpy.git@ab4f858dda1144bec732738f406054248af7103d#egg=catpy certifi==2021.5.30 coverage==6.2 decorator==5.1.1 execnet==1.9.0 importlib-metadata==4.8.3 iniconfig==1.1.1 networkx==1.11 numpy==1.12.1 packaging==21.3 Pillow==5.0.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 requests==2.14.2 requests-futures==0.9.7 six==1.10.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: catpy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - decorator==5.1.1 - execnet==1.9.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - networkx==1.11 - numpy==1.12.1 - packaging==21.3 - pillow==5.0.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - requests==2.14.2 - requests-futures==0.9.7 - six==1.10.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/catpy
[ "tests/test_image.py::test_404_handled_correctly" ]
[]
[ "tests/test_image.py::test_vol_maker[0-shape0-1]", "tests/test_image.py::test_vol_maker[1-shape1-2]", "tests/test_image.py::test_vol_maker[0-shape2-10]", "tests/test_image.py::test_vol_maker[0-shape3-46]", "tests/test_image.py::test_vol_maker[1-shape4-47]", "tests/test_image.py::test_response_to_array_png[L]", "tests/test_image.py::test_response_to_array_png[RGB]", "tests/test_image.py::test_response_to_array_png[RGBA]", "tests/test_image.py::test_response_to_array_jpeg[L]", "tests/test_image.py::test_response_to_array_jpeg[RGB]", "tests/test_image.py::test_predefined_format_urls_are_valid[TileSourceType.FILE_BASED-{image_base}{{depth}}/{{row}}_{{col}}_{{zoom_level}}.{file_extension}]", "tests/test_image.py::test_predefined_format_urls_are_valid[TileSourceType.FILE_BASED_WITH_ZOOM_DIRS-{image_base}{{depth}}/{{zoom_level}}/{{row}}_{{col}}.{file_extension}]", "tests/test_image.py::test_predefined_format_urls_are_valid[TileSourceType.DIR_BASED-{image_base}{{zoom_level}}/{{depth}}/{{row}}/{{col}}.{file_extension}]", "tests/test_image.py::test_predefined_format_urls_are_valid[TileSourceType.RENDER_SERVICE-{image_base}largeDataTileSource/{tile_width}/{tile_height}/{{zoom_level}}/{{depth}}/{{row}}/{{col}}.{file_extension}]", "tests/test_image.py::test_predefined_format_urls_are_valid[TileSourceType.FLIXSERVER-{image_base}{{depth}}/{{row}}_{{col}}_{{zoom_level}}.{file_extension}]", "tests/test_image.py::test_as_future_for_not_future", "tests/test_image.py::test_as_future_for_future", "tests/test_image.py::test_fill_tiled_cuboid", "tests/test_image.py::test_fill_tiled_cuboid_raises", "tests/test_image.py::test_dict_subtract_mismatched_keys", "tests/test_image.py::test_dict_subtract", "tests/test_image.py::test_tile_index_coords", "tests/test_image.py::test_tile_index_comparable[zoom_level]", "tests/test_image.py::test_tile_index_comparable[height]", "tests/test_image.py::test_tile_index_comparable[width]", "tests/test_image.py::test_tile_index_url_kwargs", "tests/test_image.py::test_stackmirror_corrects_image_base", "tests/test_image.py::test_stackmirror_corrects_file_extension", "tests/test_image.py::test_stackmirror_formats_url[TileSourceType.FILE_BASED]", "tests/test_image.py::test_stackmirror_formats_url[TileSourceType.FILE_BASED_WITH_ZOOM_DIRS]", "tests/test_image.py::test_stackmirror_formats_url[TileSourceType.DIR_BASED]", "tests/test_image.py::test_stackmirror_formats_url[TileSourceType.RENDER_SERVICE]", "tests/test_image.py::test_stackmirror_formats_url[TileSourceType.FLIXSERVER]", "tests/test_image.py::test_stackmirror_raises_on_incompatible_tile_index", "tests/test_image.py::test_stackmirror_get_tile_index", "tests/test_image.py::test_stack_sets_broken_slices_canary", "tests/test_image.py::test_stack_fastest_mirror_calls_get", "tests/test_image.py::test_stack_fastest_mirror_raises", "tests/test_image.py::test_tilecache_can_set", "tests/test_image.py::test_tilecache_set_refreshes_old", "tests/test_image.py::test_tilecache_can_get", "tests/test_image.py::test_tilecache_lru", "tests/test_image.py::test_tilecache_can_clear", "tests/test_image.py::test_tilecache_can_constrain_len", "tests/test_image.py::test_tilecache_can_constrain_bytes", "tests/test_image.py::test_imagefetcher_can_instantiate", "tests/test_image.py::test_imagefetcher_mirror_fallback_warning", "tests/test_image.py::test_imagefetcher_set_mirror_none", "tests/test_image.py::test_imagefetcher_set_mirror_mirror", "tests/test_image.py::test_imagefetcher_set_mirror_mirror_raises", "tests/test_image.py::test_imagefetcher_set_mirror_int", "tests/test_image.py::test_imagefetcher_set_mirror_int_as_str", "tests/test_image.py::test_imagefetcher_set_mirror_position_warns_no_match", "tests/test_image.py::test_imagefetcher_set_mirror_position_warns_too_many", "tests/test_image.py::test_imagefetcher_set_mirror_title", "tests/test_image.py::test_imagefetcher_set_mirror_title_warns_no_match", "tests/test_image.py::test_imagefetcher_set_mirror_title_warns_too_many", "tests/test_image.py::test_imagefetcher_get_auth_default", "tests/test_image.py::test_imagefetcher_get_auth_from_mirror", "tests/test_image.py::test_imagefetcher_get_auth_fallback", "tests/test_image.py::test_imagefetcher_clear_cache", "tests/test_image.py::test_imagefetcher_map_dimensions", "tests/test_image.py::test_imagefetcher_reorient", "tests/test_image.py::test_imagefetcher_reorient_expands", "tests/test_image.py::test_imagefetcher_reorient_throws", "tests/test_image.py::test_imagefetcher_roi_to_tiles[roi0-expected_drc0-expected_yx_minmax0]", "tests/test_image.py::test_imagefetcher_roi_to_tiles[roi1-expected_drc1-expected_yx_minmax1]", "tests/test_image.py::test_imagefetcher_roi_to_tiles[roi2-expected_drc2-expected_yx_minmax2]", "tests/test_image.py::test_imagefetcher_roi_to_tiles[roi3-expected_drc3-expected_yx_minmax3]", "tests/test_image.py::test_imagefetcher_roi_to_tiles[roi4-expected_drc4-expected_yx_minmax4]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ImageFetcher-scaled-0-expected0]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ImageFetcher-stack-0-expected1]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ImageFetcher-stack--2-expected2]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ImageFetcher-stack-1-expected3]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ImageFetcher-project-0-expected4]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ImageFetcher-project--2-expected5]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ImageFetcher-project-1-expected6]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ThreadedImageFetcher-scaled-0-expected0]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ThreadedImageFetcher-stack-0-expected1]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ThreadedImageFetcher-stack--2-expected2]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ThreadedImageFetcher-stack-1-expected3]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ThreadedImageFetcher-project-0-expected4]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ThreadedImageFetcher-project--2-expected5]", "tests/test_image.py::test_imagefetcher_roi_to_scaled[ThreadedImageFetcher-project-1-expected6]", "tests/test_image.py::test_imagefetcher_roi_to_scaled_raises[ImageFetcher]", "tests/test_image.py::test_imagefetcher_roi_to_scaled_raises[ThreadedImageFetcher]", "tests/test_image.py::test_imagefetcher_get[ImageFetcher-roi0-1]", "tests/test_image.py::test_imagefetcher_get[ImageFetcher-roi1-2]", "tests/test_image.py::test_imagefetcher_get[ImageFetcher-roi2-1]", "tests/test_image.py::test_imagefetcher_get[ImageFetcher-roi3-2]", "tests/test_image.py::test_imagefetcher_get[ImageFetcher-roi4-2]", "tests/test_image.py::test_imagefetcher_get[ImageFetcher-roi5-4]", "tests/test_image.py::test_imagefetcher_get[ImageFetcher-roi6-12]", "tests/test_image.py::test_imagefetcher_get[ThreadedImageFetcher-roi0-1]", "tests/test_image.py::test_imagefetcher_get[ThreadedImageFetcher-roi1-2]", "tests/test_image.py::test_imagefetcher_get[ThreadedImageFetcher-roi2-1]", "tests/test_image.py::test_imagefetcher_get[ThreadedImageFetcher-roi3-2]", "tests/test_image.py::test_imagefetcher_get[ThreadedImageFetcher-roi4-2]", "tests/test_image.py::test_imagefetcher_get[ThreadedImageFetcher-roi5-4]", "tests/test_image.py::test_imagefetcher_get[ThreadedImageFetcher-roi6-12]", "tests/test_image.py::test_imagefetcher_get_into_array[ImageFetcher]", "tests/test_image.py::test_imagefetcher_get_into_array[ThreadedImageFetcher]", "tests/test_image.py::test_imagefetcher_get_tile_from_cache[ImageFetcher]", "tests/test_image.py::test_imagefetcher_get_tile_from_cache[ThreadedImageFetcher]", "tests/test_image.py::test_imagefetcher_get_tile_from_broken_slice[ImageFetcher]", "tests/test_image.py::test_imagefetcher_get_tile_from_broken_slice[ThreadedImageFetcher]", "tests/test_image.py::test_imagefetcher_get_tile_from_fetch", "tests/test_image.py::test_imagefetcher_fetch", "tests/test_image.py::test_imagefetcher_get_wrappers[stack]", "tests/test_image.py::test_imagefetcher_get_wrappers[scaled]", "tests/test_image.py::test_imagefetcher_get_wrappers[project]" ]
[]
MIT License
2,565
[ "catpy/image.py", "catpy/__init__.py" ]
[ "catpy/image.py", "catpy/__init__.py" ]
Azure__WALinuxAgent-1183
ad18ce33f467f5eeb4ac4afadb7f46d6c7444307
2018-05-21 20:12:58
6e9b985c1d7d564253a1c344bab01b45093103cd
diff --git a/azurelinuxagent/common/protocol/imds.py b/azurelinuxagent/common/protocol/imds.py index 1748bd91..c0deb358 100644 --- a/azurelinuxagent/common/protocol/imds.py +++ b/azurelinuxagent/common/protocol/imds.py @@ -17,6 +17,10 @@ def get_imds_client(): class ComputeInfo(DataContract): + @property + def image_info(self): + return "{0}:{1}:{2}:{3}".format(self.publisher, self.offer, self.sku, self.version) + def __init__(self, location=None, name=None, @@ -32,7 +36,9 @@ class ComputeInfo(DataContract): tags=None, version=None, vmId=None, - vmSize=None): + vmSize=None, + vmScaleSetName=None, + zone=None): self.location = location self.name = name self.offer = offer @@ -48,10 +54,8 @@ class ComputeInfo(DataContract): self.version = version self.vmId = vmId self.vmSize = vmSize - - @property - def image_info(self): - return "{0}:{1}:{2}:{3}".format(self.publisher, self.offer, self.sku, self.version) + self.vmScaleSetName = vmScaleSetName + self.zone = zone class ImdsClient(object):
Telemetry Should Include Additional IMDS Metadata The latest version of IMDS includes the following fields that should be considered for inclusion: 1. zone 1. vmScaleSetName https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service#instance-metadata-data-categories
Azure/WALinuxAgent
diff --git a/tests/protocol/test_imds.py b/tests/protocol/test_imds.py index 3f8ac2ed..d0f65292 100644 --- a/tests/protocol/test_imds.py +++ b/tests/protocol/test_imds.py @@ -72,7 +72,9 @@ class TestImds(AgentTestCase): "tags": "Key1:Value1;Key2:Value2", "vmId": "f62f23fb-69e2-4df0-a20b-cb5c201a3e7a", "version": "UnitVersion", - "vmSize": "Standard_D1_v2" + "vmSize": "Standard_D1_v2", + "vmScaleSetName": "MyScaleSet", + "zone": "In" }''' data = json.loads(s, encoding='utf-8') @@ -95,6 +97,8 @@ class TestImds(AgentTestCase): self.assertEqual('f62f23fb-69e2-4df0-a20b-cb5c201a3e7a', compute_info.vmId) self.assertEqual('UnitVersion', compute_info.version) self.assertEqual('Standard_D1_v2', compute_info.vmSize) + self.assertEqual('MyScaleSet', compute_info.vmScaleSetName) + self.assertEqual('In', compute_info.zone) self.assertEqual('UnitPublisher:UnitOffer:UnitSku:UnitVersion', compute_info.image_info)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
2.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pyasn1", "pytest" ], "pre_install": null, "python": "3.4", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyasn1==0.5.1 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work -e git+https://github.com/Azure/WALinuxAgent.git@ad18ce33f467f5eeb4ac4afadb7f46d6c7444307#egg=WALinuxAgent zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: WALinuxAgent channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - pyasn1==0.5.1 prefix: /opt/conda/envs/WALinuxAgent
[ "tests/protocol/test_imds.py::TestImds::test_deserialize_ComputeInfo" ]
[]
[ "tests/protocol/test_imds.py::TestImds::test_get", "tests/protocol/test_imds.py::TestImds::test_get_bad_request", "tests/protocol/test_imds.py::TestImds::test_get_empty_response" ]
[]
Apache License 2.0
2,566
[ "azurelinuxagent/common/protocol/imds.py" ]
[ "azurelinuxagent/common/protocol/imds.py" ]
linkedin__shiv-34
7860130f09ad81c0e5c7a813d5e14d5aec7112e2
2018-05-22 01:22:52
7860130f09ad81c0e5c7a813d5e14d5aec7112e2
warsaw: What do you think about keeping `-sE` if `sys.executable` (the default) is used? sixninetynine: @warsaw I thought about that too, but ultimately felt like it would be confusing... say someone didn't want `-sE`, they'd have to explicitly set `--python` to be (effectively) the same as `sys.executable`. warsaw: True, but OTOH if they just want the defaults (which should be the most common case, right?) they'll have to use `--python` to add the isolation. I guess it's a 6 vs 1/2 dozen thing, so as long as the change is well communicated and the documentation is up to date, I don't have a strong opinion either way. warsaw: Re: Internally - will an outside consumer know what that means? Maybe just suggest that for better isolation from the system's and user's Python environment, these flags can be used? Re: default use of the flags - I'm not sure whether it's non-typical because folks don't think about it, or whether they really do no want isolation in general. None of this is a blocker for me though. Just thoughts about usability. sixninetynine: @warsaw I updated the wording in the history doc to be more clear, but rather than try and tack on `-sE` I think it will be better to leave that up to individual users. That way using `--python` vs not supplying it will be similar enough to not be confusing. (and imagine if someone supplied `-sE` without knowing that we add it by default! confusing!).
diff --git a/docs/history.rst b/docs/history.rst index a3f49f4..244d72d 100644 --- a/docs/history.rst +++ b/docs/history.rst @@ -36,9 +36,11 @@ injecting said dependencies at runtime. We have to credit the great work by @wic The primary differences between PEX and shiv are: * ``shiv`` completey avoids the use of ``pkg_resources``. If it is included by a transitive - dependency, the performance implications are mitigated by limiting the length of ``sys.path`` and - always including the `-s <https://docs.python.org/3/using/cmdline.html#cmdoption-s>`_ and - `-E <https://docs.python.org/3/using/cmdline.html#cmdoption-e>`_ Python interpreter flags. + dependency, the performance implications are mitigated by limiting the length of ``sys.path``. + Internally, at LinkedIn, we always include the + `-s <https://docs.python.org/3/using/cmdline.html#cmdoption-s>`_ and + `-E <https://docs.python.org/3/using/cmdline.html#cmdoption-e>`_ Python interpreter flags by + specifying ``--python "/path/to/python -sE"``, which ensures a clean environment. * Instead of shipping our binary with downloaded wheels inside, we package an entire site-packages directory, as installed by ``pip``. We then bootstrap that directory post-extraction via the stdlib's ``site.addsitedir`` function. That way, everything works out of the box: namespace diff --git a/src/shiv/builder.py b/src/shiv/builder.py index 640a560..2d2b1f2 100644 --- a/src/shiv/builder.py +++ b/src/shiv/builder.py @@ -14,6 +14,8 @@ import zipapp from pathlib import Path from typing import Any, IO, Generator, Union +from .constants import BINPRM_ERROR + # Typical maximum length for a shebang line BINPRM_BUF_SIZE = 128 @@ -25,24 +27,17 @@ import {module} """ -def write_file_prefix(f: IO[Any], interpreter_path: Path) -> None: +def write_file_prefix(f: IO[Any], interpreter: str) -> None: """Write a shebang line. - .. note:: - - Shiv explicitly uses `-sE` as start up flags to prevent contamination of sys.path. - :param f: An open file handle. - :param interpreter_path: A path to a python interpreter. + :param interpreter: A path to a python interpreter. """ + # if the provided path is too long for a shebang we should error out + if len(interpreter) > BINPRM_BUF_SIZE: + sys.exit(BINPRM_ERROR) - # fall back to /usr/bin/env if the interp path is too long - if len(interpreter_path.as_posix()) > BINPRM_BUF_SIZE: - shebang = f"/usr/bin/env {interpreter_path.name}" - else: - shebang = interpreter_path.as_posix() - - f.write(b"#!" + shebang.encode(sys.getfilesystemencoding()) + b" -sE\n") + f.write(b"#!" + interpreter.encode(sys.getfilesystemencoding()) + b"\n") @contextlib.contextmanager @@ -56,7 +51,11 @@ def maybe_open(archive: Union[str, Path], mode: str) -> Generator[IO[Any], None, def create_archive( - source: Path, target: Path, interpreter: Path, main: str, compressed: bool = True + source: Path, + target: Path, + interpreter: str, + main: str, + compressed: bool = True ) -> None: """Create an application archive from SOURCE. @@ -95,5 +94,4 @@ def create_archive( z.writestr("__main__.py", main_py.encode("utf-8")) # make executable - if interpreter and not hasattr(target, "write"): - target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) diff --git a/src/shiv/cli.py b/src/shiv/cli.py index d5ea025..5c88546 100644 --- a/src/shiv/cli.py +++ b/src/shiv/cli.py @@ -20,7 +20,6 @@ from .constants import ( NO_PIP_ARGS, NO_OUTFILE, NO_ENTRY_POINT, - INVALID_PYTHON, ) __version__ = '0.0.25' @@ -44,24 +43,6 @@ def find_entry_point(site_packages: Path, console_script: str) -> str: return config_parser["console_scripts"][console_script] -def validate_interpreter(interpreter_path: Optional[str] = None) -> Path: - """Ensure that the interpreter is a real path, not a symlink. - - If no interpreter is given, default to `sys.exectuable` - - :param interpreter_path: A path to a Python interpreter. - """ - real_path = Path(sys.executable) if interpreter_path is None else Path( - interpreter_path - ) - - if real_path.exists(): - return real_path - - else: - sys.exit(INVALID_PYTHON.format(path=real_path)) - - def copy_bootstrap(bootstrap_target: Path) -> None: """Copy bootstrap code from shiv into the pyz. @@ -124,16 +105,12 @@ def main( ) ) - # validate supplied python (if any) - interpreter = validate_interpreter(python) - with TemporaryDirectory() as working_path: site_packages = Path(working_path, "site-packages") site_packages.mkdir(parents=True, exist_ok=True) # install deps into staged site-packages pip.install( - python or sys.executable, ["--target", site_packages.as_posix()] + list(pip_args), ) @@ -163,7 +140,7 @@ def main( builder.create_archive( Path(working_path), target=Path(output_file), - interpreter=interpreter, + interpreter=python or sys.executable, main="_bootstrap:bootstrap", compressed=compressed, ) diff --git a/src/shiv/constants.py b/src/shiv/constants.py index 33d742b..58e0bc5 100644 --- a/src/shiv/constants.py +++ b/src/shiv/constants.py @@ -5,9 +5,9 @@ from typing import Tuple, Dict DISALLOWED_PIP_ARGS = "\nYou supplied a disallowed pip argument! '{arg}'\n\n{reason}\n" NO_PIP_ARGS = "\nYou must supply PIP ARGS!\n" NO_OUTFILE = "\nYou must provide an output file option! (--output-file/-o)\n" -INVALID_PYTHON = "\nInvalid python interpreter! {path} does not exist!\n" NO_ENTRY_POINT = "\nNo entry point '{entry_point}' found in the console_scripts!\n" PIP_INSTALL_ERROR = "\nPip install failed!\n" +BINPRM_ERROR = "\nShebang is too long, it would exceed BINPRM_BUF_SIZE! Consider /usr/bin/env" # pip PIP_INSTALL_ERROR = "\nPip install failed!\n" diff --git a/src/shiv/pip.py b/src/shiv/pip.py index 92481f0..8ab2a4c 100644 --- a/src/shiv/pip.py +++ b/src/shiv/pip.py @@ -42,14 +42,14 @@ def clean_pip_env() -> Generator[None, None, None]: pydistutils.unlink() -def install(interpreter_path: str, args: List[str]) -> None: +def install(args: List[str]) -> None: """`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py - >>> install('/usr/local/bin/python3', ['numpy', '--target', 'site-packages']) + >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s @@ -60,7 +60,7 @@ def install(interpreter_path: str, args: List[str]) -> None: with clean_pip_env(): process = subprocess.Popen( - [interpreter_path, "-m", "pip", "--disable-pip-version-check", "install"] + args, + [sys.executable, "-m", "pip", "--disable-pip-version-check", "install"] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, )
allow use generic "/usr/bin/env python3.6" shebang? Hello, I played a bit with shiv and noticed that it always writes the full path to a python interpreter (sys.executable or user provided one) in the zipapp's shebang. Which means, if I try to run the same pyz on a different machine where python3.6 is installed in a different location, it won't run. https://github.com/linkedin/shiv/blob/29fb7c316fa7b1f9111cade730b2168a2c4f4a6e/src/shiv/cli.py#L56 https://github.com/linkedin/shiv/blob/29fb7c316fa7b1f9111cade730b2168a2c4f4a6e/src/shiv/builder.py#L39-L43 https://github.com/linkedin/shiv/blob/29fb7c316fa7b1f9111cade730b2168a2c4f4a6e/src/shiv/pip.py#L46 With [pex](https://pex.readthedocs.io/en/stable/buildingpex.html#invoking-the-pex-utility), one can specify the interpreter to use either as absolute path or just the name of a Python interpreter within the environment. It would be nice if shiv also allowed to do that. Thank you
linkedin/shiv
diff --git a/test/test_bootstrap.py b/test/test_bootstrap.py index 1da3885..5734f0c 100644 --- a/test/test_bootstrap.py +++ b/test/test_bootstrap.py @@ -8,6 +8,8 @@ from code import interact from uuid import uuid4 from zipfile import ZipFile +import pytest + from unittest import mock from shiv.bootstrap import import_string, current_zipfile, cache_path @@ -33,6 +35,14 @@ class TestBootstrap: from os.path import join assert func == join + # test something already imported + import shiv + assert import_string('shiv') == shiv == sys.modules['shiv'] + + # test bogus imports raise properly + with pytest.raises(ImportError): + import_string('this is bogus!') + def test_is_zipfile(self, zip_location): assert not current_zipfile() diff --git a/test/test_builder.py b/test/test_builder.py index fd3e369..8b2ec04 100644 --- a/test/test_builder.py +++ b/test/test_builder.py @@ -8,36 +8,54 @@ from zipapp import ZipAppError import pytest -from shiv.cli import validate_interpreter from shiv.builder import write_file_prefix, create_archive UGOX = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH -class TestBuilder: - def test_file_prefix(self): - with tempfile.TemporaryFile() as fd: - python = validate_interpreter(Path(sys.executable)) - write_file_prefix(fd, python) - fd.seek(0) - written = fd.read() +def tmp_write_prefix(interpreter): + with tempfile.TemporaryFile() as fd: + write_file_prefix(fd, interpreter) + fd.seek(0) + written = fd.read() + + return written + - assert written == b'#!' + python.as_posix().encode(sys.getdefaultencoding()) + b' -sE\n' +class TestBuilder: + @pytest.mark.parametrize( + 'interpreter,expected', [ + ('/usr/bin/python', b'#!/usr/bin/python\n'), + ('/usr/bin/env python', b'#!/usr/bin/env python\n'), + ('/some/other/path/python -sE', b'#!/some/other/path/python -sE\n'), + ] + ) + def test_file_prefix(self, interpreter, expected): + assert tmp_write_prefix(interpreter) == expected + + def test_binprm_error(self): + with pytest.raises(SystemExit): + tmp_write_prefix(f"/{'c' * 200}/python") def test_create_archive(self, sp): with tempfile.TemporaryDirectory() as tmpdir: target = Path(tmpdir, 'test.zip') - create_archive(sp, target, validate_interpreter(None), 'code:interact') + + # create an archive + create_archive(sp, target, sys.executable, 'code:interact') + + # create one again (to ensure we overwrite) + create_archive(sp, target, sys.executable, 'code:interact') assert zipfile.is_zipfile(str(target)) with pytest.raises(ZipAppError): - create_archive(sp, target, validate_interpreter(None), 'alsjdbas,,,') + create_archive(sp, target, sys.executable, 'alsjdbas,,,') def test_archive_permissions(self, sp): with tempfile.TemporaryDirectory() as tmpdir: target = Path(tmpdir, 'test.zip') - create_archive(sp, target, validate_interpreter(None), 'code:interact') + create_archive(sp, target, sys.executable, 'code:interact') assert target.stat().st_mode & UGOX == UGOX diff --git a/test/test_cli.py b/test/test_cli.py index a38017c..5fef26a 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -1,5 +1,4 @@ import subprocess -import sys import tempfile from pathlib import Path @@ -8,7 +7,7 @@ import pytest from click.testing import CliRunner -from shiv.cli import main, validate_interpreter +from shiv.cli import main from shiv.constants import DISALLOWED_PIP_ARGS, NO_PIP_ARGS, NO_OUTFILE, BLACKLISTED_ARGS @@ -69,13 +68,3 @@ class TestCLI: # now run the produced zipapp with subprocess.Popen([output_file], stdout=subprocess.PIPE) as proc: assert proc.stdout.read().decode() == 'hello world\n' - - def test_interpreter(self): - assert validate_interpreter(None) == validate_interpreter() == Path(sys.executable) - - with pytest.raises(SystemExit): - validate_interpreter(Path('/usr/local/bogus_python')) - - @pytest.mark.skipif(len(sys.executable) > 128, reason='only run this test is the shebang is not too long') - def test_real_interpreter(self): - assert validate_interpreter(Path(sys.executable)) == Path(sys.executable)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 5 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "mypy", "flake8", "coveralls" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==6.7 coverage==6.2 coveralls==3.3.1 docopt==0.6.2 flake8==5.0.4 idna==3.10 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 mccabe==0.7.0 mypy==0.971 mypy-extensions==1.0.0 packaging==21.3 pluggy==1.0.0 py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 requests==2.27.1 -e git+https://github.com/linkedin/shiv.git@7860130f09ad81c0e5c7a813d5e14d5aec7112e2#egg=shiv tomli==1.2.3 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: shiv channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - click==6.7 - coverage==6.2 - coveralls==3.3.1 - docopt==0.6.2 - flake8==5.0.4 - idna==3.10 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - mccabe==0.7.0 - mypy==0.971 - mypy-extensions==1.0.0 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - requests==2.27.1 - tomli==1.2.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/shiv
[ "test/test_builder.py::TestBuilder::test_file_prefix[/usr/bin/python-#!/usr/bin/python\\n]", "test/test_builder.py::TestBuilder::test_file_prefix[/usr/bin/env", "test/test_builder.py::TestBuilder::test_file_prefix[/some/other/path/python", "test/test_builder.py::TestBuilder::test_binprm_error", "test/test_builder.py::TestBuilder::test_create_archive", "test/test_builder.py::TestBuilder::test_archive_permissions" ]
[]
[ "test/test_bootstrap.py::TestBootstrap::test_various_imports", "test/test_bootstrap.py::TestBootstrap::test_is_zipfile", "test/test_bootstrap.py::TestBootstrap::test_cache_path", "test/test_bootstrap.py::TestEnvironment::test_overrides", "test/test_bootstrap.py::TestEnvironment::test_serialize", "test/test_cli.py::TestCLI::test_no_args", "test/test_cli.py::TestCLI::test_no_outfile", "test/test_cli.py::TestCLI::test_blacklisted_args[-t]", "test/test_cli.py::TestCLI::test_blacklisted_args[--target]", "test/test_cli.py::TestCLI::test_blacklisted_args[--editable]", "test/test_cli.py::TestCLI::test_blacklisted_args[-d]", "test/test_cli.py::TestCLI::test_blacklisted_args[--download]", "test/test_cli.py::TestCLI::test_blacklisted_args[--user]", "test/test_cli.py::TestCLI::test_blacklisted_args[--root]", "test/test_cli.py::TestCLI::test_blacklisted_args[--prefix]", "test/test_cli.py::TestCLI::test_hello_world[.-None]", "test/test_cli.py::TestCLI::test_hello_world[absolute-path-None]", "test/test_pip.py::test_clean_pip_env[pydistutils.cfg-nt]", "test/test_pip.py::test_clean_pip_env[.pydistutils.cfg-posix]", "test/test_pip.py::test_clean_pip_env[None-posix]" ]
[]
BSD 2-Clause "Simplified" License
2,567
[ "src/shiv/constants.py", "src/shiv/builder.py", "src/shiv/pip.py", "docs/history.rst", "src/shiv/cli.py" ]
[ "src/shiv/constants.py", "src/shiv/builder.py", "src/shiv/pip.py", "docs/history.rst", "src/shiv/cli.py" ]
pypa__setuptools_scm-269
7cd319baaa1635a46d7325a8f8c7a42235bd0634
2018-05-22 04:42:12
e377112e996ed0adf65f6378475ea360103d947b
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index adc33c1..1548d32 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,6 +6,8 @@ v3.0.0 * switch to src layout (breaking change) * no longer alias tag and parsed_version in order to support understanding a version parse failure * require parse results to be ScmVersion or None (breaking change) +* fix #266 by requirin the prefix word to be a word again + (breaking change as the bug allowed arbitrary prefixes while the original feature only allowed words") v2.1.0 ====== diff --git a/src/setuptools_scm/git.py b/src/setuptools_scm/git.py index 6ff2c0d..7c45a84 100644 --- a/src/setuptools_scm/git.py +++ b/src/setuptools_scm/git.py @@ -111,19 +111,26 @@ def parse(root, describe_command=DEFAULT_DESCRIBE, pre_parse=warn_on_shallow): dirty=dirty, branch=wd.get_branch(), ) + else: + tag, number, node, dirty = _git_parse_describe(out) + + branch = wd.get_branch() + if number: + return meta(tag, distance=number, node=node, dirty=dirty, branch=branch) + else: + return meta(tag, node=node, dirty=dirty, branch=branch) + - # 'out' looks e.g. like 'v1.5.0-0-g4060507' or +def _git_parse_describe(describe_output): + # 'describe_output' looks e.g. like 'v1.5.0-0-g4060507' or # 'v1.15.1rc1-37-g9bd1298-dirty'. - if out.endswith("-dirty"): + + if describe_output.endswith("-dirty"): dirty = True - out = out[:-6] + describe_output = describe_output[:-6] else: dirty = False - tag, number, node = out.rsplit("-", 2) + tag, number, node = describe_output.rsplit("-", 2) number = int(number) - branch = wd.get_branch() - if number: - return meta(tag, distance=number, node=node, dirty=dirty, branch=branch) - else: - return meta(tag, node=node, dirty=dirty, branch=branch) + return tag, number, node, dirty diff --git a/src/setuptools_scm/version.py b/src/setuptools_scm/version.py index aba231d..5799f1a 100644 --- a/src/setuptools_scm/version.py +++ b/src/setuptools_scm/version.py @@ -13,6 +13,7 @@ from pkg_resources import parse_version as pkg_parse_version SEMVER_MINOR = 2 SEMVER_PATCH = 3 SEMVER_LEN = 3 +TAG_PREFIX = re.compile(r"^\w+-(.*)") def _pad(iterable, size, padding=None): @@ -56,14 +57,21 @@ def callable_or_entrypoint(group, callable_or_name): def tag_to_version(tag): + """ + take a tag that might be prefixed with a keyword and return only the version part + """ trace("tag", tag) if "+" in tag: warnings.warn("tag %r will be stripped of the local component" % tag) tag = tag.split("+")[0] # lstrip the v because of py2/py3 differences in setuptools # also required for old versions of setuptools - - version = tag.rsplit("-", 1)[-1].lstrip("v") + prefix_match = TAG_PREFIX.match(tag) + if prefix_match is not None: + version = prefix_match.group(1) + else: + version = tag + trace("version pre parse", version) if VERSION_CLASS is None: return version version = pkg_parse_version(version)
tags with dashes get mangled I want to be able to tag my git repo with "1.0.0-rc1". That version should be acceptable to setuptools_scm independently of "distance", "hash", and "dirty" suffixes. Doing so results in an error (sample tag is "3.3.1-rc26"): ``` looking for ep setuptools_scm.parse_scm_fallback . root '/Users/twall/plex/rd' looking for ep setuptools_scm.parse_scm /Users/twall/plex/rd found ep .git = setuptools_scm.git:parse cmd 'git rev-parse --show-toplevel' out b'/Users/twall/plex/rd\n' real root /Users/twall/plex/rd cmd 'git describe --dirty --tags --long --match *.*' out b'3.3.1-rc26-0-g9df187b\n' cmd 'git rev-parse --abbrev-ref HEAD' out b'pyplex\n' tag 3.3.1-rc26 version <LegacyVersion('rc26')> version None Traceback (most recent call last): File "setup.py", line 46, in <module> entry_points = { File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools/__init__.py", line 129, in setup return distutils.core.setup(**attrs) File "/anaconda3/lib/python3.6/distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools/dist.py", line 370, in __init__ k: v for k, v in attrs.items() File "/anaconda3/lib/python3.6/distutils/dist.py", line 281, in __init__ self.finalize_options() File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools/dist.py", line 529, in finalize_options ep.load()(self, ep.name, value) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/integration.py", line 22, in version_keyword dist.metadata.version = get_version(**value) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/__init__.py", line 119, in get_version parsed_version = _do_parse(root, parse) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/__init__.py", line 83, in _do_parse version = version_from_scm(root) or _version_from_entrypoint( File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/__init__.py", line 31, in version_from_scm return _version_from_entrypoint(root, 'setuptools_scm.parse_scm') File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/__init__.py", line 36, in _version_from_entrypoint version = ep.load()(root) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/git.py", line 128, in parse return meta(tag, node=node, dirty=dirty, branch=branch) File "/Users/twall/plex/rd/search/.venv-3.6/lib/python3.6/site-packages/setuptools_scm/version.py", line 135, in meta assert tag is not None, 'cant parse version %s' % tag AssertionError: cant parse version None ``` The `SemVer` description seems to allow nearly arbitrary strings for `www` in `x.y.z-www`, so I would expect such tags to work. Note that "3.3.1.rc26" sort of works, resulting in a modified version of "3.3.1rc26".
pypa/setuptools_scm
diff --git a/testing/test_functions.py b/testing/test_functions.py index 0c817b8..db573ac 100644 --- a/testing/test_functions.py +++ b/testing/test_functions.py @@ -2,7 +2,12 @@ import pytest import sys import pkg_resources from setuptools_scm import dump_version, get_version, PRETEND_KEY -from setuptools_scm.version import guess_next_version, meta, format_version +from setuptools_scm.version import ( + guess_next_version, + meta, + format_version, + tag_to_version, +) from setuptools_scm.utils import has_command PY3 = sys.version_info > (2,) @@ -77,3 +82,16 @@ def test_has_command(recwarn): assert not has_command("yadayada_setuptools_aint_ne") msg = recwarn.pop() assert "yadayada" in str(msg.message) + + [email protected]( + "tag, expected_version", + [ + ("1.1", "1.1"), + ("release-1.1", "1.1"), + pytest.param("3.3.1-rc26", "3.3.1rc26", marks=pytest.mark.issue(266)), + ], +) +def test_tag_to_version(tag, expected_version): + version = str(tag_to_version(tag)) + assert version == expected_version diff --git a/testing/test_git.py b/testing/test_git.py index be7e0a4..9530400 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -16,6 +16,15 @@ def wd(wd): return wd [email protected]( + "given, tag, number, node, dirty", + [("3.3.1-rc26-0-g9df187b", "3.3.1-rc26", 0, "g9df187b", False)], +) +def test_parse_describe_output(given, tag, number, node, dirty): + parsed = git._git_parse_describe(given) + assert parsed == (tag, number, node, dirty) + + def test_version_from_git(wd): assert wd.version == "0.1.dev0"
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 -e git+https://github.com/pypa/setuptools_scm.git@7cd319baaa1635a46d7325a8f8c7a42235bd0634#egg=setuptools_scm toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: setuptools_scm channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/setuptools_scm
[ "testing/test_functions.py::test_tag_to_version[3.3.1-rc26-3.3.1rc26]", "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]" ]
[]
[ "testing/test_functions.py::test_next_tag[1.1-1.2]", "testing/test_functions.py::test_next_tag[1.2.dev-1.2]", "testing/test_functions.py::test_next_tag[1.1a2-1.1a3]", "testing/test_functions.py::test_next_tag[23.24.post2+deadbeef-23.24.post3]", "testing/test_functions.py::test_format_version[exact-guess-next-dev", "testing/test_functions.py::test_format_version[zerodistance-guess-next-dev", "testing/test_functions.py::test_format_version[dirty-guess-next-dev", "testing/test_functions.py::test_format_version[distance-guess-next-dev", "testing/test_functions.py::test_format_version[distancedirty-guess-next-dev", "testing/test_functions.py::test_format_version[exact-post-release", "testing/test_functions.py::test_format_version[zerodistance-post-release", "testing/test_functions.py::test_format_version[dirty-post-release", "testing/test_functions.py::test_format_version[distance-post-release", "testing/test_functions.py::test_format_version[distancedirty-post-release", "testing/test_functions.py::test_dump_version_doesnt_bail_on_value_error", "testing/test_functions.py::test_dump_version_works_with_pretend", "testing/test_functions.py::test_has_command", "testing/test_functions.py::test_tag_to_version[1.1-1.1]", "testing/test_functions.py::test_tag_to_version[release-1.1-1.1]", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major" ]
[]
MIT License
2,568
[ "src/setuptools_scm/git.py", "CHANGELOG.rst", "src/setuptools_scm/version.py" ]
[ "src/setuptools_scm/git.py", "CHANGELOG.rst", "src/setuptools_scm/version.py" ]
marshmallow-code__marshmallow-826
cda2b4c97ac28412580567ba98e82568de125513
2018-05-22 18:36:40
8e217c8d6fefb7049ab3389f31a8d35824fa2d96
diff --git a/AUTHORS.rst b/AUTHORS.rst index e09e780c..3d135fbf 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -102,4 +102,5 @@ Contributors (chronological) - Suren Khorenyan `@surik00 <https://github.com/surik00>`_ - Jeffrey Berger `@JeffBerger <https://github.com/JeffBerger>`_ - Felix Yan `@felixonmars <https://github.com/felixonmars>`_ +- Prasanjit Prakash `@ikilledthecat <https://github.com/ikilledthecat>`_ - Guillaume Gelin `@ramnes <https://github.com/ramnes>`_ diff --git a/CHANGELOG.rst b/CHANGELOG.rst index cbcdedc9..48ac339a 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -16,6 +16,10 @@ Other changes: - *Backwards-incompatible*: Pre/Post-processors MUST return modified data. Returning ``None`` does not imply data were mutated (:issue:`347`). Thanks :user:`tdevelioglu` for reporting. +- *Backwards-incompatible*: ``only`` and ``exclude`` are bound by + declared and additional fields. A ``ValueError`` is raised if invalid + fields are passed (:issue:`636`). Thanks :user:`jan-23` for reporting. + Thanks :user:`ikilledthecat` and :user:`deckar01` for the PRs. Deprecations/Removals: diff --git a/marshmallow/schema.py b/marshmallow/schema.py index 9c36887f..45bca366 100644 --- a/marshmallow/schema.py +++ b/marshmallow/schema.py @@ -247,12 +247,13 @@ class BaseSchema(base.SchemaABC): data, errors = schema.dump(album) data # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'} - :param tuple|list only: Whitelist of fields to select when instantiating the Schema. - If None, all fields are used. - Nested fields can be represented with dot delimiters. - :param tuple|list exclude: Blacklist of fields to exclude when instantiating the Schema. - If a field appears in both `only` and `exclude`, it is not used. - Nested fields can be represented with dot delimiters. + :param tuple|list only: Whitelist of the declared fields to select when + instantiating the Schema. If None, all fields are used. Nested fields + can be represented with dot delimiters. + :param tuple|list exclude: Blacklist of the declared fields to exclude + when instantiating the Schema. If a field appears in both `only` and + `exclude`, it is not used. Nested fields can be represented with dot + delimiters. :param str prefix: Optional prefix that will be prepended to all the serialized field names. :param bool many: Should be set to `True` if ``obj`` is a collection @@ -723,13 +724,7 @@ class BaseSchema(base.SchemaABC): def _update_fields(self, obj=None, many=False): """Update fields based on the passed in object.""" - if self.only is not None: - # Return only fields specified in only option - if self.opts.fields: - field_names = self.set_class(self.opts.fields) & self.set_class(self.only) - else: - field_names = self.set_class(self.only) - elif self.opts.fields: + if self.opts.fields: # Return fields specified in fields option field_names = self.set_class(self.opts.fields) elif self.opts.additional: @@ -739,10 +734,26 @@ class BaseSchema(base.SchemaABC): else: field_names = self.set_class(self.declared_fields.keys()) + declared_fields = field_names + invalid_fields = self.set_class() + if self.only is not None: + # Return only fields specified in only option + only = self.set_class(self.only) + field_names = only + invalid_only = only - declared_fields + invalid_fields |= invalid_only + # If "exclude" option or param is specified, remove those fields excludes = set(self.opts.exclude) | set(self.exclude) if excludes: field_names = field_names - excludes + invalid_excludes = excludes - declared_fields + invalid_fields |= invalid_excludes + + if invalid_fields: + message = 'Invalid fields for {0}: {1}.'.format(self, invalid_fields) + raise ValueError(message) + ret = self.__filter_fields(field_names, obj, many=many) # Set parents self.__set_field_attrs(ret)
only is not bound by declared and additional fields on serializaton The only parameter is correctly bound to the fields that are defined in Meta.fields (#183): ```python class MySchema(Schema): class Meta: fields = ('a', ) MySchema(only=('b', )).dump({'a': 1, 'b': 2}).data == {} ``` Strangely it is not bound to the declared and additional fields: ```python class MySchema(Schema): a = fields.Str() class Meta: additional = ('b', ) MySchema(only=('c', )).dump({'a': 1, 'b': 2, 'c': 3}).data == {'c': 3} ``` It would be more consistent if the second example also returns an empty dict.
marshmallow-code/marshmallow
diff --git a/tests/base.py b/tests/base.py index d335ed45..a9e79163 100644 --- a/tests/base.py +++ b/tests/base.py @@ -229,7 +229,7 @@ class UserMetaSchema(Schema): class UserExcludeSchema(UserSchema): class Meta: - exclude = ('created', 'updated', 'field_not_found_but_thats_ok') + exclude = ('created', 'updated',) class UserAdditionalSchema(Schema): diff --git a/tests/test_schema.py b/tests/test_schema.py index 65fc487c..678f1b5b 100755 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -671,7 +671,7 @@ def test_only_in_init(SchemaClass, user): assert 'age' in s def test_invalid_only_param(user): - with pytest.raises(AttributeError): + with pytest.raises(ValueError): UserSchema(only=('_invalid', 'name')).dump(user) def test_can_serialize_uuid(serialized_user, user): @@ -1291,23 +1291,70 @@ def test_only_and_exclude(): assert 'bar' not in result -def test_exclude_invalid_attribute(): +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ('bar', 'baz') + sch = MySchema(only=('bar', 'baz'), exclude=('bar', )) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert 'baz' in result + assert 'bar' not in result + +def test_invalid_only_and_exclude_with_fields(): class MySchema(Schema): foo = fields.Field() - sch = MySchema(exclude=('bar', )) - assert sch.dump({'foo': 42}) == {'foo': 42} + class Meta: + fields = ('bar', 'baz') + with pytest.raises(ValueError) as excinfo: + MySchema(only=('foo', 'par'), exclude=('ban', )) -def test_only_with_invalid_attribute(): + assert 'foo' in str(excinfo) + assert 'par' in str(excinfo) + assert 'ban' in str(excinfo) + + +def test_only_and_exclude_with_additional(): class MySchema(Schema): foo = fields.Field() - sch = MySchema(only=('bar', )) - with pytest.raises(KeyError) as excinfo: - sch.dump(dict(foo=42)) - assert '"bar" is not a valid field' in str(excinfo.value.args[0]) + class Meta: + additional = ('bar', 'baz') + sch = MySchema(only=('foo', 'bar'), exclude=('bar', )) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert 'foo' in result + assert 'bar' not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ('bar', 'baz') + + with pytest.raises(ValueError) as excinfo: + MySchema(only=('foop', 'par'), exclude=('ban', )) + + assert 'foop' in str(excinfo) + assert 'par' in str(excinfo) + assert 'ban' in str(excinfo) + + +def test_exclude_invalid_attribute(): + + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError): + MySchema(exclude=('bar', )) + def test_only_bounded_by_fields(): class MySchema(Schema): @@ -1315,8 +1362,18 @@ def test_only_bounded_by_fields(): class Meta: fields = ('foo', ) - sch = MySchema(only=('baz', )) - assert sch.dump({'foo': 42}) == {} + with pytest.raises(ValueError): + MySchema(only=('baz', )) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + + class Meta: + additional = ('b', ) + + with pytest.raises(ValueError): + MySchema(only=('c', )).dump({'c': 3}) def test_only_empty(): class MySchema(Schema):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 3 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[reco]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": [ "dev-requirements.txt", "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aspy.yaml==1.3.0 atomicwrites==1.4.1 attrs==25.3.0 cached-property==2.0.1 cfgv==3.4.0 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 flake8==3.5.0 identify==2.6.9 iniconfig==2.1.0 invoke==1.0.0 -e git+https://github.com/marshmallow-code/marshmallow.git@cda2b4c97ac28412580567ba98e82568de125513#egg=marshmallow mccabe==0.6.1 more-itertools==10.6.0 nodeenv==1.9.1 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 pre-commit==1.10.2 py==1.11.0 pycodestyle==2.3.1 pyflakes==1.6.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.7.3 pytz==2018.5 PyYAML==6.0.2 simplejson==3.16.0 six==1.17.0 -e git+ssh://[email protected]/nebius/swebench_matterhorn.git@ae4d15b4472bd322342107dd10c47d793189f5b2#egg=swebench_matterhorn toml==0.10.2 tomli==2.2.1 tox==3.12.1 typing_extensions==4.13.0 virtualenv==20.29.3
name: marshmallow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aspy-yaml==1.3.0 - atomicwrites==1.4.1 - attrs==25.3.0 - cached-property==2.0.1 - cfgv==3.4.0 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - flake8==3.5.0 - identify==2.6.9 - iniconfig==2.1.0 - invoke==1.0.0 - mccabe==0.6.1 - more-itertools==10.6.0 - nodeenv==1.9.1 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==1.10.2 - py==1.11.0 - pycodestyle==2.3.1 - pyflakes==1.6.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.7.3 - pytz==2018.5 - pyyaml==6.0.2 - simplejson==3.16.0 - six==1.17.0 - toml==0.10.2 - tomli==2.2.1 - tox==3.12.1 - typing-extensions==4.13.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/marshmallow
[ "tests/test_schema.py::test_invalid_only_param", "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", "tests/test_schema.py::test_exclude_invalid_attribute", "tests/test_schema.py::test_only_bounded_by_fields", "tests/test_schema.py::test_only_bounded_by_additional" ]
[]
[ "tests/test_schema.py::test_serializing_basic_object[UserSchema]", "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", "tests/test_schema.py::test_serializer_dump", "tests/test_schema.py::test_dump_raises_with_dict_of_errors", "tests/test_schema.py::test_dump_mode_raises_error[UserSchema]", "tests/test_schema.py::test_dump_mode_raises_error[UserMetaSchema]", "tests/test_schema.py::test_dump_resets_errors", "tests/test_schema.py::test_load_resets_errors", "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", "tests/test_schema.py::test_dump_validation_error_stores_partially_valid_data", "tests/test_schema.py::test_dump_resets_error_fields", "tests/test_schema.py::test_load_resets_error_fields", "tests/test_schema.py::test_load_resets_error_kwargs", "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", "tests/test_schema.py::test_load_many_stores_error_indices", "tests/test_schema.py::test_dump_many", "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", "tests/test_schema.py::test_dump_many_stores_error_indices", "tests/test_schema.py::test_dump_many_doesnt_stores_error_indices_when_index_errors_is_false", "tests/test_schema.py::test_dump_returns_a_dict", "tests/test_schema.py::test_dumps_returns_a_string", "tests/test_schema.py::test_dumping_single_object_with_collection_schema", "tests/test_schema.py::test_loading_single_object_with_collection_schema", "tests/test_schema.py::test_dumps_many", "tests/test_schema.py::test_load_returns_an_object", "tests/test_schema.py::test_load_many", "tests/test_schema.py::test_loads_returns_a_user", "tests/test_schema.py::test_loads_many", "tests/test_schema.py::test_loads_deserializes_from_json", "tests/test_schema.py::test_serializing_none", "tests/test_schema.py::test_default_many_symmetry", "tests/test_schema.py::test_on_bind_field_hook", "tests/test_schema.py::test_nested_on_bind_field_hook", "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", "tests/test_schema.py::TestValidate::test_validate_many", "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", "tests/test_schema.py::TestValidate::test_validate", "tests/test_schema.py::TestValidate::test_validate_required", "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", "tests/test_schema.py::test_dumps_returns_json", "tests/test_schema.py::test_naive_datetime_field", "tests/test_schema.py::test_datetime_formatted_field", "tests/test_schema.py::test_datetime_iso_field", "tests/test_schema.py::test_tz_datetime_field", "tests/test_schema.py::test_local_datetime_field", "tests/test_schema.py::test_class_variable", "tests/test_schema.py::test_serialize_many[UserSchema]", "tests/test_schema.py::test_serialize_many[UserMetaSchema]", "tests/test_schema.py::test_inheriting_schema", "tests/test_schema.py::test_custom_field", "tests/test_schema.py::test_url_field", "tests/test_schema.py::test_relative_url_field", "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", "tests/test_schema.py::test_email_field[UserSchema]", "tests/test_schema.py::test_email_field[UserMetaSchema]", "tests/test_schema.py::test_stored_invalid_email", "tests/test_schema.py::test_integer_field", "tests/test_schema.py::test_as_string", "tests/test_schema.py::test_method_field[UserSchema]", "tests/test_schema.py::test_method_field[UserMetaSchema]", "tests/test_schema.py::test_function_field", "tests/test_schema.py::test_prefix[UserSchema]", "tests/test_schema.py::test_prefix[UserMetaSchema]", "tests/test_schema.py::test_fields_must_be_declared_as_instances", "tests/test_schema.py::test_serializing_generator[UserSchema]", "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", "tests/test_schema.py::test_serializing_dict", "tests/test_schema.py::test_serializing_dict_with_meta_fields", "tests/test_schema.py::test_exclude_in_init[UserSchema]", "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", "tests/test_schema.py::test_only_in_init[UserSchema]", "tests/test_schema.py::test_only_in_init[UserMetaSchema]", "tests/test_schema.py::test_can_serialize_uuid", "tests/test_schema.py::test_can_serialize_time", "tests/test_schema.py::test_invalid_time", "tests/test_schema.py::test_invalid_date", "tests/test_schema.py::test_invalid_dict_but_okay", "tests/test_schema.py::test_json_module_is_deprecated", "tests/test_schema.py::test_render_module", "tests/test_schema.py::test_custom_error_message", "tests/test_schema.py::test_load_errors_with_many", "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", "tests/test_schema.py::test_nested_only", "tests/test_schema.py::test_nested_only_inheritance", "tests/test_schema.py::test_nested_only_empty_inheritance", "tests/test_schema.py::test_nested_exclude", "tests/test_schema.py::test_nested_exclude_inheritance", "tests/test_schema.py::test_nested_only_and_exclude", "tests/test_schema.py::test_nested_only_then_exclude_inheritance", "tests/test_schema.py::test_nested_exclude_then_only_inheritance", "tests/test_schema.py::test_nested_exclude_and_only_inheritance", "tests/test_schema.py::test_meta_nested_exclude", "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", "tests/test_schema.py::test_deeply_nested_only_and_exclude", "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", "tests/test_schema.py::test_nested_constructor_only_and_exclude", "tests/test_schema.py::test_only_and_exclude", "tests/test_schema.py::test_only_and_exclude_with_fields", "tests/test_schema.py::test_only_and_exclude_with_additional", "tests/test_schema.py::test_only_empty", "tests/test_schema.py::test_nested_with_sets", "tests/test_schema.py::test_meta_serializer_fields", "tests/test_schema.py::test_meta_fields_mapping", "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", "tests/test_schema.py::test_exclude_fields", "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", "tests/test_schema.py::test_dateformat_option", "tests/test_schema.py::test_default_dateformat", "tests/test_schema.py::test_inherit_meta", "tests/test_schema.py::test_inherit_meta_override", "tests/test_schema.py::test_additional", "tests/test_schema.py::test_cant_set_both_additional_and_fields", "tests/test_schema.py::test_serializing_none_meta", "tests/test_schema.py::TestHandleError::test_dump_with_custom_error_handler", "tests/test_schema.py::TestHandleError::test_load_with_custom_error_handler", "tests/test_schema.py::TestHandleError::test_load_with_custom_error_handler_and_partially_valid_data", "tests/test_schema.py::TestHandleError::test_custom_error_handler_with_validates_decorator", "tests/test_schema.py::TestHandleError::test_custom_error_handler_with_validates_schema_decorator", "tests/test_schema.py::TestHandleError::test_validate_with_custom_error_handler", "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::TestNestedSchema::test_flat_nested", "tests/test_schema.py::TestNestedSchema::test_flat_nested_with_data_key", "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", "tests/test_schema.py::TestNestedSchema::test_flat_nested2", "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", "tests/test_schema.py::TestNestedSchema::test_nested_none", "tests/test_schema.py::TestNestedSchema::test_nested", "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", "tests/test_schema.py::TestNestedSchema::test_nested_only", "tests/test_schema.py::TestNestedSchema::test_exclude", "tests/test_schema.py::TestNestedSchema::test_list_field", "tests/test_schema.py::TestNestedSchema::test_nested_load_many", "tests/test_schema.py::TestNestedSchema::test_nested_errors", "tests/test_schema.py::TestNestedSchema::test_nested_dump_errors", "tests/test_schema.py::TestNestedSchema::test_nested_dump", "tests/test_schema.py::TestNestedSchema::test_nested_method_field", "tests/test_schema.py::TestNestedSchema::test_nested_function_field", "tests/test_schema.py::TestNestedSchema::test_nested_prefixed_field", "tests/test_schema.py::TestNestedSchema::test_nested_prefixed_many_field", "tests/test_schema.py::TestNestedSchema::test_invalid_float_field", "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", "tests/test_schema.py::TestNestedSchema::test_dump_validation_error", "tests/test_schema.py::TestSelfReference::test_nesting_schema_within_itself", "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", "tests/test_schema.py::TestSelfReference::test_multiple_nested_self_fields", "tests/test_schema.py::TestSelfReference::test_nested_many", "tests/test_schema.py::test_serialization_with_required_field", "tests/test_schema.py::test_deserialization_with_required_field", "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", "tests/test_schema.py::TestContext::test_context_method", "tests/test_schema.py::TestContext::test_context_method_function", "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", "tests/test_schema.py::TestContext::test_fields_context", "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", "tests/test_schema.py::TestRequiredFields::test_allow_none_param", "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", "tests/test_schema.py::TestDefaults::test_default_and_value_missing", "tests/test_schema.py::TestDefaults::test_loading_none", "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", "tests/test_schema.py::TestLoadOnly::test_load_only", "tests/test_schema.py::TestLoadOnly::test_dump_only", "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false" ]
[]
MIT License
2,572
[ "CHANGELOG.rst", "marshmallow/schema.py", "AUTHORS.rst" ]
[ "CHANGELOG.rst", "marshmallow/schema.py", "AUTHORS.rst" ]
ftao__python-ifcfg-27
3ae952775f66dc476ddb8f02953714e7676c9cff
2018-05-23 01:45:25
3ae952775f66dc476ddb8f02953714e7676c9cff
diff --git a/README.rst b/README.rst index 68223c5..88220c4 100644 --- a/README.rst +++ b/README.rst @@ -23,7 +23,8 @@ Usage for name, interface in ifcfg.interfaces().items(): # do something with interface print interface['device'] - print interface['inet'] + print interface['inet'] # First IPv4 found + print interface['inet4'] # List of ips print interface['inet6'] print interface['netmask'] print interface['broadcast'] @@ -43,6 +44,7 @@ following: "flags": "4163<up,broadcast,running,multicast> ", "hostname": "derks-vm.local", "inet": "172.16.217.10", + "inet4": ["172.16.217.10"], "inet6": ["fe80::20c:29ff:fe0c:da5d"], "mtu": "1500", "name": "eth0", @@ -53,6 +55,7 @@ following: "flags": "73<up,loopback,running> ", "hostname": "localhost", "inet": "127.0.0.1", + "inet4": ["127.0.0.1"], "inet6": ["::1"], "mtu": "16436", "name": "lo", @@ -64,6 +67,7 @@ following: "flags": "4099<up,broadcast,multicast> ", "hostname": "derks-vm.local", "inet": "192.168.122.1", + "inet4": ["192.168.122.1"], "inet6": [], "mtu": "1500", "name": "virbr0", @@ -75,6 +79,8 @@ following: Release notes ------------- +* Support for multiple IPv4 addresses in the new 'inet4' field + 0.15 ____ diff --git a/src/ifcfg/parser.py b/src/ifcfg/parser.py index 22ceeb8..f22135f 100644 --- a/src/ifcfg/parser.py +++ b/src/ifcfg/parser.py @@ -13,6 +13,7 @@ Log = minimal_logger(__name__) #: These will always be present for each device (even if they are None) DEVICE_PROPERTY_DEFAULTS = { 'inet': None, + 'inet4': "LIST", 'ether': None, 'inet6': "LIST", # Because lists are mutable 'netmask': None, @@ -78,6 +79,10 @@ class Parser(object): self._interfaces[cur][k] = v elif hasattr(self._interfaces[cur][k], 'append'): self._interfaces[cur][k].append(v) + elif self._interfaces[cur][k] == v: + # Silently ignore if the it's the same value as last. Example: Multiple + # inet4 addresses, result in multiple netmasks. Cardinality mismatch + continue else: raise RuntimeError( "Tried to add {}={} multiple times to {}, it was already: {}".format( @@ -90,6 +95,11 @@ class Parser(object): else: self._interfaces[cur][k] = v + # Copy the first 'inet4' ip address to 'inet' for backwards compatibility + for device, device_dict in self._interfaces.items(): + if len(device_dict['inet4']) > 0: + device_dict['inet'] = device_dict['inet4'][0] + # fix it up self._interfaces = self.alter(self._interfaces) @@ -108,6 +118,8 @@ class Parser(object): """ # fixup some things for device, device_dict in interfaces.items(): + if len(device_dict['inet4']) > 0: + device_dict['inet'] = device_dict['inet4'][0] if 'inet' in device_dict and not device_dict['inet'] is None: try: host = socket.gethostbyaddr(device_dict['inet'])[0] @@ -174,7 +186,7 @@ class WindowsParser(Parser): return [ r"^(?P<device>\w.+):", r"^ Physical Address. . . . . . . . . : (?P<ether>[ABCDEFabcdef\d-]+)", - r"^ IPv4 Address. . . . . . . . . . . : (?P<inet>[^\s\(]+)", + r"^ IPv4 Address. . . . . . . . . . . : (?P<inet4>[^\s\(]+)", r"^ IPv6 Address. . . . . . . . . . . : (?P<inet6>[ABCDEFabcdef\d\:\%]+)", ] @@ -210,7 +222,7 @@ class UnixParser(Parser): def get_patterns(cls): return [ '(?P<device>^[-a-zA-Z0-9:]+): flags=(?P<flags>.*) mtu (?P<mtu>.*)', - '.*inet\s+(?P<inet>[\d\.]+).*', + '.*inet\s+(?P<inet4>[\d\.]+).*', '.*inet6\s+(?P<inet6>[\d\:abcdef]+).*', '.*broadcast (?P<broadcast>[^\s]*).*', '.*netmask (?P<netmask>[^\s]*).*', @@ -257,7 +269,7 @@ class LinuxParser(UnixParser): return super(LinuxParser, cls).get_patterns() + [ '(?P<device>^[a-zA-Z0-9:_-]+)(.*)Link encap:(.*).*', '(.*)Link encap:(.*)(HWaddr )(?P<ether>[^\s]*).*', - '.*(inet addr:\s*)(?P<inet>[^\s]+).*', + '.*(inet addr:\s*)(?P<inet4>[^\s]+).*', '.*(inet6 addr:\s*)(?P<inet6>[^\s\/]+)', '.*(P-t-P:)(?P<ptp>[^\s]*).*', '.*(Bcast:)(?P<broadcast>[^\s]*).*', @@ -288,7 +300,7 @@ class UnixIPParser(UnixParser): def get_patterns(cls): return [ '\s*[0-9]+:\s+(?P<device>[a-zA-Z0-9]+):.*mtu (?P<mtu>.*)', - '.*(inet\s)(?P<inet>[\d\.]+)', + '.*(inet\s)(?P<inet4>[\d\.]+)', '.*(inet6 )(?P<inet6>[^/]*).*', '.*(ether )(?P<ether>[^\s]*).*', '.*inet\s.*(brd )(?P<broadcast>[^\s]*).*',
ifcfg does not see multiple ip addresses on one interfaces Hello, using ``` >>> ifcfg.__version__ '0.13' ``` on a system where eth0 has more than one IP address: ``` 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether b8:27:eb:50:39:69 brd ff:ff:ff:ff:ff:ff inet 192.168.13.1/24 brd 192.168.13.255 scope global eth0 valid_lft forever preferred_lft forever inet 192.168.10.3/24 scope global eth0 valid_lft forever preferred_lft forever inet6 fe80::ba27:ebff:fe50:3969/64 scope link valid_lft forever preferred_lft forever ``` ifcfg only sees one of them: ``` Python 3.5.3 (default, Jan 19 2017, 14:11:04) [GCC 6.3.0 20170124] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import ifcfg >>> from pprint import pprint >>> ifaces = ifcfg.interfaces() >>> pprint(ifaces['eth0']) {'broadcast': '192.168.13.255', 'device': 'eth0', 'ether': 'b8:27:eb:50:39:69', 'flags': '4163<UP,BROADCAST,RUNNING,MULTICAST> ', 'inet': '192.168.13.1', 'inet6': ['fe80::ba27:ebff:fe50:3969'], 'mtu': '1500', 'netmask': '255.255.255.0'} ```
ftao/python-ifcfg
diff --git a/tests/ifconfig_out.py b/tests/ifconfig_out.py index c0f557e..0f788ba 100644 --- a/tests/ifconfig_out.py +++ b/tests/ifconfig_out.py @@ -132,6 +132,72 @@ lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384 """ # noqa +MACOSX2 = """ +lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384 + options=1203<RXCSUM,TXCSUM,TXSTATUS,SW_TIMESTAMP> + inet 127.0.0.1 netmask 0xff000000 + inet6 ::1 prefixlen 128 + inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 + inet 127.0.1.99 netmask 0xff000000 + nd6 options=201<PERFORMNUD,DAD> +en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 + ether 8c:85:90:00:aa:bb + inet6 fe80::1c8b:e7cc:c695:a6de%en0 prefixlen 64 secured scopeid 0x6 + inet 10.0.1.12 netmask 0xffff0000 broadcast 10.0.255.255 + inet6 2601:980:c000:7c5a:da:6a59:1e94:b03 prefixlen 64 autoconf secured + inet6 2601:980:c000:7c5a:fdb3:b90c:80d6:abcd prefixlen 64 deprecated autoconf temporary + inet6 2601:980:c000:7c5a:34b0:676d:93f7:0123 prefixlen 64 autoconf temporary + nd6 options=201<PERFORMNUD,DAD> + media: autoselect + status: active +en1: flags=963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX> mtu 1500 + options=60<TSO4,TSO6> + ether 7a:00:48:a1:b2:00 + media: autoselect <full-duplex> + status: inactive +p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304 + ether 0e:85:90:0f:ab:cd + media: autoselect + status: inactive +awdl0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1484 + ether 2e:51:48:37:99:0a + inet6 fe80::2c51:48ff:fe37:86f8%awdl0 prefixlen 64 scopeid 0xc + nd6 options=201<PERFORMNUD,DAD> + media: autoselect + status: active +bridge0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 + options=63<RXCSUM,TXCSUM,TSO4,TSO6> + ether 7a:00:48:c8:aa:bd + Configuration: + id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0 + maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200 + root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0 + ipfilter disabled flags 0x2 + member: en1 flags=3<LEARNING,DISCOVER> + ifmaxaddr 0 port 7 priority 0 path cost 0 + member: en2 flags=3<LEARNING,DISCOVER> + ifmaxaddr 0 port 8 priority 0 path cost 0 + member: en3 flags=3<LEARNING,DISCOVER> + ifmaxaddr 0 port 9 priority 0 path cost 0 + member: en4 flags=3<LEARNING,DISCOVER> + ifmaxaddr 0 port 10 priority 0 path cost 0 + nd6 options=201<PERFORMNUD,DAD> + media: <unknown type> + status: inactive +utun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 2000 + inet6 fe80::ebb7:7d4a:49e8:e4fc%utun0 prefixlen 64 scopeid 0xe + nd6 options=201<PERFORMNUD,DAD> +vboxnet0: flags=8842<BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 + ether 0a:00:27:00:00:00 +en5: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 + ether ac:de:48:00:22:11 + inet6 fe80::aede:48ff:fe00:2211%en5 prefixlen 64 scopeid 0x5 + nd6 options=281<PERFORMNUD,INSECURE,DAD> + media: autoselect + status: active +""" + + ROUTE_OUTPUT = """ Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface diff --git a/tests/ifconfig_tests.py b/tests/ifconfig_tests.py index 1b3c324..dc662d3 100644 --- a/tests/ifconfig_tests.py +++ b/tests/ifconfig_tests.py @@ -88,6 +88,16 @@ class IfcfgTestCase(IfcfgTestCase): eq_(interfaces['en0']['broadcast'], '192.168.0.255') eq_(interfaces['en0']['netmask'], '255.255.255.0') + def test_macosx2(self): + ifcfg.distro = 'MacOSX' + ifcfg.Parser = ifcfg.get_parser_class() + parser = ifcfg.get_parser(ifconfig=ifconfig_out.MACOSX2) + interfaces = parser.interfaces + self.assertEqual(len(interfaces.keys()), 9) + eq_(interfaces['lo0']['inet'], '127.0.0.1') + eq_(interfaces['lo0']['inet4'], ['127.0.0.1', '127.0.1.99']) + eq_(interfaces['lo0']['netmask'], '255.0.0.0') + def test_default_interface(self): ifcfg.distro = 'Linux' ifcfg.Parser = ifcfg.get_parser_class() diff --git a/tests/ip_out.py b/tests/ip_out.py index 05ef84a..b4721e3 100644 --- a/tests/ip_out.py +++ b/tests/ip_out.py @@ -27,6 +27,18 @@ LINUX = """1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN g link/ether a0:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff """ +LINUX_MULTI_IPV4 = """ +2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 + link/ether b8:27:eb:50:39:69 brd ff:ff:ff:ff:ff:ff + inet 192.168.13.1/24 brd 192.168.13.255 scope global eth0 + valid_lft forever preferred_lft forever + inet 192.168.10.3/24 scope global eth0 + valid_lft forever preferred_lft forever + inet6 fe80::ba27:ebff:fe50:3969/64 scope link + valid_lft forever preferred_lft forever +""" + + ROUTE_OUTPUT = """ Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface diff --git a/tests/ip_tests.py b/tests/ip_tests.py index 7f6f8fe..dbe9344 100644 --- a/tests/ip_tests.py +++ b/tests/ip_tests.py @@ -31,6 +31,17 @@ class IpTestCase(IfcfgTestCase): eq_(interfaces['wlp3s0']['broadcast'], '192.168.12.255') eq_(interfaces['wlp3s0']['netmask'], '/24') + def test_linux_multi_inet4(self): + ifcfg.Parser = UnixIPParser + parser = ifcfg.get_parser(ifconfig=ip_out.LINUX_MULTI_IPV4) + interfaces = parser.interfaces + # Connected interface + eq_(interfaces['eth0']['ether'], 'b8:27:eb:50:39:69') + eq_(interfaces['eth0']['inet'], '192.168.13.1') + eq_(interfaces['eth0']['inet4'], ['192.168.13.1', '192.168.10.3']) + eq_(interfaces['eth0']['broadcast'], '192.168.13.255') + eq_(interfaces['eth0']['netmask'], '/24') + def test_default_interface(self): ifcfg.distro = 'Linux' ifcfg.Parser = UnixIPParser
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 2 }
0.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "nose", "coverage", "mock", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 -e git+https://github.com/ftao/python-ifcfg.git@3ae952775f66dc476ddb8f02953714e7676c9cff#egg=ifcfg importlib-metadata==4.8.3 iniconfig==1.1.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: python-ifcfg channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/python-ifcfg
[ "tests/ifconfig_tests.py::IfcfgTestCase::test_macosx2", "tests/ip_tests.py::IpTestCase::test_linux_multi_inet4" ]
[]
[ "tests/ifconfig_tests.py::IfcfgTestCase::test_default_interface", "tests/ifconfig_tests.py::IfcfgTestCase::test_ifcfg", "tests/ifconfig_tests.py::IfcfgTestCase::test_illegal", "tests/ifconfig_tests.py::IfcfgTestCase::test_linux", "tests/ifconfig_tests.py::IfcfgTestCase::test_linux2", "tests/ifconfig_tests.py::IfcfgTestCase::test_linux3", "tests/ifconfig_tests.py::IfcfgTestCase::test_linuxdocker", "tests/ifconfig_tests.py::IfcfgTestCase::test_macosx", "tests/ifconfig_tests.py::IfcfgTestCase::test_unknown", "tests/ip_tests.py::IpTestCase::test_default_interface", "tests/ip_tests.py::IpTestCase::test_ifcfg", "tests/ip_tests.py::IpTestCase::test_linux" ]
[]
BSD 3-Clause "New" or "Revised" License
2,573
[ "README.rst", "src/ifcfg/parser.py" ]
[ "README.rst", "src/ifcfg/parser.py" ]
dask__dask-3522
771a045cd9196b37af54bee16761da7330c943a6
2018-05-23 02:28:15
279fdf7a6a78a1dfaa0974598aead3e1b44f9194
diff --git a/dask/dataframe/core.py b/dask/dataframe/core.py index 5c55ab9b4..54f256c24 100644 --- a/dask/dataframe/core.py +++ b/dask/dataframe/core.py @@ -2565,7 +2565,7 @@ class DataFrame(_Frame): df2 = self._meta.assign(**_extract_meta(kwargs)) return elemwise(methods.assign, self, *pairs, meta=df2) - @derived_from(pd.DataFrame) + @derived_from(pd.DataFrame, ua_args=['index']) def rename(self, index=None, columns=None): if index is not None: raise ValueError("Cannot rename index.") @@ -3536,7 +3536,17 @@ def apply_and_enforce(func, args, kwargs, meta): if isinstance(df, (pd.DataFrame, pd.Series, pd.Index)): if len(df) == 0: return meta - c = meta.columns if isinstance(df, pd.DataFrame) else meta.name + + if isinstance(df, pd.DataFrame): + # Need nan_to_num otherwise nan comparison gives False + if not np.array_equal(np.nan_to_num(meta.columns), + np.nan_to_num(df.columns)): + raise ValueError("The columns in the computed data do not match" + " the columns in the provided metadata") + else: + c = meta.columns + else: + c = meta.name return _rename(c, df) return df diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index df2d77421..6bc853540 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -14,6 +14,7 @@ Dataframe +++++++++ - Add to/read_json (:pr:`3494`) `Martin Durant`_ +- Adds ``index`` to unsupported arguments for ``DataFrame.rename`` method (:pr:`3522`) `James Bourbeau`_ Bag +++
dask.dataframe.DataFrame.rename not allowed Is it really not allowed to rename columns of Dask DataFrame's? The code to reproduce it: ```python import pandas as pd import dask.dataframe as dd df1 = pd.DataFrame(data={'a':[1,2,3],'b':[10,20,30]}) dd1 = dd.from_pandas(df1, npartitions=3) dd1.rename(index=str, columns={'a':'A'}) ``` gives > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "/path/to/Python-3.6.3/lib/python3.6/site-packages/dask/dataframe/core.py", line 2565, in rename > raise ValueError("Cannot rename index.") > ValueError: Cannot rename index. The corresponding line in the core.py says: ```python if index is not None: raise ValueError("Cannot rename index.") ``` However, even Dask's own documentation examples allow `index=str`: http://dask.pydata.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.rename
dask/dask
diff --git a/dask/dataframe/io/tests/test_io.py b/dask/dataframe/io/tests/test_io.py index adee19cb3..0c8e582ee 100644 --- a/dask/dataframe/io/tests/test_io.py +++ b/dask/dataframe/io/tests/test_io.py @@ -514,6 +514,29 @@ def test_from_delayed(): assert str(e.value).startswith('Metadata mismatch found in `from_delayed`') +def test_from_delayed_misordered_meta(): + df = pd.DataFrame( + columns=['(1)', '(2)', 'date', 'ent', 'val'], + data=[range(i * 5, i * 5 + 5) for i in range(3)], + index=range(3) + ) + + # meta with different order for columns + misordered_meta = pd.DataFrame( + columns=['date', 'ent', 'val', '(1)', '(2)'], + data=[range(5)] + ) + + ddf = dd.from_delayed([delayed(lambda: df)()], meta=misordered_meta) + + with pytest.raises(ValueError) as info: + #produces dataframe which does not match meta + ddf.reset_index().compute() + msg = "The columns in the computed data do not match the columns in the" \ + " provided metadata" + assert msg in str(info.value) + + def test_from_delayed_sorted(): a = pd.DataFrame({'x': [1, 2]}, index=[1, 10]) b = pd.DataFrame({'x': [4, 1]}, index=[100, 200])
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
0.17
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "flake8", "pytest-xdist", "moto" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work boto3==1.23.10 botocore==1.26.10 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 click==8.0.4 cloudpickle==2.2.1 cryptography==40.0.2 -e git+https://github.com/dask/dask.git@771a045cd9196b37af54bee16761da7330c943a6#egg=dask dataclasses==0.8 distributed==1.21.8 execnet==1.9.0 flake8==5.0.4 HeapDict==1.0.1 idna==3.10 importlib-metadata==4.2.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.0.3 jmespath==0.10.0 locket==1.0.0 MarkupSafe==2.0.1 mccabe==0.7.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work moto==4.0.13 msgpack==1.0.5 numpy==1.19.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 partd==1.2.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==7.0.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work pycodestyle==2.9.1 pycparser==2.21 pyflakes==2.5.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.27.1 responses==0.17.0 s3transfer==0.5.2 six==1.17.0 sortedcontainers==2.4.0 tblib==1.7.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work toolz==0.12.0 tornado==6.1 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 Werkzeug==2.0.3 xmltodict==0.14.2 zict==2.1.0 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - boto3==1.23.10 - botocore==1.26.10 - cffi==1.15.1 - charset-normalizer==2.0.12 - click==8.0.4 - cloudpickle==2.2.1 - cryptography==40.0.2 - dataclasses==0.8 - distributed==1.21.8 - execnet==1.9.0 - flake8==5.0.4 - heapdict==1.0.1 - idna==3.10 - importlib-metadata==4.2.0 - jinja2==3.0.3 - jmespath==0.10.0 - locket==1.0.0 - markupsafe==2.0.1 - mccabe==0.7.0 - moto==4.0.13 - msgpack==1.0.5 - numpy==1.19.5 - pandas==1.1.5 - partd==1.2.0 - psutil==7.0.0 - pycodestyle==2.9.1 - pycparser==2.21 - pyflakes==2.5.0 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.27.1 - responses==0.17.0 - s3transfer==0.5.2 - six==1.17.0 - sortedcontainers==2.4.0 - tblib==1.7.0 - toolz==0.12.0 - tornado==6.1 - urllib3==1.26.20 - werkzeug==2.0.3 - xmltodict==0.14.2 - zict==2.1.0 prefix: /opt/conda/envs/dask
[ "dask/dataframe/io/tests/test_io.py::test_from_delayed_misordered_meta" ]
[]
[ "dask/dataframe/io/tests/test_io.py::test_meta_from_array", "dask/dataframe/io/tests/test_io.py::test_meta_from_1darray", "dask/dataframe/io/tests/test_io.py::test_meta_from_recarray", "dask/dataframe/io/tests/test_io.py::test_from_array", "dask/dataframe/io/tests/test_io.py::test_from_array_with_record_dtype", "dask/dataframe/io/tests/test_io.py::test_from_pandas_dataframe", "dask/dataframe/io/tests/test_io.py::test_from_pandas_small", "dask/dataframe/io/tests/test_io.py::test_from_pandas_series", "dask/dataframe/io/tests/test_io.py::test_from_pandas_non_sorted", "dask/dataframe/io/tests/test_io.py::test_from_pandas_single_row", "dask/dataframe/io/tests/test_io.py::test_from_pandas_with_datetime_index", "dask/dataframe/io/tests/test_io.py::test_DataFrame_from_dask_array", "dask/dataframe/io/tests/test_io.py::test_Series_from_dask_array", "dask/dataframe/io/tests/test_io.py::test_from_dask_array_compat_numpy_array", "dask/dataframe/io/tests/test_io.py::test_from_dask_array_compat_numpy_array_1d", "dask/dataframe/io/tests/test_io.py::test_from_dask_array_struct_dtype", "dask/dataframe/io/tests/test_io.py::test_from_dask_array_unknown_chunks", "dask/dataframe/io/tests/test_io.py::test_to_bag", "dask/dataframe/io/tests/test_io.py::test_to_records", "dask/dataframe/io/tests/test_io.py::test_from_delayed", "dask/dataframe/io/tests/test_io.py::test_from_delayed_sorted", "dask/dataframe/io/tests/test_io.py::test_to_delayed", "dask/dataframe/io/tests/test_io.py::test_to_delayed_optimize_graph" ]
[]
BSD 3-Clause "New" or "Revised" License
2,574
[ "dask/dataframe/core.py", "docs/source/changelog.rst" ]
[ "dask/dataframe/core.py", "docs/source/changelog.rst" ]
tomMoral__loky-128
7e46ee602a23251f476312357c00fd13f77f9938
2018-05-23 10:17:18
1bf741a4796d15c517902a3331b5bd9e86502037
ogrisel: > For the future, should we do the same as in joblib and run the test of joblib as part of the CI? I agree but let's do that in another PR.
diff --git a/loky/backend/semaphore_tracker.py b/loky/backend/semaphore_tracker.py index 79587f2..f494237 100644 --- a/loky/backend/semaphore_tracker.py +++ b/loky/backend/semaphore_tracker.py @@ -203,7 +203,6 @@ def main(fd): try: sem_unlink(name) if VERBOSE: # pragma: no cover - name = name.decode('ascii') sys.stderr.write("[SemaphoreTracker] unlink {}\n" .format(name)) sys.stderr.flush() diff --git a/loky/backend/semlock.py b/loky/backend/semlock.py index c94c4cd..2d35f6a 100644 --- a/loky/backend/semlock.py +++ b/loky/backend/semlock.py @@ -68,7 +68,7 @@ if sys.version_info[:2] < (3, 3): def sem_unlink(name): - if pthread.sem_unlink(name) < 0: + if pthread.sem_unlink(name.encode('ascii')) < 0: raiseFromErrno() @@ -153,8 +153,8 @@ class SemLock(object): self.ident = 0 self.kind = kind self.maxvalue = maxvalue - self.name = name.encode('ascii') - self.handle = _sem_open(self.name, value) + self.name = name + self.handle = _sem_open(self.name.encode('ascii'), value) def __del__(self): try: @@ -265,7 +265,7 @@ class SemLock(object): self.kind = kind self.maxvalue = maxvalue self.name = name - self.handle = _sem_open(name) + self.handle = _sem_open(name.encode('ascii')) return self diff --git a/loky/backend/synchronize.py b/loky/backend/synchronize.py index 2cdb43d..4773b9d 100644 --- a/loky/backend/synchronize.py +++ b/loky/backend/synchronize.py @@ -121,8 +121,7 @@ class SemLock(object): @staticmethod def _make_name(): # OSX does not support long names for semaphores - name = '/loky-%i-%s' % (os.getpid(), next(SemLock._rand)) - return name + return '/loky-%i-%s' % (os.getpid(), next(SemLock._rand)) #
loky.backend.semaphore_tracker.sem_unlink does not have same signature if coming from ctypes or _multiprocessing * `_multi_processing.sem_unlink` takes `str` * `loky.backend.semlock.sem_unlink` comes from `ctypes` and take `bytes`. It feels like some code was written with the ctypes variant in mind and raise an error when the `_multiprocessing.sem_unlink` is called. Tests seem to be only testing `loky.backend.semlock.sem_unlink`. #### Context This is an error I just saw in a joblib Travis [build](https://travis-ci.org/joblib/joblib/jobs/346847911#L4044). Note this is with loky version 1.2.1. ``` E /home/travis/build/joblib/joblib/joblib/externals/loky/backend/semaphore_tracker.py:195: UserWarning: semaphore_tracker: There appear to be 6 leaked semaphores to clean up at shutdown E len(cache)) E /home/travis/build/joblib/joblib/joblib/externals/loky/backend/semaphore_tracker.py:211: UserWarning: semaphore_tracker: b'/loky-5456-6haleho6': TypeError('argument 1 must be str, not bytes',) E warnings.warn('semaphore_tracker: %r: %r' % (name, e)) ``` Quickly looking at it, it seems like this is still in master. The code where the warning happens is here: https://github.com/tomMoral/loky/blob/dec1c8144b12938dfe7bfc511009e12f25fd1cd9/loky/backend/semaphore_tracker.py#L203-L211
tomMoral/loky
diff --git a/tests/test_synchronize.py b/tests/test_synchronize.py index 797070d..4794f17 100644 --- a/tests/test_synchronize.py +++ b/tests/test_synchronize.py @@ -22,7 +22,7 @@ if sys.version_info < (3, 3): @pytest.mark.skipif(sys.platform == "win32", reason="UNIX test") def test_semlock_failure(): from loky.backend.semlock import SemLock, sem_unlink - name = "test1" + name = "loky-test-semlock" sl = SemLock(0, 1, 1, name=name) with pytest.raises(FileExistsError): @@ -30,7 +30,7 @@ def test_semlock_failure(): sem_unlink(sl.name) with pytest.raises(FileNotFoundError): - SemLock._rebuild(None, 0, 0, name.encode('ascii')) + SemLock._rebuild(None, 0, 0, name) def assert_sem_value_equal(sem, value):
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 3 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "psutil", "pytest-timeout", "coverage" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 cloudpickle==2.2.1 coverage==6.2 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/tomMoral/loky.git@7e46ee602a23251f476312357c00fd13f77f9938#egg=loky more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==7.0.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-timeout==2.1.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: loky channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - cloudpickle==2.2.1 - coverage==6.2 - psutil==7.0.0 - pytest-timeout==2.1.0 prefix: /opt/conda/envs/loky
[ "tests/test_synchronize.py::test_semlock_failure" ]
[]
[ "tests/test_synchronize.py::TestLock::test_lock", "tests/test_synchronize.py::TestLock::test_rlock", "tests/test_synchronize.py::TestLock::test_lock_context", "tests/test_synchronize.py::TestSemaphore::test_semaphore", "tests/test_synchronize.py::TestSemaphore::test_bounded_semaphore", "tests/test_synchronize.py::TestSemaphore::test_timeout", "tests/test_synchronize.py::TestCondition::test_notify", "tests/test_synchronize.py::TestCondition::test_notify_all", "tests/test_synchronize.py::TestCondition::test_timeout", "tests/test_synchronize.py::TestCondition::test_waitfor", "tests/test_synchronize.py::TestCondition::test_wait_result", "tests/test_synchronize.py::TestEvent::test_event" ]
[]
BSD 3-Clause "New" or "Revised" License
2,575
[ "loky/backend/semaphore_tracker.py", "loky/backend/semlock.py", "loky/backend/synchronize.py" ]
[ "loky/backend/semaphore_tracker.py", "loky/backend/semlock.py", "loky/backend/synchronize.py" ]
acorg__seqgen-2
2d2ddd5ea539ac58c29facbb017815aae2ff0354
2018-05-23 14:34:47
2d2ddd5ea539ac58c29facbb017815aae2ff0354
diff --git a/.gitignore b/.gitignore index 4234921..29b9dee 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ __pycache__ build dist seqgen.egg-info +.pytest_cache diff --git a/README.md b/README.md index 2ae492c..af241af 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ optional arguments: 100) ``` -## Sequence spefication +## Sequence specification Your JSON specifies what sequences you want created. @@ -148,6 +148,11 @@ specification keys you can put in a object in the JSON is as follows: an internal name. * `random aa`: The sequence should be made of random amino acids. * `random nt`: The sequence should be made of random nucleotides. +* `ratchet`: If `true` and a count and mutation rate are given, sequences + after the first will be mutants of the previous sequence. This can be + used to build a series of sequences that are successive mutants of one + another. For the name derivation, see + [Muller's Ratchet](https://en.wikipedia.org/wiki/Muller's_ratchet). * `sections`: Gives a list of sequence sections used to build up another sequence (see example above). Each section is a JSON object that may contain the keys present in a regular sequence object, excluding `count`, diff --git a/seqgen/__init__.py b/seqgen/__init__.py index 58c2ae3..285814d 100644 --- a/seqgen/__init__.py +++ b/seqgen/__init__.py @@ -2,6 +2,6 @@ from seqgen.sequences import Sequences # Note that the version string must have the following format, otherwise it # will not be found by the version() function in ../setup.py -__version__ = '1.0.10' +__version__ = '1.0.11' __all__ = ['Sequences'] diff --git a/seqgen/sequences.py b/seqgen/sequences.py index 7e31515..3af0d90 100644 --- a/seqgen/sequences.py +++ b/seqgen/sequences.py @@ -23,6 +23,7 @@ class Sequences(object): DEFAULT_LENGTH = 100 DEFAULT_ID_PREFIX = 'seq-id-' LEGAL_SPEC_KEYS = { + 'alphabet', 'count', 'description', 'id', @@ -33,12 +34,14 @@ class Sequences(object): 'name', 'random aa', 'random nt', + 'ratchet', 'sections', 'sequence', 'sequence file', 'skip', } LEGAL_SPEC_SECTION_KEYS = { + 'alphabet', 'from name', 'length', 'mutation rate', @@ -82,8 +85,30 @@ class Sequences(object): self._vars = vars_ self._sequenceSpecs = list(map(self._expandSpec, sequenceSpecs)) self._checkKeys() + self._checkValid() self._names = {} + def _checkValid(self): + """ + Check that all specification dicts contain sensible values. + + @param sequenceSpec: A C{dict} with information about the sequences + to be produced. + @raise ValueError: If any problem is found. + """ + for specCount, spec in enumerate(self._sequenceSpecs, start=1): + if spec.get('ratchet'): + nSequences = spec.get('count', 1) + if nSequences == 1: + raise ValueError( + 'Sequence specification %d is specified as ratchet ' + 'but its count is only 1.' % specCount) + + if 'mutation rate' not in spec: + raise ValueError( + 'Sequence specification %d is specified as ratchet ' + 'but does not give a mutation rate.' % specCount) + def _checkKeys(self): """ Check that all specification dicts only contain legal keys. @@ -147,11 +172,15 @@ class Sequences(object): new[k] = value return new - def _specToRead(self, spec): + def _specToRead(self, spec, previousRead=None): """ Get a sequence from a specification. @param spec: A C{dict} with keys/values specifying a sequence. + @param previousRead: If not C{None}, a {dark.Read} instance containing + the last read this method returned. This is only used when + 'ratchet' is given for a specification, in which case we generate + a mutant based on the previous read. @raise ValueError: If the section spec refers to a non-existent other sequence, or to part of another sequence but the requested part exceeds the bounds of the other sequence. Or if the C{spec} does @@ -159,10 +188,14 @@ class Sequences(object): to. @return: A C{dark.Read} instance. """ - nt = True + alphabet = self.NT length = spec.get('length', self._defaultLength) - if 'from name' in spec: + if spec.get('ratchet') and previousRead: + read = Read(None, previousRead.sequence) + alphabet = previousRead.alphabet + + elif 'from name' in spec: name = spec['from name'] try: namedRead = self._names[name] @@ -176,6 +209,7 @@ class Sequences(object): # named read. length = spec.get('length', len(namedRead)) sequence = namedRead.sequence[index:index + length] + alphabet = namedRead.alphabet if len(sequence) != length: raise ValueError( @@ -201,37 +235,39 @@ class Sequences(object): raise ValueError("Sequence file '%s' could not be read." % spec['sequence file']) + elif spec.get('alphabet'): + alphabet = spec['alphabet'] + read = Read(None, ''.join(choice(alphabet) for _ in range(length))) + elif spec.get('random aa'): - read = Read(None, ''.join(choice(self.AA) for _ in range(length))) - nt = False + alphabet = self.AA + read = Read(None, ''.join(choice(alphabet) for _ in range(length))) else: - # Assume random nucleotides are wanted. - read = Read(None, ''.join(choice(self.NT) for _ in range(length))) + read = Read(None, ''.join(choice(alphabet) for _ in range(length))) try: rate = spec['mutation rate'] except KeyError: pass else: - read.sequence = self._mutate(read.sequence, rate, nt) + read.sequence = self._mutate(read.sequence, rate, alphabet) + + read.alphabet = alphabet return read - def _mutate(self, sequence, rate, nt): + def _mutate(self, sequence, rate, alphabet): """ Mutate a sequence at a certain rate. @param sequence: A C{str} nucleotide or amino acid sequence. @param rate: A C{float} mutation rate. - @param nt: If C{True} the sequence is nucleotides, else amino acids. + @param alphabet: A C{list} of alphabet letters. @return: The mutatated C{str} sequence. """ result = [] - if nt: - possibles = set(self.NT) - else: - possibles = set(self.AA) + possibles = set(alphabet) for current in sequence: if uniform(0.0, 1.0) < rate: result.append(choice(list(possibles - {current}))) @@ -247,17 +283,24 @@ class Sequences(object): @param sequenceSpec: A C{dict} with information about the sequences to be produced. """ + alphabet = None + previousRead = None nSequences = spec.get('count', 1) for count in range(nSequences): id_ = None if 'sections' in spec: sequence = '' for section in spec['sections']: - sequence += self._specToRead(section).sequence + read = self._specToRead( + section, previousRead) + sequence += read.sequence + if alphabet is None: + alphabet = read.alphabet else: - read = self._specToRead(spec) + read = self._specToRead(spec, previousRead) sequence = read.sequence id_ = read.id + alphabet = read.alphabet if id_ is None: try: @@ -284,6 +327,7 @@ class Sequences(object): pass read = Read(id_, sequence) + read.alphabet = alphabet # Keep a reference to this result if it is named. if count == 0 and 'name' in spec: @@ -296,6 +340,7 @@ class Sequences(object): if not spec.get('skip'): yield read + previousRead = read def __iter__(self): for sequenceSpec in self._sequenceSpecs:
Add a 'linear' directive to allow a set of mutant sequences to be successively generated from the previous one
acorg/seqgen
diff --git a/test/testSequences.py b/test/testSequences.py index 5e9e4ef..b4b839d 100644 --- a/test/testSequences.py +++ b/test/testSequences.py @@ -33,7 +33,7 @@ class TestSequences(TestCase): If the specification is not valid JSON, a ValueError must be raised. """ if PY3: - error = '^Expecting value: line 1 column 1 \(char 0\)$' + error = '^Expecting value: line 1 column 1 \\(char 0\\)$' else: error = '^No JSON object could be decoded$' assertRaisesRegex(self, ValueError, error, Sequences, @@ -45,7 +45,7 @@ class TestSequences(TestCase): If the JSON specification has no 'sequences' key, a ValueError must be raised. """ - error = "^The specification JSON must have a 'sequences' key\.$" + error = "^The specification JSON must have a 'sequences' key\\.$" assertRaisesRegex(self, ValueError, error, Sequences, spec='filename') @@ -57,7 +57,7 @@ class TestSequences(TestCase): must be raised. """ s = Sequences(spec='filename') - error = "^Name 'a' is duplicated in the JSON specification\.$" + error = "^Name 'a' is duplicated in the JSON specification\\.$" assertRaisesRegex(self, ValueError, error, list, s) def testNoSequences(self): @@ -137,18 +137,53 @@ class TestSequences(TestCase): } ] }''')) - error = ("^Sequence with id 'the-id' has a count of 6\. If you want " - "to specify one sequence with an id, the count must be 1\. " + error = ("^Sequence with id 'the-id' has a count of 6\\. If you want " + "to specify one sequence with an id, the count must be 1\\. " "To specify multiple sequences with an id prefix, use " - "'id prefix'\.$") + "'id prefix'\\.$") assertRaisesRegex(self, ValueError, error, list, s) + def testRatchetWithNoCount(self): + """ + If ratchet is specified for seqeunce spec its count must be greater + than one. + """ + spec = StringIO('''{ + "sequences": [ + { + "id": "xxx", + "ratchet": true + } + ] + }''') + error = ("^Sequence specification 1 is specified as ratchet but its " + "count is only 1\\.$") + assertRaisesRegex(self, ValueError, error, Sequences, spec) + + def testRatchetWithNoMutationRate(self): + """ + If ratchet is specified for seqeunce spec it must have a mutation + rate. + """ + spec = StringIO('''{ + "sequences": [ + { + "count": 4, + "id": "xxx", + "ratchet": true + } + ] + }''') + error = ("^Sequence specification 1 is specified as ratchet but does " + "not give a mutation rate\\.$") + assertRaisesRegex(self, ValueError, error, Sequences, spec) + def testUnknownSpecificationKey(self): """ If an unknown key is given in a sequence specification, a ValueError must be raised. """ - error = "^Sequence specification 1 contains an unknown key: dog\.$" + error = "^Sequence specification 1 contains an unknown key: dog\\.$" assertRaisesRegex(self, ValueError, error, Sequences, StringIO('''{ "sequences": [ { @@ -164,7 +199,7 @@ class TestSequences(TestCase): """ for key in 'id', 'id prefix', 'name': error = ("^Section 1 of sequence specification 1 contains an " - "unknown key: %s\.$" % key) + "unknown key: %s\\.$" % key) assertRaisesRegex(self, ValueError, error, Sequences, StringIO('''{ "sequences": [ { @@ -177,6 +212,34 @@ class TestSequences(TestCase): ] }''' % key)) + def testOneLetterAlphabet(self): + """ + It must be possible to specify an alphabet with just one symbol. + """ + s = Sequences(StringIO('''{ + "sequences": [ + { + "alphabet": "0" + } + ] + }'''), defaultLength=500) + (read,) = list(s) + self.assertEqual('0' * 500, read.sequence) + + def testTwoLetterAlphabet(self): + """ + It must be possible to specify an alphabet with two symbols. + """ + s = Sequences(StringIO('''{ + "sequences": [ + { + "alphabet": "01" + } + ] + }'''), defaultLength=500) + (read,) = list(s) + self.assertTrue(x in '01' for x in read.sequence) + def testOneSequenceIdOnlyDefaultLength(self): """ If only one sequence is specified, and only by id, one sequence @@ -526,7 +589,7 @@ class TestSequences(TestCase): ] }''')) error = ("^Sequence section refers to name 'xxx' of " - "non-existent other sequence\.$") + "non-existent other sequence\\.$") assertRaisesRegex(self, ValueError, error, list, s) def testSectionWithNameReferenceTooShort(self): @@ -552,7 +615,7 @@ class TestSequences(TestCase): }''')) error = ("^Sequence specification refers to sequence name 'xxx', " "starting at index 1 with length 10, but 'xxx' is not long " - "enough to support that\.$") + "enough to support that\\.$") assertRaisesRegex(self, ValueError, error, list, s) def testNamedRecombinant(self): @@ -636,3 +699,42 @@ class TestSequences(TestCase): diffs = sum((a != b) for (a, b) in zip(sequence, read.sequence)) self.assertEqual(len(sequence), len(read.sequence)) self.assertEqual(diffs, len(read.sequence)) + + def testRatchet(self): + """ + The ratchet specification must result in the expected result. + """ + # Note that this is a very simple test, using a 1.0 mutation rate + # and a fixed alphabet. + length = 50 + s = Sequences(StringIO('''{ + "sequences": [ + { + "name": "orig", + "alphabet": "01", + "length": %s + }, + { + "count": 2, + "from name": "orig", + "mutation rate": 1.0, + "ratchet": true + } + ] + }''' % length)) + (orig, mutant1, mutant2) = list(s) + # The distance from the original to the first mutant must be 100 (i.e., + # all bases). + diffCount = sum(a != b for (a, b) in + zip(orig.sequence, mutant1.sequence)) + self.assertEqual(length, diffCount) + + # The distance from the first mutant to the second must be 100 (i.e., + # all bases). + diffCount = sum(a != b for (a, b) in + zip(mutant1.sequence, mutant2.sequence)) + self.assertEqual(length, diffCount) + + # The sequences of the original and the second mutant must be + # identical. + self.assertEqual(orig.sequence, mutant2.sequence)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 4 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "dark-matter>=1.1.28" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall==0.2.0 biopython==1.79 bz2file==0.98 cachetools==4.2.4 certifi==2021.5.30 charset-normalizer==2.0.12 cycler==0.11.0 Cython==3.0.12 dark-matter==4.0.13 decorator==5.1.1 idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 kiwisolver==1.3.1 matplotlib==3.3.4 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work mysql-connector-python==8.0.11 numpy==1.19.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 Pillow==8.4.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work prompt-toolkit==3.0.36 protobuf==3.19.6 ptyprocess==0.7.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work Pygments==2.14.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pysam==0.23.0 pytest==6.2.4 python-dateutil==2.9.0.post0 pyzmq==25.1.2 requests==2.27.1 -e git+https://github.com/acorg/seqgen.git@2d2ddd5ea539ac58c29facbb017815aae2ff0354#egg=seqgen simplejson==3.20.1 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work traitlets==4.3.3 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 wcwidth==0.2.13 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: seqgen channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - backcall==0.2.0 - biopython==1.79 - bz2file==0.98 - cachetools==4.2.4 - charset-normalizer==2.0.12 - cycler==0.11.0 - cython==3.0.12 - dark-matter==4.0.13 - decorator==5.1.1 - idna==3.10 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - kiwisolver==1.3.1 - matplotlib==3.3.4 - mysql-connector-python==8.0.11 - numpy==1.19.5 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==8.4.0 - prompt-toolkit==3.0.36 - protobuf==3.19.6 - ptyprocess==0.7.0 - pygments==2.14.0 - pysam==0.23.0 - python-dateutil==2.9.0.post0 - pyzmq==25.1.2 - requests==2.27.1 - simplejson==3.20.1 - six==1.17.0 - traitlets==4.3.3 - urllib3==1.26.20 - wcwidth==0.2.13 prefix: /opt/conda/envs/seqgen
[ "test/testSequences.py::TestSequences::testOneLetterAlphabet", "test/testSequences.py::TestSequences::testRatchet", "test/testSequences.py::TestSequences::testRatchetWithNoCount", "test/testSequences.py::TestSequences::testRatchetWithNoMutationRate", "test/testSequences.py::TestSequences::testTwoLetterAlphabet" ]
[]
[ "test/testSequences.py::TestSequences::testDuplicatedName", "test/testSequences.py::TestSequences::testNamedRecombinant", "test/testSequences.py::TestSequences::testNoSequences", "test/testSequences.py::TestSequences::testNoSequencesKey", "test/testSequences.py::TestSequences::testNonExistentSpecificationFile", "test/testSequences.py::TestSequences::testNotJSON", "test/testSequences.py::TestSequences::testOneSectionRandomAAs", "test/testSequences.py::TestSequences::testOneSectionRandomNTs", "test/testSequences.py::TestSequences::testOneSectionWithLength", "test/testSequences.py::TestSequences::testOneSectionWithSequence", "test/testSequences.py::TestSequences::testOneSequenceAAOnly", "test/testSequences.py::TestSequences::testOneSequenceByLength", "test/testSequences.py::TestSequences::testOneSequenceIdAndCountGreaterThanOne", "test/testSequences.py::TestSequences::testOneSequenceIdOnly", "test/testSequences.py::TestSequences::testOneSequenceIdOnlyDefaultIdPrefix", "test/testSequences.py::TestSequences::testOneSequenceIdOnlyDefaultLength", "test/testSequences.py::TestSequences::testOneSequenceIdPrefix", "test/testSequences.py::TestSequences::testOneSequenceLengthIsAVariable", "test/testSequences.py::TestSequences::testOneSequenceNameOnly", "test/testSequences.py::TestSequences::testOneSequenceRandomNTs", "test/testSequences.py::TestSequences::testOneSequenceSequenceMutated", "test/testSequences.py::TestSequences::testOneSequenceSequenceOnly", "test/testSequences.py::TestSequences::testOneSequenceWithIdAndDescription", "test/testSequences.py::TestSequences::testRecombinantFromFullOtherSequences", "test/testSequences.py::TestSequences::testSectionWithNameReference", "test/testSequences.py::TestSequences::testSectionWithNameReferenceTooShort", "test/testSequences.py::TestSequences::testSectionWithUnknownNameReference", "test/testSequences.py::TestSequences::testTwoSectionsWithLengths", "test/testSequences.py::TestSequences::testTwoSequencesButSecondOneSkipped", "test/testSequences.py::TestSequences::testTwoSequencesByCount", "test/testSequences.py::TestSequences::testTwoSequencesSecondFromName", "test/testSequences.py::TestSequences::testTwoSequencesSecondOneNotSkipped", "test/testSequences.py::TestSequences::testTwoSequencesWithDifferentIdPrefixesAndCounts", "test/testSequences.py::TestSequences::testUnknownSectionKey", "test/testSequences.py::TestSequences::testUnknownSpecificationKey" ]
[]
MIT License
2,576
[ "seqgen/sequences.py", ".gitignore", "seqgen/__init__.py", "README.md" ]
[ "seqgen/sequences.py", ".gitignore", "seqgen/__init__.py", "README.md" ]
acorg__seqgen-4
fa23a119856b254988fc51a41835b927d516df53
2018-05-23 15:47:10
fa23a119856b254988fc51a41835b927d516df53
diff --git a/README.md b/README.md index af241af..40f7376 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,10 @@ specification keys you can put in a object in the JSON is as follows: * `name`: Give a name to the sequence so you can refer to it from elsewhere in the JSON. Note that this has nothing to do with FASTA ids, it is just an internal name. +* `name count`: An optional integer specifying which of a set of sequences + generated from the same specification should be named (assumes `name` + is also given). The default is to name the first sequence. Note that this + number is 1-based. Special values `first` and `last` are also allowed. * `random aa`: The sequence should be made of random amino acids. * `random nt`: The sequence should be made of random nucleotides. * `ratchet`: If `true` and a count and mutation rate are given, sequences diff --git a/seqgen/__init__.py b/seqgen/__init__.py index 285814d..51d6e92 100644 --- a/seqgen/__init__.py +++ b/seqgen/__init__.py @@ -2,6 +2,6 @@ from seqgen.sequences import Sequences # Note that the version string must have the following format, otherwise it # will not be found by the version() function in ../setup.py -__version__ = '1.0.11' +__version__ = '1.0.12' __all__ = ['Sequences'] diff --git a/seqgen/sequences.py b/seqgen/sequences.py index 3af0d90..b57ba6d 100644 --- a/seqgen/sequences.py +++ b/seqgen/sequences.py @@ -32,6 +32,7 @@ class Sequences(object): 'length', 'mutation rate', 'name', + 'name count', 'random aa', 'random nt', 'ratchet', @@ -88,6 +89,27 @@ class Sequences(object): self._checkValid() self._names = {} + def _nameCount(self, spec): + """ + Get the name count for a spec + + @param spec: A C{dict} with keys/values specifying a sequence. + @return: A 0-based integer count of the sequence index that should be + named or C{0} if there is no 'name count' directive in C{spec}. + """ + nSequences = spec.get('count', 1) + try: + nameCount = spec['name count'] + except KeyError: + return 0 + else: + if nameCount == 'first': + return 0 + elif nameCount == 'last': + return nSequences - 1 + else: + return nameCount - 1 + def _checkValid(self): """ Check that all specification dicts contain sensible values. @@ -96,6 +118,7 @@ class Sequences(object): to be produced. @raise ValueError: If any problem is found. """ + names = set() for specCount, spec in enumerate(self._sequenceSpecs, start=1): if spec.get('ratchet'): nSequences = spec.get('count', 1) @@ -109,6 +132,27 @@ class Sequences(object): 'Sequence specification %d is specified as ratchet ' 'but does not give a mutation rate.' % specCount) + nSequences = spec.get('count', 1) + + nameCount = self._nameCount(spec) + if nameCount is not None and nameCount >= nSequences: + raise ValueError( + 'Sequence specification %d will only produce %d ' + 'sequence%s but has a (too high) name count value of %d.' % + (specCount, nSequences, '' if nSequences == 1 else 's', + nameCount + 1)) + + try: + name = spec['name'] + except KeyError: + pass + else: + if name in names: + raise ValueError("Name '%s' is duplicated in the JSON " + "specification." % name) + else: + names.add(name) + def _checkKeys(self): """ Check that all specification dicts only contain legal keys. @@ -286,6 +330,8 @@ class Sequences(object): alphabet = None previousRead = None nSequences = spec.get('count', 1) + nameCount = self._nameCount(spec) + for count in range(nSequences): id_ = None if 'sections' in spec: @@ -329,14 +375,10 @@ class Sequences(object): read = Read(id_, sequence) read.alphabet = alphabet - # Keep a reference to this result if it is named. - if count == 0 and 'name' in spec: - name = spec['name'] - if name in self._names: - raise ValueError("Name '%s' is duplicated in the JSON " - "specification." % name) - else: - self._names[name] = read + # Keep a reference to this result if it is named and this is the + # sequence (by count) we want to name. + if 'name' in spec and nameCount == count: + self._names[spec['name']] = read if not spec.get('skip'): yield read
Add a 'name count' directive so a certain sequence in a spec can be named Currently we only assign the name of a named spec to the first sequence in that series. Make it so any one can be named.
acorg/seqgen
diff --git a/test/testSequences.py b/test/testSequences.py index b4b839d..a57de94 100644 --- a/test/testSequences.py +++ b/test/testSequences.py @@ -56,9 +56,8 @@ class TestSequences(TestCase): If a duplicate sequence name is present in the JSON, a ValueError must be raised. """ - s = Sequences(spec='filename') error = "^Name 'a' is duplicated in the JSON specification\\.$" - assertRaisesRegex(self, ValueError, error, list, s) + assertRaisesRegex(self, ValueError, error, Sequences, spec='filename') def testNoSequences(self): """ @@ -738,3 +737,138 @@ class TestSequences(TestCase): # The sequences of the original and the second mutant must be # identical. self.assertEqual(orig.sequence, mutant2.sequence) + + def testNameCountTooHigh(self): + """ + A name count value that is higher than the number of sequences in + a specification must result in a ValueError. + """ + spec = StringIO('''{ + "sequences": [ + { + "name": "orig", + "name count": 10, + "count": 2 + } + ] + }''') + error = ('^Sequence specification 1 will only produce 2 sequences but ' + 'has a \\(too high\\) name count value of 10\\.$') + assertRaisesRegex(self, ValueError, error, Sequences, spec) + + def testNameCountFirst(self): + """ + A name count value of 'first' must result in the first sequence of a + series being named. + """ + s = Sequences(StringIO('''{ + "sequences": [ + { + "name": "orig", + "name count": "first", + "count": 20, + "mutation rate": 0.1, + "length": 500, + "ratchet": true + }, + { + "id": "copy", + "from name": "orig" + } + ] + }''')) + reads = list(s) + copySequence = reads[-1].sequence + # The final sequence (the copy) must be the same as the first sequence + # (and no others). + self.assertEqual(reads[0].sequence, copySequence) + for i in range(1, 20): + self.assertNotEqual(reads[i].sequence, copySequence) + + def testNameCountLast(self): + """ + A name count value of 'last' must result in the last sequence of a + series being named. + """ + s = Sequences(StringIO('''{ + "sequences": [ + { + "name": "orig", + "name count": "last", + "count": 20, + "mutation rate": 0.1, + "length": 500, + "ratchet": true + }, + { + "id": "copy", + "from name": "orig" + } + ] + }''')) + reads = list(s) + copySequence = reads[-1].sequence + # The final sequence (the copy) must be the same as the second last + # (i.e., the final mutant) sequence (and no others). + self.assertEqual(reads[-2].sequence, copySequence) + for i in range(19): + self.assertNotEqual(reads[i].sequence, copySequence) + + def testNameCountOne(self): + """ + A name count value of 1 must result in the first sequence of a + series being named. + """ + s = Sequences(StringIO('''{ + "sequences": [ + { + "name": "orig", + "name count": 1, + "count": 20, + "mutation rate": 0.1, + "length": 500, + "ratchet": true + }, + { + "id": "copy", + "from name": "orig" + } + ] + }''')) + reads = list(s) + copySequence = reads[-1].sequence + # The final sequence (the copy) must be the same as the first sequence + # (and no others). + self.assertEqual(reads[0].sequence, copySequence) + for i in range(1, 20): + self.assertNotEqual(reads[i].sequence, copySequence) + + def testNameCountTwo(self): + """ + A name count value of 2 must result in the second sequence of a + series being named. + """ + s = Sequences(StringIO('''{ + "sequences": [ + { + "name": "orig", + "name count": 2, + "count": 20, + "mutation rate": 0.1, + "length": 500, + "ratchet": true + }, + { + "id": "copy", + "from name": "orig" + } + ] + }''')) + reads = list(s) + copySequence = reads[-1].sequence + # The final sequence (the copy) must be the same as the second sequence + # (and no others). + self.assertEqual(reads[1].sequence, copySequence) + self.assertNotEqual(reads[0].sequence, copySequence) + for i in range(2, 20): + self.assertNotEqual(reads[i].sequence, copySequence)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall==0.2.0 biopython==1.79 bz2file==0.98 cachetools==4.2.4 certifi==2021.5.30 charset-normalizer==2.0.12 cycler==0.11.0 Cython==3.0.12 dark-matter==4.0.13 decorator==5.1.1 idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 kiwisolver==1.3.1 matplotlib==3.3.4 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work mysql-connector-python==8.0.11 numpy==1.19.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 Pillow==8.4.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work prompt-toolkit==3.0.36 protobuf==3.19.6 ptyprocess==0.7.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work Pygments==2.14.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pysam==0.23.0 pytest==6.2.4 python-dateutil==2.9.0.post0 pyzmq==25.1.2 requests==2.27.1 -e git+https://github.com/acorg/seqgen.git@fa23a119856b254988fc51a41835b927d516df53#egg=seqgen simplejson==3.20.1 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work traitlets==4.3.3 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 wcwidth==0.2.13 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: seqgen channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - backcall==0.2.0 - biopython==1.79 - bz2file==0.98 - cachetools==4.2.4 - charset-normalizer==2.0.12 - cycler==0.11.0 - cython==3.0.12 - dark-matter==4.0.13 - decorator==5.1.1 - idna==3.10 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - kiwisolver==1.3.1 - matplotlib==3.3.4 - mysql-connector-python==8.0.11 - numpy==1.19.5 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==8.4.0 - prompt-toolkit==3.0.36 - protobuf==3.19.6 - ptyprocess==0.7.0 - pygments==2.14.0 - pysam==0.23.0 - python-dateutil==2.9.0.post0 - pyzmq==25.1.2 - requests==2.27.1 - simplejson==3.20.1 - six==1.17.0 - traitlets==4.3.3 - urllib3==1.26.20 - wcwidth==0.2.13 prefix: /opt/conda/envs/seqgen
[ "test/testSequences.py::TestSequences::testDuplicatedName", "test/testSequences.py::TestSequences::testNameCountFirst", "test/testSequences.py::TestSequences::testNameCountLast", "test/testSequences.py::TestSequences::testNameCountOne", "test/testSequences.py::TestSequences::testNameCountTooHigh", "test/testSequences.py::TestSequences::testNameCountTwo" ]
[]
[ "test/testSequences.py::TestSequences::testNamedRecombinant", "test/testSequences.py::TestSequences::testNoSequences", "test/testSequences.py::TestSequences::testNoSequencesKey", "test/testSequences.py::TestSequences::testNonExistentSpecificationFile", "test/testSequences.py::TestSequences::testNotJSON", "test/testSequences.py::TestSequences::testOneLetterAlphabet", "test/testSequences.py::TestSequences::testOneSectionRandomAAs", "test/testSequences.py::TestSequences::testOneSectionRandomNTs", "test/testSequences.py::TestSequences::testOneSectionWithLength", "test/testSequences.py::TestSequences::testOneSectionWithSequence", "test/testSequences.py::TestSequences::testOneSequenceAAOnly", "test/testSequences.py::TestSequences::testOneSequenceByLength", "test/testSequences.py::TestSequences::testOneSequenceIdAndCountGreaterThanOne", "test/testSequences.py::TestSequences::testOneSequenceIdOnly", "test/testSequences.py::TestSequences::testOneSequenceIdOnlyDefaultIdPrefix", "test/testSequences.py::TestSequences::testOneSequenceIdOnlyDefaultLength", "test/testSequences.py::TestSequences::testOneSequenceIdPrefix", "test/testSequences.py::TestSequences::testOneSequenceLengthIsAVariable", "test/testSequences.py::TestSequences::testOneSequenceNameOnly", "test/testSequences.py::TestSequences::testOneSequenceRandomNTs", "test/testSequences.py::TestSequences::testOneSequenceSequenceMutated", "test/testSequences.py::TestSequences::testOneSequenceSequenceOnly", "test/testSequences.py::TestSequences::testOneSequenceWithIdAndDescription", "test/testSequences.py::TestSequences::testRatchet", "test/testSequences.py::TestSequences::testRatchetWithNoCount", "test/testSequences.py::TestSequences::testRatchetWithNoMutationRate", "test/testSequences.py::TestSequences::testRecombinantFromFullOtherSequences", "test/testSequences.py::TestSequences::testSectionWithNameReference", "test/testSequences.py::TestSequences::testSectionWithNameReferenceTooShort", "test/testSequences.py::TestSequences::testSectionWithUnknownNameReference", "test/testSequences.py::TestSequences::testTwoLetterAlphabet", "test/testSequences.py::TestSequences::testTwoSectionsWithLengths", "test/testSequences.py::TestSequences::testTwoSequencesButSecondOneSkipped", "test/testSequences.py::TestSequences::testTwoSequencesByCount", "test/testSequences.py::TestSequences::testTwoSequencesSecondFromName", "test/testSequences.py::TestSequences::testTwoSequencesSecondOneNotSkipped", "test/testSequences.py::TestSequences::testTwoSequencesWithDifferentIdPrefixesAndCounts", "test/testSequences.py::TestSequences::testUnknownSectionKey", "test/testSequences.py::TestSequences::testUnknownSpecificationKey" ]
[]
MIT License
2,577
[ "seqgen/sequences.py", "seqgen/__init__.py", "README.md" ]
[ "seqgen/sequences.py", "seqgen/__init__.py", "README.md" ]
acorg__seqgen-6
a46ce6635de4e891fa252624c65d8070c073c802
2018-05-23 22:01:15
a46ce6635de4e891fa252624c65d8070c073c802
diff --git a/README.md b/README.md index 40f7376..9ca6f87 100644 --- a/README.md +++ b/README.md @@ -70,26 +70,24 @@ As an example, the JSON shown below specifies the following: }, "sequences": [ { - "name": "A", "id": "seq-A", "length": "%(length)d" }, { - "from name": "A", + "from id": "seq-A", "id prefix": "seq-A-mutant-", "length": "%(length)d", "count": 19, "mutation rate": 0.01 }, { - "name": "B", "id": "seq-B", - "from name": "A", + "from id": "A", "length": "%(length)d", "mutation rate": 0.15 }, { - "from name": "B", + "from id": "seq-B", "id prefix": "seq-B-mutant-", "length": "%(length)d", "count": 19, @@ -99,12 +97,12 @@ As an example, the JSON shown below specifies the following: "id": "recombinant", "sections": [ { - "from name": "A", + "from id": "seq-A", "start": 1, "length": 30 }, { - "from name": "B", + "from id": "seq-B", "start": 31, "length": 70 } @@ -129,29 +127,30 @@ There are many more small examples of usage in The sequence specification must be a list of objects. The full list of specification keys you can put in a object in the JSON is as follows: -* `count`: The number of sequences to generate from this object. If the - sequence specification also contains a `name`, the name will refer to the - first of the sequences generated by this object. +* `alphabet`: A string of characters from which sequences will be drawn + (see `random nt` and `random aa` below). +* `count`: The number of sequences to generate from this object. * `description`: The sequence description. This will be appended to the - FASTA id (separated by a space). + FASTA id (separated by a space). Note that if a sequence has a + description and you want to refer to it using `from id` (see below), you + must include its id and description, separated by a single space. * `id`: The FASTA id to give this sequence. * `id prefix`: The prefix of the FASTA ids to give a set of sequences. A count will be appended to this prefix. This is useful when you specify a `count` value. -* `from name`: The sequence should come from another (already named) - sequence in the JSON file. You give a name to a sequence using the `name` - key (below). +* `from id`: The sequence should be based on another (already named) + sequence in the JSON file. The value given should either be the exact + `id` of another sequence or else be the `id prefix` of another sequence + followed by a number. E.g., if you specify `"count": 10` and `"id + prefix": "my-id"` for a set of ten sequences, and want to refer to the + 3rd of them when specifying another sequence, you would use `"from id": + "my-id-3"`. The default id prefixes for sequences that are not given an + id explicity is `seq-id-`. * `length`: The sequence length. * `mutation rate`: A mutation rate to apply to the sequence. -* `name`: Give a name to the sequence so you can refer to it from elsewhere - in the JSON. Note that this has nothing to do with FASTA ids, it is just - an internal name. -* `name count`: An optional integer specifying which of a set of sequences - generated from the same specification should be named (assumes `name` - is also given). The default is to name the first sequence. Note that this - number is 1-based. Special values `first` and `last` are also allowed. * `random aa`: The sequence should be made of random amino acids. -* `random nt`: The sequence should be made of random nucleotides. +* `random nt`: The sequence should be made of random nucleotides. This is + the default. * `ratchet`: If `true` and a count and mutation rate are given, sequences after the first will be mutants of the previous sequence. This can be used to build a series of sequences that are successive mutants of one @@ -167,7 +166,7 @@ specification keys you can put in a object in the JSON is as follows: only the first sequence in the file is used. * `skip`: If `true` the sequence will not be output. This is useful either for temporarily omitting a sequence or for just giving a sequence (e.g., - one read from a file) a name so part of it can be used as a section of + one read from a file) an id so it can be used in the construction of another sequence. All specification keys are optional. A completely empty specification diff --git a/seqgen/__init__.py b/seqgen/__init__.py index 51d6e92..3614796 100644 --- a/seqgen/__init__.py +++ b/seqgen/__init__.py @@ -2,6 +2,6 @@ from seqgen.sequences import Sequences # Note that the version string must have the following format, otherwise it # will not be found by the version() function in ../setup.py -__version__ = '1.0.12' +__version__ = '1.0.13' __all__ = ['Sequences'] diff --git a/seqgen/sequences.py b/seqgen/sequences.py index b57ba6d..5c3a12a 100644 --- a/seqgen/sequences.py +++ b/seqgen/sequences.py @@ -28,11 +28,9 @@ class Sequences(object): 'description', 'id', 'id prefix', - 'from name', + 'from id', 'length', 'mutation rate', - 'name', - 'name count', 'random aa', 'random nt', 'ratchet', @@ -43,7 +41,7 @@ class Sequences(object): } LEGAL_SPEC_SECTION_KEYS = { 'alphabet', - 'from name', + 'from id', 'length', 'mutation rate', 'random aa', @@ -58,6 +56,7 @@ class Sequences(object): self._defaultIdPrefix = defaultIdPrefix or self.DEFAULT_ID_PREFIX self._readSpecification(spec) self._idPrefixCount = {} + self._sequences = {} def _readSpecification(self, spec): """ @@ -87,28 +86,6 @@ class Sequences(object): self._sequenceSpecs = list(map(self._expandSpec, sequenceSpecs)) self._checkKeys() self._checkValid() - self._names = {} - - def _nameCount(self, spec): - """ - Get the name count for a spec - - @param spec: A C{dict} with keys/values specifying a sequence. - @return: A 0-based integer count of the sequence index that should be - named or C{0} if there is no 'name count' directive in C{spec}. - """ - nSequences = spec.get('count', 1) - try: - nameCount = spec['name count'] - except KeyError: - return 0 - else: - if nameCount == 'first': - return 0 - elif nameCount == 'last': - return nSequences - 1 - else: - return nameCount - 1 def _checkValid(self): """ @@ -118,7 +95,7 @@ class Sequences(object): to be produced. @raise ValueError: If any problem is found. """ - names = set() + ids = set() for specCount, spec in enumerate(self._sequenceSpecs, start=1): if spec.get('ratchet'): nSequences = spec.get('count', 1) @@ -134,24 +111,27 @@ class Sequences(object): nSequences = spec.get('count', 1) - nameCount = self._nameCount(spec) - if nameCount is not None and nameCount >= nSequences: - raise ValueError( - 'Sequence specification %d will only produce %d ' - 'sequence%s but has a (too high) name count value of %d.' % - (specCount, nSequences, '' if nSequences == 1 else 's', - nameCount + 1)) - try: - name = spec['name'] + id_ = spec['id'] except KeyError: pass else: - if name in names: - raise ValueError("Name '%s' is duplicated in the JSON " - "specification." % name) - else: - names.add(name) + # If an id is given, the number of sequences requested must be + # one. + if nSequences != 1: + raise ValueError( + "Sequence specification %d with id '%s' has a count " + "of %d. If you want to specify a sequence with an " + "id, the count must be 1. To specify multiple " + "sequences with an id prefix, use 'id prefix'." % + (specCount, id_, nSequences)) + + if id_ in ids: + raise ValueError( + "Sequence specification %d has an id (%s) that has " + "already been used." % (specCount, id_)) + + ids.add(id_) def _checkKeys(self): """ @@ -239,28 +219,28 @@ class Sequences(object): read = Read(None, previousRead.sequence) alphabet = previousRead.alphabet - elif 'from name' in spec: - name = spec['from name'] + elif 'from id' in spec: + fromId = spec['from id'] try: - namedRead = self._names[name] + fromRead = self._sequences[fromId] except KeyError: - raise ValueError("Sequence section refers to name '%s' of " - "non-existent other sequence." % name) + raise ValueError("Sequence section refers to the id '%s' of " + "non-existent other sequence." % fromId) else: # The start offset in the spec is 1-based. Convert to 0-based. index = int(spec.get('start', 1)) - 1 # Use the given length (if any) else the length of the # named read. - length = spec.get('length', len(namedRead)) - sequence = namedRead.sequence[index:index + length] - alphabet = namedRead.alphabet + length = spec.get('length', len(fromRead)) + sequence = fromRead.sequence[index:index + length] + alphabet = fromRead.alphabet if len(sequence) != length: raise ValueError( - "Sequence specification refers to sequence name '%s', " - "starting at index %d with length %d, but '%s' " - "is not long enough to support that." % - (name, index + 1, length, name)) + "Sequence specification refers to sequence id '%s', " + "starting at index %d with length %d, but sequence " + "'%s' is not long enough to support that." % + (fromId, index + 1, length, fromId)) read = Read(None, sequence) @@ -330,7 +310,6 @@ class Sequences(object): alphabet = None previousRead = None nSequences = spec.get('count', 1) - nameCount = self._nameCount(spec) for count in range(nSequences): id_ = None @@ -356,16 +335,6 @@ class Sequences(object): prefixCount = self._idPrefixCount.setdefault(prefix, 0) + 1 self._idPrefixCount[prefix] += 1 id_ = '%s%d' % (prefix, prefixCount) - else: - # If an id is given, the number of sequences requested must - # be one. - if nSequences != 1: - raise ValueError( - "Sequence with id '%s' has a count of %d. If you " - "want to specify one sequence with an id, the " - "count must be 1. To specify multiple sequences " - "with an id prefix, use 'id prefix'." % - (id_, nSequences)) try: id_ = id_ + ' ' + spec['description'] @@ -375,10 +344,11 @@ class Sequences(object): read = Read(id_, sequence) read.alphabet = alphabet - # Keep a reference to this result if it is named and this is the - # sequence (by count) we want to name. - if 'name' in spec and nameCount == count: - self._names[spec['name']] = read + if id_ in self._sequenceSpecs: + raise ValueError( + "Sequence id '%s' has already been used." % id_) + else: + self._sequences[id_] = read if not spec.get('skip'): yield read
Simplify sequencing naming so everything has a name (id)
acorg/seqgen
diff --git a/test/testSequences.py b/test/testSequences.py index a57de94..b96fd97 100644 --- a/test/testSequences.py +++ b/test/testSequences.py @@ -50,13 +50,14 @@ class TestSequences(TestCase): spec='filename') @patch(open_, new_callable=mock_open, - read_data='[{"name": "a"}, {"name": "a"}]') - def testDuplicatedName(self, mock): + read_data='[{"id": "a"}, {"id": "a"}]') + def testDuplicatedId(self, mock): """ - If a duplicate sequence name is present in the JSON, a ValueError + If a duplicate sequence id is present in the JSON, a ValueError must be raised. """ - error = "^Name 'a' is duplicated in the JSON specification\\.$" + error = ("^Sequence specification 2 has an id \\(a\\) that has " + "already been used\\.$") assertRaisesRegex(self, ValueError, error, Sequences, spec='filename') def testNoSequences(self): @@ -66,18 +67,6 @@ class TestSequences(TestCase): s = Sequences(StringIO('[]')) self.assertEqual([], list(s)) - def testOneSequenceNameOnly(self): - """ - If only one sequence is specified, and only by name, one sequence - should be created, it should have the default length, the expected - id, and it should be entirely composed of nucleotides. - """ - s = Sequences(StringIO('[{"name": "a"}]')) - (read,) = list(s) - self.assertEqual(Sequences.DEFAULT_ID_PREFIX + '1', read.id) - self.assertEqual(Sequences.DEFAULT_LENGTH, len(read.sequence)) - self.assertEqual(set(), set(read.sequence) - set('ACGT')) - def testOneSequenceIdOnly(self): """ If only one sequence is specified, and only by id, one sequence @@ -128,19 +117,19 @@ class TestSequences(TestCase): If only one sequence is specified with an id, a ValueError must be raised if its count is greater than one. """ - s = Sequences(StringIO('''{ + spec = StringIO('''{ "sequences": [ { "id": "the-id", "count": 6 } ] - }''')) - error = ("^Sequence with id 'the-id' has a count of 6\\. If you want " - "to specify one sequence with an id, the count must be 1\\. " - "To specify multiple sequences with an id prefix, use " - "'id prefix'\\.$") - assertRaisesRegex(self, ValueError, error, list, s) + }''') + error = ("^Sequence specification 1 with id 'the-id' has a count of " + "6\\. If you want to specify a sequence with an id, the " + "count must be 1\\. To specify multiple sequences with an id " + "prefix, use 'id prefix'\\.$") + assertRaisesRegex(self, ValueError, error, Sequences, spec) def testRatchetWithNoCount(self): """ @@ -196,7 +185,7 @@ class TestSequences(TestCase): If an unknown key is given in a sequence specification section, a ValueError must be raised. """ - for key in 'id', 'id prefix', 'name': + for key in 'id', 'id prefix', 'xxx': error = ("^Section 1 of sequence specification 1 contains an " "unknown key: %s\\.$" % key) assertRaisesRegex(self, ValueError, error, Sequences, StringIO('''{ @@ -283,23 +272,23 @@ class TestSequences(TestCase): the default length, the expected id, and it should be entirely composed of nucleotides. """ - s = Sequences(StringIO('[{"name": "a", "random aa": true}]')) + s = Sequences(StringIO('[{"random aa": true}]')) (read,) = list(s) self.assertEqual(Sequences.DEFAULT_ID_PREFIX + '1', read.id) self.assertEqual(Sequences.DEFAULT_LENGTH, len(read.sequence)) self.assertEqual(set(), set(read.sequence) - set(AA_LETTERS)) - def testTwoSequencesSecondFromName(self): + def testTwoSequencesSecondFromId(self): """ - If only one sequence is specified by name and a second refers to it - by name, the second sequence should be the same as the first. + If only one sequence is given an id and a second refers to it + by that id, the second sequence should be the same as the first. """ s = Sequences(StringIO('''[ { - "name": "a" + "id": "a" }, { - "from name": "a" + "from id": "a" } ]''')) (read1, read2) = list(s) @@ -544,7 +533,7 @@ class TestSequences(TestCase): (read,) = list(s) self.assertEqual(50, len(read.sequence)) - def testSectionWithNameReference(self): + def testSectionWithIdReference(self): """ A sequence must be able to be built up from sections, with two sections given by length. @@ -552,13 +541,13 @@ class TestSequences(TestCase): s = Sequences(StringIO('''{ "sequences": [ { - "name": "xxx", + "id": "xxx", "sequence": "ACCGT" }, { "sections": [ { - "from name": "xxx" + "from id": "xxx" }, { "length": 10 @@ -571,76 +560,76 @@ class TestSequences(TestCase): self.assertEqual(15, len(read2.sequence)) self.assertTrue(read2.sequence.startswith('ACCGT')) - def testSectionWithUnknownNameReference(self): + def testSectionWithUnknownIdReference(self): """ If a sequence is built up from sections and a referred to sequence - does not exist, a ValueError must be raised. + id does not exist, a ValueError must be raised. """ s = Sequences(StringIO('''{ "sequences": [ { "sections": [ { - "from name": "xxx" + "from id": "xxx" } ] } ] }''')) - error = ("^Sequence section refers to name 'xxx' of " + error = ("^Sequence section refers to the id 'xxx' of " "non-existent other sequence\\.$") assertRaisesRegex(self, ValueError, error, list, s) - def testSectionWithNameReferenceTooShort(self): + def testSectionWithIdReferenceTooShort(self): """ - If a sequence is built up from sections and a referred to sequence + If a sequence is built up from sections and a referred-to sequence is too short for the desired length, a ValueError must be raised. """ s = Sequences(StringIO('''{ "sequences": [ { - "name": "xxx", + "id": "xxx", "sequence": "ACCGT" }, { "sections": [ { - "from name": "xxx", + "from id": "xxx", "length": 10 } ] } ] }''')) - error = ("^Sequence specification refers to sequence name 'xxx', " - "starting at index 1 with length 10, but 'xxx' is not long " - "enough to support that\\.$") + error = ("^Sequence specification refers to sequence id 'xxx', " + "starting at index 1 with length 10, but sequence 'xxx' is " + "not long enough to support that\\.$") assertRaisesRegex(self, ValueError, error, list, s) def testNamedRecombinant(self): """ - It must be possible to build up and name a recombinant. + It must be possible to build up and give an id to a recombinant. """ s = Sequences(StringIO('''{ "sequences": [ { - "name": "xxx", + "id": "xxx", "sequence": "ACCA" }, { - "name": "yyy", + "id": "yyy", "sequence": "GGTT" }, { "id": "recombinant", "sections": [ { - "from name": "xxx", + "from id": "xxx", "start": 1, "length": 3 }, { - "from name": "yyy", + "from id": "yyy", "start": 2, "length": 2 } @@ -655,26 +644,26 @@ class TestSequences(TestCase): def testRecombinantFromFullOtherSequences(self): """ It must be possible to build up a recombinant that is composed of two - other sequences by only giving the names of the other sequences. + other sequences by only giving the ids of the other sequences. """ s = Sequences(StringIO('''{ "sequences": [ { - "name": "xxx", + "id": "xxx", "sequence": "ACCA" }, { - "name": "yyy", + "id": "yyy", "sequence": "GGTT" }, { "id": "recombinant", "sections": [ { - "from name": "xxx" + "from id": "xxx" }, { - "from name": "yyy" + "from id": "yyy" } ] } @@ -709,13 +698,13 @@ class TestSequences(TestCase): s = Sequences(StringIO('''{ "sequences": [ { - "name": "orig", + "id": "orig", "alphabet": "01", "length": %s }, { "count": 2, - "from name": "orig", + "from id": "orig", "mutation rate": 1.0, "ratchet": true } @@ -737,138 +726,3 @@ class TestSequences(TestCase): # The sequences of the original and the second mutant must be # identical. self.assertEqual(orig.sequence, mutant2.sequence) - - def testNameCountTooHigh(self): - """ - A name count value that is higher than the number of sequences in - a specification must result in a ValueError. - """ - spec = StringIO('''{ - "sequences": [ - { - "name": "orig", - "name count": 10, - "count": 2 - } - ] - }''') - error = ('^Sequence specification 1 will only produce 2 sequences but ' - 'has a \\(too high\\) name count value of 10\\.$') - assertRaisesRegex(self, ValueError, error, Sequences, spec) - - def testNameCountFirst(self): - """ - A name count value of 'first' must result in the first sequence of a - series being named. - """ - s = Sequences(StringIO('''{ - "sequences": [ - { - "name": "orig", - "name count": "first", - "count": 20, - "mutation rate": 0.1, - "length": 500, - "ratchet": true - }, - { - "id": "copy", - "from name": "orig" - } - ] - }''')) - reads = list(s) - copySequence = reads[-1].sequence - # The final sequence (the copy) must be the same as the first sequence - # (and no others). - self.assertEqual(reads[0].sequence, copySequence) - for i in range(1, 20): - self.assertNotEqual(reads[i].sequence, copySequence) - - def testNameCountLast(self): - """ - A name count value of 'last' must result in the last sequence of a - series being named. - """ - s = Sequences(StringIO('''{ - "sequences": [ - { - "name": "orig", - "name count": "last", - "count": 20, - "mutation rate": 0.1, - "length": 500, - "ratchet": true - }, - { - "id": "copy", - "from name": "orig" - } - ] - }''')) - reads = list(s) - copySequence = reads[-1].sequence - # The final sequence (the copy) must be the same as the second last - # (i.e., the final mutant) sequence (and no others). - self.assertEqual(reads[-2].sequence, copySequence) - for i in range(19): - self.assertNotEqual(reads[i].sequence, copySequence) - - def testNameCountOne(self): - """ - A name count value of 1 must result in the first sequence of a - series being named. - """ - s = Sequences(StringIO('''{ - "sequences": [ - { - "name": "orig", - "name count": 1, - "count": 20, - "mutation rate": 0.1, - "length": 500, - "ratchet": true - }, - { - "id": "copy", - "from name": "orig" - } - ] - }''')) - reads = list(s) - copySequence = reads[-1].sequence - # The final sequence (the copy) must be the same as the first sequence - # (and no others). - self.assertEqual(reads[0].sequence, copySequence) - for i in range(1, 20): - self.assertNotEqual(reads[i].sequence, copySequence) - - def testNameCountTwo(self): - """ - A name count value of 2 must result in the second sequence of a - series being named. - """ - s = Sequences(StringIO('''{ - "sequences": [ - { - "name": "orig", - "name count": 2, - "count": 20, - "mutation rate": 0.1, - "length": 500, - "ratchet": true - }, - { - "id": "copy", - "from name": "orig" - } - ] - }''')) - reads = list(s) - copySequence = reads[-1].sequence - # The final sequence (the copy) must be the same as the second sequence - # (and no others). - self.assertEqual(reads[1].sequence, copySequence) - self.assertNotEqual(reads[0].sequence, copySequence) - for i in range(2, 20): - self.assertNotEqual(reads[i].sequence, copySequence)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "dark-matter>=1.1.28" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall==0.2.0 biopython==1.79 bz2file==0.98 cachetools==4.2.4 certifi==2021.5.30 charset-normalizer==2.0.12 cycler==0.11.0 Cython==3.0.12 dark-matter==4.0.13 decorator==5.1.1 idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 kiwisolver==1.3.1 matplotlib==3.3.4 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work mysql-connector-python==8.0.11 numpy==1.19.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 Pillow==8.4.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work prompt-toolkit==3.0.36 protobuf==3.19.6 ptyprocess==0.7.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work Pygments==2.14.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pysam==0.23.0 pytest==6.2.4 python-dateutil==2.9.0.post0 pyzmq==25.1.2 requests==2.27.1 -e git+https://github.com/acorg/seqgen.git@a46ce6635de4e891fa252624c65d8070c073c802#egg=seqgen simplejson==3.20.1 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work traitlets==4.3.3 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 wcwidth==0.2.13 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: seqgen channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - backcall==0.2.0 - biopython==1.79 - bz2file==0.98 - cachetools==4.2.4 - charset-normalizer==2.0.12 - cycler==0.11.0 - cython==3.0.12 - dark-matter==4.0.13 - decorator==5.1.1 - idna==3.10 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - kiwisolver==1.3.1 - matplotlib==3.3.4 - mysql-connector-python==8.0.11 - numpy==1.19.5 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==8.4.0 - prompt-toolkit==3.0.36 - protobuf==3.19.6 - ptyprocess==0.7.0 - pygments==2.14.0 - pysam==0.23.0 - python-dateutil==2.9.0.post0 - pyzmq==25.1.2 - requests==2.27.1 - simplejson==3.20.1 - six==1.17.0 - traitlets==4.3.3 - urllib3==1.26.20 - wcwidth==0.2.13 prefix: /opt/conda/envs/seqgen
[ "test/testSequences.py::TestSequences::testDuplicatedId", "test/testSequences.py::TestSequences::testNamedRecombinant", "test/testSequences.py::TestSequences::testOneSequenceIdAndCountGreaterThanOne", "test/testSequences.py::TestSequences::testRatchet", "test/testSequences.py::TestSequences::testRecombinantFromFullOtherSequences", "test/testSequences.py::TestSequences::testSectionWithIdReference", "test/testSequences.py::TestSequences::testSectionWithIdReferenceTooShort", "test/testSequences.py::TestSequences::testSectionWithUnknownIdReference", "test/testSequences.py::TestSequences::testTwoSequencesSecondFromId" ]
[]
[ "test/testSequences.py::TestSequences::testNoSequences", "test/testSequences.py::TestSequences::testNoSequencesKey", "test/testSequences.py::TestSequences::testNonExistentSpecificationFile", "test/testSequences.py::TestSequences::testNotJSON", "test/testSequences.py::TestSequences::testOneLetterAlphabet", "test/testSequences.py::TestSequences::testOneSectionRandomAAs", "test/testSequences.py::TestSequences::testOneSectionRandomNTs", "test/testSequences.py::TestSequences::testOneSectionWithLength", "test/testSequences.py::TestSequences::testOneSectionWithSequence", "test/testSequences.py::TestSequences::testOneSequenceAAOnly", "test/testSequences.py::TestSequences::testOneSequenceByLength", "test/testSequences.py::TestSequences::testOneSequenceIdOnly", "test/testSequences.py::TestSequences::testOneSequenceIdOnlyDefaultIdPrefix", "test/testSequences.py::TestSequences::testOneSequenceIdOnlyDefaultLength", "test/testSequences.py::TestSequences::testOneSequenceIdPrefix", "test/testSequences.py::TestSequences::testOneSequenceLengthIsAVariable", "test/testSequences.py::TestSequences::testOneSequenceRandomNTs", "test/testSequences.py::TestSequences::testOneSequenceSequenceMutated", "test/testSequences.py::TestSequences::testOneSequenceSequenceOnly", "test/testSequences.py::TestSequences::testOneSequenceWithIdAndDescription", "test/testSequences.py::TestSequences::testRatchetWithNoCount", "test/testSequences.py::TestSequences::testRatchetWithNoMutationRate", "test/testSequences.py::TestSequences::testTwoLetterAlphabet", "test/testSequences.py::TestSequences::testTwoSectionsWithLengths", "test/testSequences.py::TestSequences::testTwoSequencesButSecondOneSkipped", "test/testSequences.py::TestSequences::testTwoSequencesByCount", "test/testSequences.py::TestSequences::testTwoSequencesSecondOneNotSkipped", "test/testSequences.py::TestSequences::testTwoSequencesWithDifferentIdPrefixesAndCounts", "test/testSequences.py::TestSequences::testUnknownSectionKey", "test/testSequences.py::TestSequences::testUnknownSpecificationKey" ]
[]
MIT License
2,578
[ "seqgen/sequences.py", "seqgen/__init__.py", "README.md" ]
[ "seqgen/sequences.py", "seqgen/__init__.py", "README.md" ]
python-useful-helpers__exec-helpers-44
814d435b7eda2b00fa1559d5a94103f1e888ab52
2018-05-24 08:25:51
814d435b7eda2b00fa1559d5a94103f1e888ab52
coveralls: ## Pull Request Test Coverage Report for [Build 128](https://coveralls.io/builds/17142361) * **17** of **17** **(100.0%)** changed or added relevant lines in **3** files are covered. * No unchanged relevant lines lost coverage. * Overall coverage remained the same at **100.0%** --- | Totals | [![Coverage Status](https://coveralls.io/builds/17142361/badge)](https://coveralls.io/builds/17142361) | | :-- | --: | | Change from base [Build 127](https://coveralls.io/builds/17054024): | 0.0% | | Covered Lines: | 945 | | Relevant Lines: | 945 | --- ##### 💛 - [Coveralls](https://coveralls.io) coveralls: ## Pull Request Test Coverage Report for [Build 128](https://coveralls.io/builds/17142361) * **17** of **17** **(100.0%)** changed or added relevant lines in **3** files are covered. * No unchanged relevant lines lost coverage. * Overall coverage remained the same at **100.0%** --- | Totals | [![Coverage Status](https://coveralls.io/builds/17142361/badge)](https://coveralls.io/builds/17142361) | | :-- | --: | | Change from base [Build 127](https://coveralls.io/builds/17054024): | 0.0% | | Covered Lines: | 945 | | Relevant Lines: | 945 | --- ##### 💛 - [Coveralls](https://coveralls.io) coveralls: ## Pull Request Test Coverage Report for [Build 128](https://coveralls.io/builds/17142361) * **17** of **17** **(100.0%)** changed or added relevant lines in **3** files are covered. * No unchanged relevant lines lost coverage. * Overall coverage remained the same at **100.0%** --- | Totals | [![Coverage Status](https://coveralls.io/builds/17142361/badge)](https://coveralls.io/builds/17142361) | | :-- | --: | | Change from base [Build 127](https://coveralls.io/builds/17054024): | 0.0% | | Covered Lines: | 945 | | Relevant Lines: | 945 | --- ##### 💛 - [Coveralls](https://coveralls.io)
diff --git a/doc/source/exceptions.rst b/doc/source/exceptions.rst index d558cae..5d50d24 100644 --- a/doc/source/exceptions.rst +++ b/doc/source/exceptions.rst @@ -14,13 +14,45 @@ API: exceptions Deserialize impossible. -.. py:exception:: ExecHelperTimeoutError(ExecHelperError) +.. py:exception:: ExecCalledProcessError(ExecHelperError) + + Base class for process call errors. + +.. py:exception:: ExecHelperTimeoutError(ExecCalledProcessError) Execution timeout. -.. py:exception:: ExecCalledProcessError(ExecHelperError) + .. versionchanged:: 1.3.0 provide full result and timeout inside. + .. versionchanged:: 1.3.0 subclass ExecCalledProcessError - Base class for process call errors. + .. py:method:: __init__(self, result, timeout) + + Exception for error on process calls. + + :param result: execution result + :type result: exec_result.ExecResult + :param timeout: timeout for command + :type timeout: typing.Union[int, float] + + .. py:attribute:: timeout + + ``int`` + + .. py:attribute:: result + + Execution result + + :rtype: ExecResult + + .. py:attribute:: stdout + + ``typing.Text`` + stdout string or brief string + + .. py:attribute:: stderr + + ``typing.Text`` + stdout string or brief string .. py:exception:: CalledProcessError(ExecCalledProcessError) @@ -60,12 +92,12 @@ API: exceptions .. py:attribute:: stdout - ``typing.Any`` + ``typing.Text`` stdout string or brief string .. py:attribute:: stderr - ``typing.Any`` + ``typing.Text`` stdout string or brief string .. py:exception:: ParallelCallExceptions(ExecCalledProcessError) diff --git a/exec_helpers/_ssh_client_base.py b/exec_helpers/_ssh_client_base.py index 65395bc..f0ce5b5 100644 --- a/exec_helpers/_ssh_client_base.py +++ b/exec_helpers/_ssh_client_base.py @@ -735,7 +735,7 @@ class SSHClientBase(six.with_metaclass(_MemorizedSSH, _api.ExecHelper)): timeout=timeout ) self.logger.debug(wait_err_msg) - raise exceptions.ExecHelperTimeoutError(wait_err_msg) + raise exceptions.ExecHelperTimeoutError(result=result, timeout=timeout) def execute_through_host( self, diff --git a/exec_helpers/exceptions.py b/exec_helpers/exceptions.py index 07d2cb4..fc01aa7 100644 --- a/exec_helpers/exceptions.py +++ b/exec_helpers/exceptions.py @@ -21,6 +21,7 @@ from __future__ import unicode_literals import typing # noqa # pylint: disable=unused-import from exec_helpers import proc_enums +from exec_helpers import _log_templates __all__ = ( 'ExecHelperError', @@ -44,16 +45,58 @@ class DeserializeValueError(ExecHelperError, ValueError): __slots__ = () -class ExecHelperTimeoutError(ExecHelperError): - """Execution timeout.""" +class ExecCalledProcessError(ExecHelperError): + """Base class for process call errors.""" __slots__ = () -class ExecCalledProcessError(ExecHelperError): - """Base class for process call errors.""" +class ExecHelperTimeoutError(ExecCalledProcessError): + """Execution timeout. - __slots__ = () + .. versionchanged:: 1.3.0 provide full result and timeout inside. + .. versionchanged:: 1.3.0 subclass ExecCalledProcessError + """ + + __slots__ = ( + 'result', + 'timeout', + ) + + def __init__( + self, + result, # type: exec_result.ExecResult + timeout, # type: typing.Union[int, float] + ): # type: (...) -> None + """Exception for error on process calls. + + :param result: execution result + :type result: exec_result.ExecResult + :param timeout: timeout for command + :type timeout: typing.Union[int, float] + """ + self.result = result + self.timeout = timeout + message = _log_templates.CMD_WAIT_ERROR.format( + result=result, + timeout=timeout + ) + super(ExecHelperTimeoutError, self).__init__(message) + + @property + def cmd(self): # type: () -> str + """Failed command.""" + return self.result.cmd + + @property + def stdout(self): # type: () -> typing.Text + """Command stdout.""" + return self.result.stdout_str + + @property + def stderr(self): # type: () -> typing.Text + """Command stderr.""" + return self.result.stderr_str class CalledProcessError(ExecCalledProcessError): @@ -74,9 +117,7 @@ class CalledProcessError(ExecCalledProcessError): :param result: execution result :type result: exec_result.ExecResult :param expected: expected return codes - :type expected: typing.Optional[ - typing.List[typing.Union[int, proc_enums.ExitCodes]] - ] + :type expected: typing.Optional[typing.List[typing.Union[int, proc_enums.ExitCodes]]] .. versionchanged:: 1.1.1 - provide full result """ @@ -89,7 +130,7 @@ class CalledProcessError(ExecCalledProcessError): "\tSTDOUT:\n" "{result.stdout_brief}\n" "\tSTDERR:\n{result.stderr_brief}".format( - result=result, + result=self.result, expected=self.expected ) ) diff --git a/exec_helpers/exceptions.pyi b/exec_helpers/exceptions.pyi index 4a22763..1f4558b 100644 --- a/exec_helpers/exceptions.pyi +++ b/exec_helpers/exceptions.pyi @@ -7,13 +7,32 @@ class ExecHelperError(Exception): class DeserializeValueError(ExecHelperError, ValueError): ... -class ExecHelperTimeoutError(ExecHelperError): - ... class ExecCalledProcessError(ExecHelperError): ... +class ExecHelperTimeoutError(ExecCalledProcessError): + + result: exec_result.ExecResult = ... + timeout: int = ... + + def __init__( + self, + result: exec_result.ExecResult, + timeout: typing.Union[int, float], + ) -> None: ... + + @property + def cmd(self) -> str: ... + + @property + def stdout(self) -> typing.Text: ... + + @property + def stderr(self) -> typing.Text: ... + + class CalledProcessError(ExecCalledProcessError): result: exec_result.ExecResult = ... diff --git a/exec_helpers/subprocess_runner.py b/exec_helpers/subprocess_runner.py index 8b79cc2..b36a05c 100644 --- a/exec_helpers/subprocess_runner.py +++ b/exec_helpers/subprocess_runner.py @@ -269,7 +269,7 @@ class Subprocess(six.with_metaclass(SingletonMeta, _api.ExecHelper)): timeout=timeout ) logger.debug(wait_err_msg) - raise exceptions.ExecHelperTimeoutError(wait_err_msg) + raise exceptions.ExecHelperTimeoutError(result=result, timeout=timeout) def execute_async( self,
Timeout error object should contain execution result and timeout for the future processing Currently `ExecHelperTimeoutError` contains only message and inherited from `ExecHelperError` while used in single call scenarios only. Need to re-inherit `ExecHelperError` and provide result + timeout + properties access to cmd, stdout_str and stderr_str.
python-useful-helpers/exec-helpers
diff --git a/test/test_ssh_client.py b/test/test_ssh_client.py index 9119773..f02a68f 100644 --- a/test/test_ssh_client.py +++ b/test/test_ssh_client.py @@ -1028,10 +1028,15 @@ class TestExecute(unittest.TestCase): logger.reset_mock() - with self.assertRaises(exec_helpers.ExecHelperTimeoutError): + with self.assertRaises(exec_helpers.ExecHelperTimeoutError) as cm: # noinspection PyTypeChecker ssh.execute(command=command, verbose=False, timeout=0.2) + self.assertEqual(cm.exception.timeout, 0.2) + self.assertEqual(cm.exception.cmd, command) + self.assertEqual(cm.exception.stdout, stdout_str) + self.assertEqual(cm.exception.stderr, stderr_str) + execute_async.assert_called_once_with(command, verbose=False) chan.assert_has_calls((mock.call.status_event.is_set(), )) diff --git a/test/test_subprocess_runner.py b/test/test_subprocess_runner.py index 04555c7..18d508d 100644 --- a/test/test_subprocess_runner.py +++ b/test/test_subprocess_runner.py @@ -233,10 +233,15 @@ class TestSubprocessRunner(unittest.TestCase): # noinspection PyTypeChecker - with self.assertRaises(exec_helpers.ExecHelperTimeoutError): + with self.assertRaises(exec_helpers.ExecHelperTimeoutError) as cm: # noinspection PyTypeChecker runner.execute(command, timeout=0.2) + self.assertEqual(cm.exception.timeout, 0.2) + self.assertEqual(cm.exception.cmd, command) + self.assertEqual(cm.exception.stdout, exp_result.stdout_str) + self.assertEqual(cm.exception.stderr, exp_result.stderr_str) + popen.assert_has_calls(( mock.call( args=[command],
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 5 }
1.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest_v2", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-html", "pytest-sugar" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt", "CI_REQUIREMENTS.txt", "build_requirements.txt" ], "test_cmd": "pytest -vv -s -p no:django -p no:ipdb" }
advanced-descriptors==3.0.9.post0 attrs==22.2.0 bcrypt==4.0.1 certifi==2021.5.30 cffi==1.15.1 coverage==6.2 cryptography==40.0.2 Cython==3.0.12 -e git+https://github.com/python-useful-helpers/exec-helpers.git@814d435b7eda2b00fa1559d5a94103f1e888ab52#egg=exec_helpers importlib-metadata==4.8.3 iniconfig==1.1.1 mock==5.2.0 packaging==21.3 paramiko==3.5.1 pluggy==1.0.0 py==1.11.0 pycparser==2.21 PyNaCl==1.5.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-html==3.2.0 pytest-metadata==1.11.0 pytest-sugar==0.9.6 PyYAML==6.0.1 six==1.17.0 tenacity==8.2.2 termcolor==1.1.0 threaded==4.1.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: exec-helpers channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - advanced-descriptors==3.0.9.post0 - attrs==22.2.0 - bcrypt==4.0.1 - cffi==1.15.1 - coverage==6.2 - cryptography==40.0.2 - cython==3.0.12 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mock==5.2.0 - packaging==21.3 - paramiko==3.5.1 - pluggy==1.0.0 - py==1.11.0 - pycparser==2.21 - pynacl==1.5.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-html==3.2.0 - pytest-metadata==1.11.0 - pytest-sugar==0.9.6 - pyyaml==6.0.1 - six==1.17.0 - tenacity==8.2.2 - termcolor==1.1.0 - threaded==4.1.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/exec-helpers
[ "test/test_ssh_client.py::TestExecute::test_025_execute_timeout_fail", "test/test_subprocess_runner.py::TestSubprocessRunner::test_004_execute_timeout_fail" ]
[]
[ "test/test_ssh_client.py::TestExecute::test_001_execute_async", "test/test_ssh_client.py::TestExecute::test_002_execute_async_pty", "test/test_ssh_client.py::TestExecute::test_003_execute_async_no_stdout_stderr", "test/test_ssh_client.py::TestExecute::test_004_execute_async_sudo", "test/test_ssh_client.py::TestExecute::test_005_execute_async_with_sudo_enforce", "test/test_ssh_client.py::TestExecute::test_006_execute_async_with_no_sudo_enforce", "test/test_ssh_client.py::TestExecute::test_007_execute_async_with_sudo_none_enforce", "test/test_ssh_client.py::TestExecute::test_008_execute_async_sudo_password", "test/test_ssh_client.py::TestExecute::test_009_execute_async_verbose", "test/test_ssh_client.py::TestExecute::test_010_execute_async_mask_command", "test/test_ssh_client.py::TestExecute::test_011_check_stdin_str", "test/test_ssh_client.py::TestExecute::test_012_check_stdin_bytes", "test/test_ssh_client.py::TestExecute::test_013_check_stdin_bytearray", "test/test_ssh_client.py::TestExecute::test_014_check_stdin_closed", "test/test_ssh_client.py::TestExecute::test_015_keepalive", "test/test_ssh_client.py::TestExecute::test_016_no_keepalive", "test/test_ssh_client.py::TestExecute::test_017_keepalive_enforced", "test/test_ssh_client.py::TestExecute::test_018_no_keepalive_enforced", "test/test_ssh_client.py::TestExecute::test_019_execute", "test/test_ssh_client.py::TestExecute::test_020_execute_verbose", "test/test_ssh_client.py::TestExecute::test_021_execute_no_stdout", "test/test_ssh_client.py::TestExecute::test_022_execute_no_stderr", "test/test_ssh_client.py::TestExecute::test_023_execute_no_stdout_stderr", "test/test_ssh_client.py::TestExecute::test_024_execute_timeout", "test/test_ssh_client.py::TestExecute::test_026_execute_mask_command", "test/test_ssh_client.py::TestExecute::test_027_execute_together", "test/test_ssh_client.py::TestExecute::test_028_execute_together_exceptions", "test/test_ssh_client.py::TestExecute::test_029_check_call", "test/test_ssh_client.py::TestExecute::test_030_check_call_expected", "test/test_ssh_client.py::TestExecute::test_031_check_stderr", "test/test_ssh_client.py::TestExecuteThrowHost::test_01_execute_through_host_no_creds", "test/test_ssh_client.py::TestExecuteThrowHost::test_02_execute_through_host_auth", "test/test_ssh_client.py::TestExecuteThrowHost::test_03_execute_through_host_get_pty", "test/test_ssh_client.py::TestSftp::test_download", "test/test_ssh_client.py::TestSftp::test_exists", "test/test_ssh_client.py::TestSftp::test_isdir", "test/test_ssh_client.py::TestSftp::test_isfile", "test/test_ssh_client.py::TestSftp::test_mkdir", "test/test_ssh_client.py::TestSftp::test_open", "test/test_ssh_client.py::TestSftp::test_rm_rf", "test/test_ssh_client.py::TestSftp::test_stat", "test/test_ssh_client.py::TestSftp::test_upload_dir", "test/test_ssh_client.py::TestSftp::test_upload_file", "test/test_subprocess_runner.py::TestSubprocessRunner::test_001_call", "test/test_subprocess_runner.py::TestSubprocessRunner::test_002_call_verbose", "test/test_subprocess_runner.py::TestSubprocessRunner::test_003_context_manager", "test/test_subprocess_runner.py::TestSubprocessRunner::test_004_check_stdin_str", "test/test_subprocess_runner.py::TestSubprocessRunner::test_005_check_stdin_bytes", "test/test_subprocess_runner.py::TestSubprocessRunner::test_005_execute_no_stdout", "test/test_subprocess_runner.py::TestSubprocessRunner::test_006_check_stdin_bytearray", "test/test_subprocess_runner.py::TestSubprocessRunner::test_006_execute_no_stderr", "test/test_subprocess_runner.py::TestSubprocessRunner::test_007_check_stdin_fail_broken_pipe", "test/test_subprocess_runner.py::TestSubprocessRunner::test_007_execute_no_stdout_stderr", "test/test_subprocess_runner.py::TestSubprocessRunner::test_008_check_stdin_fail_closed_win", "test/test_subprocess_runner.py::TestSubprocessRunner::test_008_execute_mask_global", "test/test_subprocess_runner.py::TestSubprocessRunner::test_009_check_stdin_fail_write", "test/test_subprocess_runner.py::TestSubprocessRunner::test_009_execute_mask_local", "test/test_subprocess_runner.py::TestSubprocessRunner::test_010_check_stdin_fail_close_pipe", "test/test_subprocess_runner.py::TestSubprocessRunner::test_011_check_stdin_fail_close_pipe_win", "test/test_subprocess_runner.py::TestSubprocessRunner::test_012_check_stdin_fail_close", "test/test_subprocess_runner.py::TestSubprocessRunner::test_013_execute_timeout_done", "test/test_subprocess_runner.py::TestSubprocessRunnerHelpers::test_001_check_call", "test/test_subprocess_runner.py::TestSubprocessRunnerHelpers::test_002_check_call_expected", "test/test_subprocess_runner.py::TestSubprocessRunnerHelpers::test_003_check_stderr" ]
[]
Apache License 2.0
2,579
[ "doc/source/exceptions.rst", "exec_helpers/subprocess_runner.py", "exec_helpers/_ssh_client_base.py", "exec_helpers/exceptions.pyi", "exec_helpers/exceptions.py" ]
[ "doc/source/exceptions.rst", "exec_helpers/subprocess_runner.py", "exec_helpers/_ssh_client_base.py", "exec_helpers/exceptions.pyi", "exec_helpers/exceptions.py" ]
fniessink__next-action-74
6e69cacd6b944eec7be0489e9f4bf9442802c5ea
2018-05-24 15:52:48
6e69cacd6b944eec7be0489e9f4bf9442802c5ea
diff --git a/CHANGELOG.md b/CHANGELOG.md index d6fd7c7..7768ac2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Added - Option to not read a configuration file. Closes #71. +- Option to write a default configuration file. Closes #68. ## [0.7.0] - 2018-05-23 diff --git a/README.md b/README.md index 8ff4108..762ffb6 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ optional arguments: -c <config.cfg>, --config-file <config.cfg> filename of configuration file to read (default: ~/.next-action.cfg) -C, --no-config-file don't read the configuration file + --write-config-file generate a sample configuration file and exit -f <todo.txt>, --file <todo.txt> filename of todo.txt file to read; can be '-' to read from standard input; argument can be repeated to read tasks from multiple todo.txt files (default: ~/todo.txt) @@ -121,7 +122,20 @@ Note again that completed tasks and task with a future creation date are never s ### Configuring *Next-action* -Instead of specifying which todo.txt files to read on the command-line, you can also configure this in a configuration file. By default, *Next-action* tries to read a file called [.next-action.cfg](https://raw.githubusercontent.com/fniessink/next-action/master/docs/.next-action.cfg) in your home folder, but you can tell it to read another configuration file: +In addition to specifying options on the command-line, you can also configure options in a configuration file. By default, *Next-action* tries to read a file called [.next-action.cfg](https://raw.githubusercontent.com/fniessink/next-action/master/docs/.next-action.cfg) in your home folder. + +To get started, you can tell *Next-action* to generate a configuration file with the default options: + +```console +$ next-action --write-config-file +# Configuration file for Next-action. Edit the settings below as you like. +file: ~/todo.txt +number: 1 +``` + +To make this the configuration that *Next-action* reads by default, redirect the output to `~/.next-action.cfg` like this: `next-action --write-config-file > ~/.next-action.cfg`. + +If you want to use a configuration file that is not in the default location (`~/.next-action.cfg`), you'll need to explicitly tell *Next-action* its location: ```console $ next-action --config-file docs/.next-action.cfg @@ -175,9 +189,9 @@ To run the unit tests: ```console $ python -m unittest -....................................................................................................................... +........................................................................................................................ ---------------------------------------------------------------------- -Ran 119 tests in 0.168s +Ran 120 tests in 0.346s OK ``` diff --git a/docs/update_readme.py b/docs/update_readme.py index 5333ee9..b8de9af 100644 --- a/docs/update_readme.py +++ b/docs/update_readme.py @@ -19,7 +19,7 @@ def update_readme(): elif line.startswith("$ "): print(line) command = line[2:].split(" ") - if command[0] == "next-action": + if command[0] == "next-action" and "--write-config-file" not in command: command.extend(["--config", "docs/.next-action.cfg"]) command_output = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, universal_newlines=True) diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index 3c349f6..604915c 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -4,6 +4,8 @@ import argparse import sys from typing import List +import yaml + import next_action from .config import read_config_file, validate_config_file @@ -32,6 +34,8 @@ class NextActionArgumentParser(argparse.ArgumentParser): help="filename of configuration file to read (default: %(default)s)") config_file.add_argument( "-C", "--no-config-file", help="don't read the configuration file", action="store_true") + config_file.add_argument( + "--write-config-file", help="generate a sample configuration file and exit", action="store_true") self.add_argument( "-f", "--file", action="append", metavar="<todo.txt>", default=default_filenames[:], type=str, help="filename of todo.txt file to read; can be '-' to read from standard input; argument can be " @@ -70,6 +74,8 @@ class NextActionArgumentParser(argparse.ArgumentParser): self.parse_remaining_args(remaining, namespace) if not namespace.no_config_file: self.process_config_file(namespace) + if namespace.write_config_file: + self.write_config_file() return namespace def parse_remaining_args(self, remaining: List[str], namespace: argparse.Namespace) -> None: @@ -102,6 +108,13 @@ class NextActionArgumentParser(argparse.ArgumentParser): number = sys.maxsize if config.get("all", False) else config.get("number", 1) setattr(namespace, "number", number) + def write_config_file(self) -> None: + """ Generate a configuration file on standard out and exi. """ + intro = "# Configuration file for Next-action. Edit the settings below as you like.\n" + config = yaml.dump(dict(file="~/todo.txt", number=1), default_flow_style=False) + sys.stdout.write(intro + config) + self.exit() + def arguments_not_specified(self, namespace: argparse.Namespace, *arguments: str) -> bool: """ Return whether the arguments were not specified on the command line. """ return all([getattr(namespace, argument) == self.get_default(argument) for argument in arguments])
Option to write out a default configuration file
fniessink/next-action
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py index e5bae6c..775e336 100644 --- a/tests/unittests/arguments/test_config.py +++ b/tests/unittests/arguments/test_config.py @@ -88,6 +88,16 @@ class ConfigFileTest(unittest.TestCase): parse_arguments() self.assertEqual([], mock_file_open.call_args_list) + @patch.object(sys, "argv", ["next-action", "--write-config-file"]) + @patch.object(config, "open", mock_open(read_data="")) + @patch.object(sys.stdout, "write") + def test_write_config(self, mock_stdout_write): + """ Test that a config file can be written to stdout. """ + self.assertRaises(SystemExit, parse_arguments) + expected = "# Configuration file for Next-action. Edit the settings below as you like.\n" + expected += "file: ~/todo.txt\nnumber: 1\n" + self.assertEqual([call(expected)], mock_stdout_write.call_args_list) + class FilenameTest(unittest.TestCase): """ Unit tests for the config file parameter. """ diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index 754fe21..0eca016 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -77,6 +77,7 @@ optional arguments: -c <config.cfg>, --config-file <config.cfg> filename of configuration file to read (default: ~/.next-action.cfg) -C, --no-config-file don't read the configuration file + --write-config-file generate a sample configuration file and exit -f <todo.txt>, --file <todo.txt> filename of todo.txt file to read; can be '-' to read from standard input; argument can be repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 4 }
0.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
Cerberus==1.2 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@6e69cacd6b944eec7be0489e9f4bf9442802c5ea#egg=next_action packaging==24.2 pluggy==1.5.0 pytest==8.3.5 PyYAML==3.12 tomli==2.2.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cerberus==1.2 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pyyaml==3.12 - tomli==2.2.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config", "tests/unittests/test_cli.py::CLITest::test_help" ]
[]
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config", "tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files", "tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_config.py::NumberTest::test_all_false", "tests/unittests/arguments/test_config.py::NumberTest::test_all_true", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_valid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_zero", "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_missing_file", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_version" ]
[]
Apache License 2.0
2,580
[ "docs/update_readme.py", "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
[ "docs/update_readme.py", "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
google__mobly-453
f1aff6a7f06887424759e3c192b1bf6e13d2a6bf
2018-05-24 19:50:41
95286a01a566e056d44acfa9577a45bc7f37f51d
xpconanfan: I don't see how this is related to logging stderr as the issue described. One of the msg is incorrect? --- Review status: 0 of 2 files reviewed at latest revision, all discussions resolved. --- *[mobly/controllers/android_device_lib/adb.py, line 215 at r1](https://reviewable.io/reviews/google/mobly/453#-LDIjCGd2zhkKzp2ablH:-LDIjCGd2zhkKzp2ablI:b-x8c38) ([raw file](https://github.com/google/mobly/blob/73f94e45966ec8566eabae03fc00893e5a13ee33/mobly/controllers/android_device_lib/adb.py#L215)):* > ```Python > break > finally: > (unhandled_out, err) = proc.communicate() > ``` wait, so this does happen? shouldn't we call the handler with this out instead? --- *Comments from [Reviewable](https://reviewable.io/reviews/google/mobly/453#-:-LDIjnBO4MUgZxYNImBt:blud5im)* <!-- Sent from Reviewable.io --> winterfroststrom: Review status: 0 of 2 files reviewed at latest revision, 1 unresolved discussion. --- *[mobly/controllers/android_device_lib/adb.py, line 215 at r1](https://reviewable.io/reviews/google/mobly/453#-LDIjCGd2zhkKzp2ablH:-LDIkOBz8aQLOE0ovB8O:brjczjz) ([raw file](https://github.com/google/mobly/blob/73f94e45966ec8566eabae03fc00893e5a13ee33/mobly/controllers/android_device_lib/adb.py#L215)):* <details><summary><i>Previously, xpconanfan (Ang Li) wrote…</i></summary><blockquote> wait, so this does happen? shouldn't we call the handler with this out instead? </blockquote></details> I'm not sure? I'm adding logging here first to try to determine what the underlying problem is --- *Comments from [Reviewable](https://reviewable.io/reviews/google/mobly/453)* <!-- Sent from Reviewable.io --> xpconanfan: Review status: 0 of 2 files reviewed at latest revision, 1 unresolved discussion. --- *[mobly/controllers/android_device_lib/adb.py, line 215 at r1](https://reviewable.io/reviews/google/mobly/453#-LDIjCGd2zhkKzp2ablH:-LDIl2971UfZ3LqypsHv:b332s67) ([raw file](https://github.com/google/mobly/blob/73f94e45966ec8566eabae03fc00893e5a13ee33/mobly/controllers/android_device_lib/adb.py#L215)):* <details><summary><i>Previously, winterfroststrom wrote…</i></summary><blockquote> I'm not sure? I'm adding logging here first to try to determine what the underlying problem is </blockquote></details> seems like we should pipe all stdout content through the handler as this function promised? you could add additional logging to signify the existence of stdout from `communicate`? --- *Comments from [Reviewable](https://reviewable.io/reviews/google/mobly/453)* <!-- Sent from Reviewable.io --> xpconanfan: Review status: 0 of 2 files reviewed at latest revision, 1 unresolved discussion. --- *[tests/mobly/controllers/android_device_lib/adb_test.py, line 156 at r1](https://reviewable.io/reviews/google/mobly/453#-LDImOOR-GL1gRhihxxl:-LDImOOR-GL1gRhihxxm:ba86vyn) ([raw file](https://github.com/google/mobly/blob/73f94e45966ec8566eabae03fc00893e5a13ee33/tests/mobly/controllers/android_device_lib/adb_test.py#L156)):* > ```Python > def test_execute_and_process_stdout_logs_cmd(self, mock_debug_logger, > mock_popen): > self._mock_execute_and_process_stdout_process(mock_popen) > ``` this test is relying on the default mock stdout value in `_mock_execute_and_process_stdout_process`, which is difficult to read. Can we more explicitly set the mock value within the test? --- *Comments from [Reviewable](https://reviewable.io/reviews/google/mobly/453)* <!-- Sent from Reviewable.io --> winterfroststrom: Review status: 0 of 2 files reviewed at latest revision, 2 unresolved discussions. --- *[mobly/controllers/android_device_lib/adb.py, line 215 at r1](https://reviewable.io/reviews/google/mobly/453#-LDIjCGd2zhkKzp2ablH:-LDIsvuPD4jS9CVrpnr5:bcy1d3j) ([raw file](https://github.com/google/mobly/blob/73f94e45966ec8566eabae03fc00893e5a13ee33/mobly/controllers/android_device_lib/adb.py#L215)):* <details><summary><i>Previously, xpconanfan (Ang Li) wrote…</i></summary><blockquote> seems like we should pipe all stdout content through the handler as this function promised? you could add additional logging to signify the existence of stdout from `communicate`? </blockquote></details> So, I've never seen this output actually get populated and I'm not sure it is in the case I'm debugging, but okay. I'm preferring changing the logged command because otherwise you'd get semi-duplicate log lines. --- *[tests/mobly/controllers/android_device_lib/adb_test.py, line 156 at r1](https://reviewable.io/reviews/google/mobly/453#-LDImOOR-GL1gRhihxxl:-LDItG5yEIdICTRzP1c0:b-896fix) ([raw file](https://github.com/google/mobly/blob/73f94e45966ec8566eabae03fc00893e5a13ee33/tests/mobly/controllers/android_device_lib/adb_test.py#L156)):* <details><summary><i>Previously, xpconanfan (Ang Li) wrote…</i></summary><blockquote> this test is relying on the default mock stdout value in `_mock_execute_and_process_stdout_process`, which is difficult to read. Can we more explicitly set the mock value within the test? </blockquote></details> Done. --- *Comments from [Reviewable](https://reviewable.io/reviews/google/mobly/453)* <!-- Sent from Reviewable.io --> xpconanfan: <img class="emoji" title=":lgtm:" alt=":lgtm:" align="absmiddle" src="https://reviewable.io/lgtm.png" height="20" width="61"/> --- Review status: 0 of 2 files reviewed at latest revision, all discussions resolved. --- *Comments from [Reviewable](https://reviewable.io/reviews/google/mobly/453#-:-LEBweyyBV-cQJiSKgM7:bnfp4nl)* <!-- Sent from Reviewable.io -->
diff --git a/mobly/controllers/android_device_lib/adb.py b/mobly/controllers/android_device_lib/adb.py index 90dcd0b..95d1261 100644 --- a/mobly/controllers/android_device_lib/adb.py +++ b/mobly/controllers/android_device_lib/adb.py @@ -203,6 +203,7 @@ class AdbProxy(object): stderr=subprocess.PIPE, shell=shell, bufsize=1) + out = '[elided, processed via handler]' try: while proc.poll() is None: line = proc.stdout.readline() @@ -211,16 +212,19 @@ class AdbProxy(object): else: break finally: - (_, err) = proc.communicate() + (unexpected_out, err) = proc.communicate() + if unexpected_out: + out = '[unexpected stdout] %s' % unexpected_out + for line in unexpected_out.splitlines(): + handler(line) + ret = proc.returncode + logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', + cli_cmd_to_string(args), out, err, ret) if ret == 0: return err else: - raise AdbError( - cmd=args, - stdout='[elided, processed via handler]', - stderr=err, - ret_code=ret) + raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret) def _construct_adb_cmd(self, raw_name, args, shell): """Constructs an adb command with arguments for a subprocess call. diff --git a/mobly/controllers/android_device_lib/snippet_client.py b/mobly/controllers/android_device_lib/snippet_client.py index e3e835d..03674ff 100644 --- a/mobly/controllers/android_device_lib/snippet_client.py +++ b/mobly/controllers/android_device_lib/snippet_client.py @@ -125,8 +125,7 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase): # Yaaay! We're done! self.log.debug('Snippet %s started after %.1fs on host port %s', - self.package, - time.time() - start_time, self.host_port) + self.package, time.time() - start_time, self.host_port) def restore_app_connection(self, port=None): """Restores the app after device got reconnected. @@ -151,12 +150,13 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase): try: self.connect() except: - # Failed to connect to app, something went wrong. + # Log the original error and raise AppRestoreConnectionError. + self.log.exception('Failed to re-connect to app.') raise jsonrpc_client_base.AppRestoreConnectionError( - self._ad( - 'Failed to restore app connection for %s at host port %s, ' - 'device port %s'), self.package, self.host_port, - self.device_port) + self._ad, + ('Failed to restore app connection for %s at host port %s, ' + 'device port %s') % (self.package, self.host_port, + self.device_port)) # Because the previous connection was lost, update self._proc self._proc = None
`_execute_and_process_stdout` should log cmd
google/mobly
diff --git a/tests/mobly/controllers/android_device_lib/adb_test.py b/tests/mobly/controllers/android_device_lib/adb_test.py index 1c75a9d..8dec8aa 100755 --- a/tests/mobly/controllers/android_device_lib/adb_test.py +++ b/tests/mobly/controllers/android_device_lib/adb_test.py @@ -76,8 +76,7 @@ class AdbTest(unittest.TestCase): mock_popen.return_value.stdout.readline.side_effect = [''] mock_proc.communicate = mock.Mock( - return_value=(MOCK_DEFAULT_STDOUT.encode('utf-8'), - MOCK_DEFAULT_STDERR.encode('utf-8'))) + return_value=('', MOCK_DEFAULT_STDERR.encode('utf-8'))) mock_proc.returncode = 0 return mock_popen @@ -150,6 +149,57 @@ class AdbTest(unittest.TestCase): mock_handler.assert_any_call('1') mock_handler.assert_any_call('2') + @mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen') + def test_execute_and_process_stdout_reads_unexpected_stdout( + self, mock_popen): + unexpected_stdout = MOCK_DEFAULT_STDOUT.encode('utf-8') + + self._mock_execute_and_process_stdout_process(mock_popen) + mock_handler = mock.MagicMock() + mock_popen.return_value.communicate = mock.Mock( + return_value=(unexpected_stdout, MOCK_DEFAULT_STDERR.encode( + 'utf-8'))) + + err = adb.AdbProxy()._execute_and_process_stdout( + ['fake_cmd'], shell=False, handler=mock_handler) + self.assertEqual(mock_handler.call_count, 1) + mock_handler.assert_called_with(unexpected_stdout) + + @mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen') + @mock.patch('logging.debug') + def test_execute_and_process_stdout_logs_cmd(self, mock_debug_logger, + mock_popen): + raw_expected_stdout = '' + expected_stdout = '[elided, processed via handler]' + expected_stderr = MOCK_DEFAULT_STDERR.encode('utf-8') + self._mock_execute_and_process_stdout_process(mock_popen) + mock_popen.return_value.communicate = mock.Mock( + return_value=(raw_expected_stdout, expected_stderr)) + + err = adb.AdbProxy()._execute_and_process_stdout( + ['fake_cmd'], shell=False, handler=mock.MagicMock()) + mock_debug_logger.assert_called_with( + 'cmd: %s, stdout: %s, stderr: %s, ret: %s', 'fake_cmd', + expected_stdout, expected_stderr, 0) + + @mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen') + @mock.patch('logging.debug') + def test_execute_and_process_stdout_logs_cmd_with_unexpected_stdout( + self, mock_debug_logger, mock_popen): + raw_expected_stdout = MOCK_DEFAULT_STDOUT.encode('utf-8') + expected_stdout = '[unexpected stdout] %s' % raw_expected_stdout + expected_stderr = MOCK_DEFAULT_STDERR.encode('utf-8') + + self._mock_execute_and_process_stdout_process(mock_popen) + mock_popen.return_value.communicate = mock.Mock( + return_value=(raw_expected_stdout, expected_stderr)) + + err = adb.AdbProxy()._execute_and_process_stdout( + ['fake_cmd'], shell=False, handler=mock.MagicMock()) + mock_debug_logger.assert_called_with( + 'cmd: %s, stdout: %s, stderr: %s, ret: %s', 'fake_cmd', + expected_stdout, expected_stderr, 0) + @mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen') def test_execute_and_process_stdout_when_cmd_exits(self, mock_popen): self._mock_execute_and_process_stdout_process(mock_popen) diff --git a/tests/mobly/controllers/android_device_lib/snippet_client_test.py b/tests/mobly/controllers/android_device_lib/snippet_client_test.py index 2c875d8..d964ae3 100755 --- a/tests/mobly/controllers/android_device_lib/snippet_client_test.py +++ b/tests/mobly/controllers/android_device_lib/snippet_client_test.py @@ -166,6 +166,15 @@ class SnippetClientTest(jsonrpc_client_test_base.JsonRpcClientTestBase): self.assertEqual(789, callback._event_client.host_port) self.assertEqual(456, callback._event_client.device_port) + # if unable to reconnect for any reason, a + # jsonrpc_client_base.AppRestoreConnectionError is raised. + mock_create_connection.side_effect = IOError('socket timed out') + with self.assertRaisesRegex( + jsonrpc_client_base.AppRestoreConnectionError, + ('Failed to restore app connection for %s at host port %s, ' + 'device port %s') % (MOCK_PACKAGE_NAME, 789, 456)): + client.restore_app_connection() + @mock.patch('socket.create_connection') @mock.patch('mobly.controllers.android_device_lib.snippet_client.' 'utils.start_standing_subprocess')
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
1.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work execnet==2.1.1 future==1.0.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/google/mobly.git@f1aff6a7f06887424759e3c192b1bf6e13d2a6bf#egg=mobly mock==1.0.1 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work portpicker==1.6.0 psutil==7.0.0 pyserial==3.5 pytest @ file:///croot/pytest_1738938843180/work pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 pytz==2025.2 PyYAML==6.0.2 timeout-decorator==0.5.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typing_extensions==4.13.0
name: mobly channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - execnet==2.1.1 - future==1.0.0 - mock==1.0.1 - portpicker==1.6.0 - psutil==7.0.0 - pyserial==3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - pytz==2025.2 - pyyaml==6.0.2 - timeout-decorator==0.5.0 - typing-extensions==4.13.0 prefix: /opt/conda/envs/mobly
[ "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_logs_cmd", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_logs_cmd_with_unexpected_stdout", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_reads_unexpected_stdout", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_restore_event_client" ]
[]
[ "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_cli_cmd_to_string", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_list", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_one_arg_command", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_one_arg_command_list", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_one_command", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_serial", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_serial_with_list", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_auto_quotes", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_list", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_one_arg_command", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_one_arg_command_list", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_one_command", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_serial", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_serial_with_list", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_special_characters", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_formats_command", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_formats_command_with_shell_true", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_shell_true", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_stderr_pipe", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_error_no_timeout", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_no_timeout_success", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_timed_out", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_negative_timeout_value", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_timeout_success", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_adb_and_process_stdout_formats_command", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_raises_adb_error", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_reads_stdout", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_returns_stderr", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_when_cmd_eof", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_when_cmd_exits", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_when_handler_crash", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_forward", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_called_correctly", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_existing_command", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_missing_command_on_newer_devices", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_missing_command_on_older_devices", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_handler", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_handler_with_options", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_handler_with_runner", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_options", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_runner", "tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_without_parameters", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_app_not_installed", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_not_instrumented", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_target_not_installed", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_normal", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_header_junk", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_no_valid_line", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_persistent_session", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_unknown_protocol", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_crash", "tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_event_client" ]
[]
Apache License 2.0
2,581
[ "mobly/controllers/android_device_lib/snippet_client.py", "mobly/controllers/android_device_lib/adb.py" ]
[ "mobly/controllers/android_device_lib/snippet_client.py", "mobly/controllers/android_device_lib/adb.py" ]
fniessink__next-action-76
b19f717b5bab95a8cbbd0f9ce33d0ad7813451d7
2018-05-24 21:58:21
b19f717b5bab95a8cbbd0f9ce33d0ad7813451d7
diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e024cc..d57b572 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- Option to limit the next action to tasks that are over due. Closes #75. + ## [0.8.0] - 2018-05-24 ### Added diff --git a/README.md b/README.md index f76dbf3..46d4a98 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the ```console $ next-action --help -usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [<context|project> ...] +usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by @@ -46,6 +46,7 @@ optional arguments: -n <number>, --number <number> number of next actions to show (default: 1) -a, --all show all next actions + -o, --overdue show only overdue next actions optional context and project arguments; these can be repeated: @<context> context the next action must have @@ -99,6 +100,13 @@ $ next-action -+PaintHouse @store (G) Buy wood for new +DogHouse @store ``` +To make sure you have no overdue actions, or work on overdue actions first, limit the tasks from which the next action is selected to overdue actions: + +```console +$ next-action --overdue +Buy flowers due:2018-02-14 +``` + ### Showing more than one next action To show more than one next action, supply the number you think you can handle: @@ -189,9 +197,9 @@ To run the unit tests: ```console $ python -m unittest -........................................................................................................................ +........................................................................................................................... ---------------------------------------------------------------------- -Ran 120 tests in 0.202s +Ran 123 tests in 0.187s OK ``` diff --git a/docs/todo.txt b/docs/todo.txt index df5e79a..f69b27d 100644 --- a/docs/todo.txt +++ b/docs/todo.txt @@ -4,5 +4,6 @@ (G) Buy wood for new +DogHouse @store Get rid of old +DogHouse @home Borrow ladder from the neighbors +PaintHouse @home +Buy flowers due:2018-02-14 x This is a completed task 9999-01-01 Start preparing for five-digit years diff --git a/next_action/arguments/__init__.py b/next_action/arguments/__init__.py index efc3a95..6b132bd 100644 --- a/next_action/arguments/__init__.py +++ b/next_action/arguments/__init__.py @@ -3,23 +3,23 @@ import argparse import os import shutil -import sys -from typing import cast, Dict, List, Set, Tuple +from typing import Tuple from .arguments import Arguments from .parser import NextActionArgumentParser -def parse_arguments() -> Arguments: +def parse_arguments() -> Tuple[argparse.ArgumentParser, Arguments]: """ Build the argument parser, parse the command line arguments, and post-process them. """ # Ensure that the help info is printed using all columns available os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns) default_filenames = ["~/todo.txt"] parser = NextActionArgumentParser(default_filenames) - arguments = Arguments(parser, default_filenames) + arguments = Arguments(default_filenames) namespace = parser.parse_args() arguments.filenames = namespace.file arguments.number = namespace.number arguments.show_all(namespace.all) + arguments.overdue = namespace.overdue arguments.filters = namespace.filters - return arguments + return parser, arguments diff --git a/next_action/arguments/arguments.py b/next_action/arguments/arguments.py index b7b5a73..5356fc5 100644 --- a/next_action/arguments/arguments.py +++ b/next_action/arguments/arguments.py @@ -1,6 +1,5 @@ """ Argument data class for transfering command line arguments. """ -import argparse import os.path import sys from typing import List, Set @@ -8,12 +7,12 @@ from typing import List, Set class Arguments(object): """ Argument data class. """ - def __init__(self, parser: argparse.ArgumentParser, default_filenames: List[str]) -> None: - self.parser = parser + def __init__(self, default_filenames: List[str]) -> None: self.__default_filenames = default_filenames self.__filenames: List[str] = [] - self.__filters: List[Set[str]] = [] + self.__filters: List[Set[str]] = [set(), set(), set(), set()] self.number = 1 + self.overdue = False @property def filenames(self) -> List[str]: diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index 604915c..860f94a 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -19,7 +19,7 @@ class NextActionArgumentParser(argparse.ArgumentParser): "todo.txt file based on task properties such as priority, due date, and creation date. Limit " "the tasks from which the next action is selected by specifying contexts the tasks must have " "and/or projects the tasks must belong to.", - usage="next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] " + usage="next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] " "[<context|project> ...]") self.add_optional_arguments(default_filenames) self.add_positional_arguments() @@ -45,6 +45,7 @@ class NextActionArgumentParser(argparse.ArgumentParser): "-n", "--number", metavar="<number>", type=int, default=1, help="number of next actions to show (default: %(default)s)") number.add_argument("-a", "--all", help="show all next actions", action="store_true") + self.add_argument("-o", "--overdue", help="show only overdue next actions", action="store_true") def add_positional_arguments(self) -> None: """ Add the positional arguments to the parser. """ diff --git a/next_action/cli.py b/next_action/cli.py index 03cda4c..68f2c50 100644 --- a/next_action/cli.py +++ b/next_action/cli.py @@ -15,11 +15,11 @@ def next_action() -> None: 2) read todo.txt file(s), 3) determine the next action(s) and display them. """ - arguments = parse_arguments() + parser, arguments = parse_arguments() try: with fileinput.input(arguments.filenames) as todotxt_file: tasks = read_todotxt_file(todotxt_file) except OSError as reason: - arguments.parser.error("can't open file: {0}".format(reason)) - actions = next_actions(tasks, *arguments.filters) + parser.error("can't open file: {0}".format(reason)) + actions = next_actions(tasks, arguments) print("\n".join(action.text for action in actions[:arguments.number]) if actions else "Nothing to do!") diff --git a/next_action/pick_action.py b/next_action/pick_action.py index 71646d4..aa9d625 100644 --- a/next_action/pick_action.py +++ b/next_action/pick_action.py @@ -1,9 +1,10 @@ """ Algorithm for deciding the next action(s). """ import datetime -from typing import Set, Sequence, Tuple +from typing import Sequence, Tuple from .todotxt import Task +from .arguments import Arguments def sort_key(task: Task) -> Tuple[str, datetime.date, datetime.date, int]: @@ -12,9 +13,9 @@ def sort_key(task: Task) -> Tuple[str, datetime.date, datetime.date, int]: -len(task.projects())) -def next_actions(tasks: Sequence[Task], contexts: Set[str] = None, projects: Set[str] = None, - excluded_contexts: Set[str] = None, excluded_projects: Set[str] = None) -> Sequence[Task]: +def next_actions(tasks: Sequence[Task], arguments: Arguments) -> Sequence[Task]: """ Return the next action(s) from the collection of tasks. """ + contexts, projects, excluded_contexts, excluded_projects = arguments.filters # First, get the potential next actions by filtering out completed tasks and tasks with a future creation date actionable_tasks = [task for task in tasks if task.is_actionable()] # Then, exclude tasks that have an excluded context @@ -27,5 +28,7 @@ def next_actions(tasks: Sequence[Task], contexts: Set[str] = None, projects: Set tasks_in_context = filter(lambda task: contexts <= task.contexts() if contexts else True, eligible_tasks) # Next, select the tasks that belong to at least one of the given projects, if any tasks_in_project = filter(lambda task: projects & task.projects() if projects else True, tasks_in_context) + # If the user only wants to see overdue tasks, filter out non-overdue tasks + tasks_in_project = filter(lambda task: task.is_overdue() if arguments.overdue else True, tasks_in_project) # Finally, sort by priority, due date and creation date return sorted(tasks_in_project, key=sort_key) diff --git a/next_action/todotxt/task.py b/next_action/todotxt/task.py index 5a2e37f..226a5df 100644 --- a/next_action/todotxt/task.py +++ b/next_action/todotxt/task.py @@ -54,6 +54,10 @@ class Task(object): date. """ return not self.is_completed() and not self.is_future() + def is_overdue(self) -> bool: + """ Return whether the taks is overdue, i.e. whether it has a due date in the past. """ + return self.due_date() < datetime.date.today() if self.due_date() else False + def __prefixed_items(self, prefix: str) -> Set[str]: """ Return the prefixed items in the task. """ return {match.group(1) for match in re.finditer(" {0}([^ ]+)".format(prefix), self.text)}
Show only overdue tasks Select a next action that is over due: ```console $ next-action --over-due Buy flowers due:2018-02-14 ``` Show all overdue next actions: ```console $ next-action --all --over-due Buy flowers due:2018-02-14 Submit taxes due:2018-05-01 ```
fniessink/next-action
diff --git a/tests/unittests/arguments/test_arguments.py b/tests/unittests/arguments/test_arguments.py index 50d4da0..3a76282 100644 --- a/tests/unittests/arguments/test_arguments.py +++ b/tests/unittests/arguments/test_arguments.py @@ -1,7 +1,6 @@ """ Unit tests for the argument data class. """ import unittest -from unittest.mock import Mock from next_action.arguments import Arguments @@ -11,22 +10,22 @@ class FilenameArgumentsTest(unittest.TestCase): def test_default_filenames(self): """ Test that the default file name is returned when no filenames are set. """ - self.assertEqual(["todo.txt"], Arguments(Mock(), ["todo.txt"]).filenames) + self.assertEqual(["todo.txt"], Arguments(["todo.txt"]).filenames) def test_set_filenames(self): """ Test that the set file names are returned when filenames are set. """ - arguments = Arguments(Mock(), ["todo.txt"]) + arguments = Arguments(["todo.txt"]) arguments.filenames = ["foo.txt"] self.assertEqual(["foo.txt"], arguments.filenames) def test_remove_default(self): """ Test that the default filename is removed when it is the filenames. """ - arguments = Arguments(Mock(), ["todo.txt"]) + arguments = Arguments(["todo.txt"]) arguments.filenames = ["todo.txt", "foo.txt"] self.assertEqual(["foo.txt"], arguments.filenames) def test_remove_default_once(self): """ Test that the default filename is removed when it is the filenames, but only one time. """ - arguments = Arguments(Mock(), ["todo.txt"]) + arguments = Arguments(["todo.txt"]) arguments.filenames = ["todo.txt", "todo.txt", "foo.txt"] self.assertEqual(["todo.txt", "foo.txt"], arguments.filenames) diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py index 775e336..c0fd64c 100644 --- a/tests/unittests/arguments/test_config.py +++ b/tests/unittests/arguments/test_config.py @@ -19,14 +19,14 @@ class ConfigFileTest(unittest.TestCase): @patch.object(config, "open", mock_open(read_data="")) def test_empty_file(self): """ Test that an empty config file doesn't change the filenames. """ - self.assertEqual([os.path.expanduser("~/todo.txt")], parse_arguments().filenames) + self.assertEqual([os.path.expanduser("~/todo.txt")], parse_arguments()[1].filenames) @patch.object(sys, "argv", ["next-action"]) @patch.object(config, "open") def test_missing_default_config(self, mock_file_open): """ Test that a missing config file at the default location is no problem. """ mock_file_open.side_effect = FileNotFoundError("some problem") - self.assertEqual([os.path.expanduser("~/todo.txt")], parse_arguments().filenames) + self.assertEqual([os.path.expanduser("~/todo.txt")], parse_arguments()[1].filenames) @patch.object(sys, "argv", ["next-action", "--config-file", "config.cfg"]) @patch.object(config, "open", mock_open(read_data="- this_is_invalid")) @@ -130,19 +130,19 @@ class FilenameTest(unittest.TestCase): @patch.object(config, "open", mock_open(read_data="file: todo.txt")) def test_valid_file(self): """ Test that a valid filename changes the filenames. """ - self.assertEqual(["todo.txt"], parse_arguments().filenames) + self.assertEqual(["todo.txt"], parse_arguments()[1].filenames) @patch.object(sys, "argv", ["next-action", "--config-file", "config.cfg"]) @patch.object(config, "open", mock_open(read_data="file:\n- todo.txt\n- tada.txt")) def test_valid_files(self): """ Test that a list of valid filenames changes the filenames. """ - self.assertEqual(["todo.txt", "tada.txt"], parse_arguments().filenames) + self.assertEqual(["todo.txt", "tada.txt"], parse_arguments()[1].filenames) @patch.object(sys, "argv", ["next-action", "--config-file", "config.cfg", "--file", "tada.txt"]) @patch.object(config, "open", mock_open(read_data="file: todo.txt")) def test_cli_takes_precedence(self): """ Test that a command line argument overrules the filename in the configuration file. """ - self.assertEqual(["tada.txt"], parse_arguments().filenames) + self.assertEqual(["tada.txt"], parse_arguments()[1].filenames) class NumberTest(unittest.TestCase): @@ -175,19 +175,19 @@ class NumberTest(unittest.TestCase): @patch.object(config, "open", mock_open(read_data="number: 3")) def test_valid_number(self): """ Test that a valid number changes the number argument. """ - self.assertEqual(3, parse_arguments().number) + self.assertEqual(3, parse_arguments()[1].number) @patch.object(sys, "argv", ["next-action", "--config-file", "config.cfg", "--number", "3"]) @patch.object(config, "open", mock_open(read_data="number: 2")) def test_cli_takes_precedence(self): """ Test that a command line argument overrules the number in the configuration file. """ - self.assertEqual(3, parse_arguments().number) + self.assertEqual(3, parse_arguments()[1].number) @patch.object(sys, "argv", ["next-action", "--config-file", "config.cfg"]) @patch.object(config, "open", mock_open(read_data="all: True")) def test_all_true(self): """ Test that all is true sets number to the max number. """ - self.assertEqual(sys.maxsize, parse_arguments().number) + self.assertEqual(sys.maxsize, parse_arguments()[1].number) @patch.object(sys, "argv", ["next-action", "--config-file", "config.cfg"]) @patch.object(config, "open", mock_open(read_data="all: False")) @@ -218,10 +218,10 @@ class NumberTest(unittest.TestCase): @patch.object(config, "open", mock_open(read_data="all: True")) def test_argument_nr_overrides(self): """ Test that --number on the command line overrides --all in the configuration file. """ - self.assertEqual(3, parse_arguments().number) + self.assertEqual(3, parse_arguments()[1].number) @patch.object(sys, "argv", ["next-action", "--config-file", "config.cfg", "--all"]) @patch.object(config, "open", mock_open(read_data="number: 3")) def test_argument_all_overrides(self): """ Test that --all on the command line overrides --number in the configuration file. """ - self.assertEqual(sys.maxsize, parse_arguments().number) + self.assertEqual(sys.maxsize, parse_arguments()[1].number) diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py index 13801e9..d735f20 100644 --- a/tests/unittests/arguments/test_parser.py +++ b/tests/unittests/arguments/test_parser.py @@ -8,7 +8,7 @@ from unittest.mock import call, mock_open, patch from next_action.arguments import config, parse_arguments -USAGE_MESSAGE = "usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] " \ +USAGE_MESSAGE = "usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] " \ "[<context|project> ...]\n" @@ -19,12 +19,12 @@ class NoArgumentTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action"]) def test_filters(self): """ Test that the argument parser returns no filters if the user doesn't pass one. """ - self.assertEqual([set(), set(), set(), set()], parse_arguments().filters) + self.assertEqual([set(), set(), set(), set()], parse_arguments()[1].filters) @patch.object(sys, "argv", ["next-action"]) def test_filename(self): """ Test that the argument parser returns the default filename if the user doesn't pass one. """ - self.assertEqual([os.path.expanduser("~/todo.txt")], parse_arguments().filenames) + self.assertEqual([os.path.expanduser("~/todo.txt")], parse_arguments()[1].filenames) @patch.object(config, "open", mock_open(read_data="")) @@ -34,27 +34,27 @@ class FilenameTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action", "-f", "my_todo.txt"]) def test_filename_argument(self): """ Test that the argument parser accepts a filename. """ - self.assertEqual(["my_todo.txt"], parse_arguments().filenames) + self.assertEqual(["my_todo.txt"], parse_arguments()[1].filenames) @patch.object(sys, "argv", ["next-action", "--file", "my_other_todo.txt"]) def test_long_filename_argument(self): """ Test that the argument parser accepts a filename. """ - self.assertEqual(["my_other_todo.txt"], parse_arguments().filenames) + self.assertEqual(["my_other_todo.txt"], parse_arguments()[1].filenames) @patch.object(sys, "argv", ["next-action", "-f", "todo.txt"]) def test_add_default_filename(self): """ Test that adding the default filename doesn't get it included twice. """ - self.assertEqual(["todo.txt"], parse_arguments().filenames) + self.assertEqual(["todo.txt"], parse_arguments()[1].filenames) @patch.object(sys, "argv", ["next-action", "-f", "todo.txt", "-f", "other.txt"]) def test_default_and_non_default(self): """ Test that adding the default filename and another filename gets both included. """ - self.assertEqual(["todo.txt", "other.txt"], parse_arguments().filenames) + self.assertEqual(["todo.txt", "other.txt"], parse_arguments()[1].filenames) @patch.object(sys, "argv", ["next-action", "-f", "other.txt", "-f", "other.txt"]) def test__add_filename_twice(self): """ Test that adding the same filename twice includes it only once. """ - self.assertEqual(["other.txt"], parse_arguments().filenames) + self.assertEqual(["other.txt"], parse_arguments()[1].filenames) @patch.object(config, "open", mock_open(read_data="")) @@ -64,12 +64,12 @@ class FilterArgumentTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action", "@home"]) def test_one_context(self): """ Test that the argument parser returns the context if the user passes one. """ - self.assertEqual({"home"}, parse_arguments().filters[0]) + self.assertEqual({"home"}, parse_arguments()[1].filters[0]) @patch.object(sys, "argv", ["next-action", "@home", "@work"]) def test_multiple_contexts(self): """ Test that the argument parser returns all contexts if the user passes multiple contexts. """ - self.assertEqual({"home", "work"}, parse_arguments().filters[0]) + self.assertEqual({"home", "work"}, parse_arguments()[1].filters[0]) @patch.object(sys, "argv", ["next-action", "@"]) @patch.object(sys.stderr, "write") @@ -84,7 +84,7 @@ class FilterArgumentTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action", "-@home"]) def test_exclude_context(self): """ Test that contexts can be excluded. """ - self.assertEqual({"home"}, parse_arguments().filters[2]) + self.assertEqual({"home"}, parse_arguments()[1].filters[2]) @patch.object(sys, "argv", ["next-action", "@home", "-@home"]) @patch.object(sys.stderr, "write") @@ -108,12 +108,12 @@ class FilterArgumentTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action", "+DogHouse"]) def test_one_project(self): """ Test that the argument parser returns the project if the user passes one. """ - self.assertEqual({"DogHouse"}, parse_arguments().filters[1]) + self.assertEqual({"DogHouse"}, parse_arguments()[1].filters[1]) @patch.object(sys, "argv", ["next-action", "+DogHouse", "+PaintHouse"]) def test_multiple_projects(self): """ Test that the argument parser returns the projects if the user passes multiple projects. """ - self.assertEqual({"DogHouse", "PaintHouse"}, parse_arguments().filters[1]) + self.assertEqual({"DogHouse", "PaintHouse"}, parse_arguments()[1].filters[1]) @patch.object(sys, "argv", ["next-action", "+"]) @patch.object(sys.stderr, "write") @@ -128,7 +128,7 @@ class FilterArgumentTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action", "-+DogHouse"]) def test_exclude_project(self): """ Test that projects can be excluded. """ - self.assertEqual({"DogHouse"}, parse_arguments().filters[3]) + self.assertEqual({"DogHouse"}, parse_arguments()[1].filters[3]) @patch.object(sys, "argv", ["next-action", "+DogHouse", "-+DogHouse"]) @patch.object(sys.stderr, "write") @@ -153,8 +153,8 @@ class FilterArgumentTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action", "+DogHouse", "@home", "+PaintHouse", "@weekend"]) def test_contexts_and_projects(self): """ Test that the argument parser returns the contexts and the projects, even when mixed. """ - self.assertEqual({"home", "weekend"}, parse_arguments().filters[0]) - self.assertEqual({"DogHouse", "PaintHouse"}, parse_arguments().filters[1]) + self.assertEqual({"home", "weekend"}, parse_arguments()[1].filters[0]) + self.assertEqual({"DogHouse", "PaintHouse"}, parse_arguments()[1].filters[1]) @patch.object(sys, "argv", ["next-action", "home"]) @patch.object(sys.stderr, "write") @@ -174,12 +174,12 @@ class NumberTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action"]) def test_default_number(self): """ Test that the argument parser has a default number of actions to return. """ - self.assertEqual(1, parse_arguments().number) + self.assertEqual(1, parse_arguments()[1].number) @patch.object(sys, "argv", ["next-action", "--number", "3"]) def test_number(self): """ Test that a number of actions to be shown can be passed. """ - self.assertEqual(3, parse_arguments().number) + self.assertEqual(3, parse_arguments()[1].number) @patch.object(sys, "argv", ["next-action", "--number", "not_a_number"]) @patch.object(sys.stderr, "write") @@ -194,7 +194,7 @@ class NumberTest(unittest.TestCase): @patch.object(sys, "argv", ["next-action", "--all"]) def test_all_actions(self): """ Test that --all option also sets the number of actions to show to a very big number. """ - self.assertEqual(sys.maxsize, parse_arguments().number) + self.assertEqual(sys.maxsize, parse_arguments()[1].number) @patch.object(sys, "argv", ["next-action", "--all", "--number", "3"]) @patch.object(sys.stderr, "write") diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index 0eca016..f8ad064 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -65,7 +65,8 @@ class CLITest(unittest.TestCase): os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough. self.assertRaises(SystemExit, next_action) self.assertEqual(call("""\ -usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [<context|project> ...] +usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] [<context|project> \ +...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by @@ -84,6 +85,7 @@ optional arguments: -n <number>, --number <number> number of next actions to show (default: 1) -a, --all show all next actions + -o, --overdue show only overdue next actions optional context and project arguments; these can be repeated: @<context> context the next action must have diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py index 8ccd64b..dad21e7 100644 --- a/tests/unittests/test_pick_action.py +++ b/tests/unittests/test_pick_action.py @@ -3,6 +3,7 @@ import unittest from next_action import todotxt, pick_action +from next_action.arguments import Arguments class PickActionTest(unittest.TestCase): @@ -10,18 +11,18 @@ class PickActionTest(unittest.TestCase): def test_no_tasks(self): """ Test that no tasks means no next action. """ - self.assertEqual([], pick_action.next_actions([])) + self.assertEqual([], pick_action.next_actions([], Arguments([]))) def test_one_task(self): """ If there is one task, that one is the next action. """ task = todotxt.Task("Todo") - self.assertEqual([task], pick_action.next_actions([task])) + self.assertEqual([task], pick_action.next_actions([task], Arguments([]))) def test_multiple_tasks(self): """ If there are multiple tasks, the first is the next action. """ task1 = todotxt.Task("Todo 1") task2 = todotxt.Task("Todo 2") - self.assertEqual([task1, task2], pick_action.next_actions([task1, task2])) + self.assertEqual([task1, task2], pick_action.next_actions([task1, task2], Arguments([]))) def test_higher_prio_goes_first(self): """ If there are multiple tasks with different priorities, the task with the @@ -29,7 +30,7 @@ class PickActionTest(unittest.TestCase): task1 = todotxt.Task("Todo 1") task2 = todotxt.Task("(B) Todo 2") task3 = todotxt.Task("(A) Todo 3") - self.assertEqual([task3, task2, task1], pick_action.next_actions([task1, task2, task3])) + self.assertEqual([task3, task2, task1], pick_action.next_actions([task1, task2, task3], Arguments([]))) def test_creation_dates(self): """ Test that a task with an older creation date takes precedence. """ @@ -37,7 +38,7 @@ class PickActionTest(unittest.TestCase): newer_task = todotxt.Task("2018-02-02 Task 2") older_task = todotxt.Task("2017-01-01 Task 3") self.assertEqual([older_task, newer_task, no_creation_date], - pick_action.next_actions([no_creation_date, newer_task, older_task])) + pick_action.next_actions([no_creation_date, newer_task, older_task], Arguments([]))) def test_priority_and_creation_date(self): """ Test that priority takes precedence over creation date. """ @@ -45,7 +46,7 @@ class PickActionTest(unittest.TestCase): newer_task = todotxt.Task("2018-02-02 Task 2") older_task = todotxt.Task("2017-01-01 Task 3") self.assertEqual([priority, older_task, newer_task], - pick_action.next_actions([priority, newer_task, older_task])) + pick_action.next_actions([priority, newer_task, older_task], Arguments([]))) def test_due_dates(self): """ Test that a task with an earlier due date takes precedence. """ @@ -53,25 +54,25 @@ class PickActionTest(unittest.TestCase): earlier_task = todotxt.Task("Task 2 due:2018-02-02") later_task = todotxt.Task("Task 3 due:2019-01-01") self.assertEqual([earlier_task, later_task, no_due_date], - pick_action.next_actions([no_due_date, later_task, earlier_task])) + pick_action.next_actions([no_due_date, later_task, earlier_task], Arguments([]))) def test_due_and_creation_dates(self): """ Test that a task with a due date takes precedence over creation date. """ task1 = todotxt.Task("2018-1-1 Task 1") task2 = todotxt.Task("Task 2 due:2018-1-1") - self.assertEqual([task2, task1], pick_action.next_actions([task1, task2])) + self.assertEqual([task2, task1], pick_action.next_actions([task1, task2], Arguments([]))) def test_project(self): """ Test that a task with a project takes precedence over a task without a project. """ task1 = todotxt.Task("Task 1") task2 = todotxt.Task("Task 2 +Project") - self.assertEqual([task2, task1], pick_action.next_actions([task1, task2])) + self.assertEqual([task2, task1], pick_action.next_actions([task1, task2], Arguments([]))) def test_projects(self): """ Test that a task with more projects takes precedence over a task with less projects. """ task1 = todotxt.Task("Task 1 +Project") task2 = todotxt.Task("Task 2 +Project1 +Project2") - self.assertEqual([task2, task1], pick_action.next_actions([task1, task2])) + self.assertEqual([task2, task1], pick_action.next_actions([task1, task2], Arguments([]))) class FilterTasksTest(unittest.TestCase): @@ -82,59 +83,78 @@ class FilterTasksTest(unittest.TestCase): task1 = todotxt.Task("Todo 1 @work") task2 = todotxt.Task("(B) Todo 2 @work") task3 = todotxt.Task("(A) Todo 3 @home") - self.assertEqual([task2, task1], pick_action.next_actions([task1, task2, task3], contexts={"work"})) + arguments = Arguments([]) + arguments.filters = ["@work"] + self.assertEqual([task2, task1], pick_action.next_actions([task1, task2, task3], arguments)) def test_contexts(self): """ Test that the next action can be limited to a set of contexts. """ task1 = todotxt.Task("Todo 1 @work @computer") task2 = todotxt.Task("(B) Todo 2 @work @computer") task3 = todotxt.Task("(A) Todo 3 @home @computer") - self.assertEqual([task2, task1], pick_action.next_actions([task1, task2, task3], contexts={"work", "computer"})) + arguments = Arguments([]) + arguments.filters = ["@work", "@computer"] + self.assertEqual([task2, task1], pick_action.next_actions([task1, task2, task3], arguments)) def test_excluded_context(self): """ Test that contexts can be excluded. """ task = todotxt.Task("(A) Todo @computer") - self.assertEqual([], pick_action.next_actions([task], excluded_contexts={"computer"})) + arguments = Arguments([]) + arguments.filters = ["-@computer"] + self.assertEqual([], pick_action.next_actions([task], arguments)) def test_excluded_contexts(self): """ Test that contexts can be excluded. """ task = todotxt.Task("(A) Todo @computer @work") - self.assertEqual([], pick_action.next_actions([task], excluded_contexts={"computer"})) + arguments = Arguments([]) + arguments.filters = ["-@computer"] + self.assertEqual([], pick_action.next_actions([task], arguments)) def test_not_excluded_context(self): """ Test that a task is not excluded if it doesn't belong to the excluded category. """ task = todotxt.Task("(A) Todo @computer") - self.assertEqual([task], pick_action.next_actions([task], excluded_contexts={"phone"})) + arguments = Arguments([]) + arguments.filters = ["-@phone"] + self.assertEqual([task], pick_action.next_actions([task], arguments)) def test_project(self): """ Test that the next action can be limited to a specific project. """ task1 = todotxt.Task("Todo 1 +ProjectX") task2 = todotxt.Task("(B) Todo 2 +ProjectX") task3 = todotxt.Task("(A) Todo 3 +ProjectY") - self.assertEqual([task2, task1], pick_action.next_actions([task1, task2, task3], projects={"ProjectX"})) + arguments = Arguments([]) + arguments.filters = ["+ProjectX"] + self.assertEqual([task2, task1], pick_action.next_actions([task1, task2, task3], arguments)) def test_excluded_project(self): """ Test that projects can be excluded. """ task = todotxt.Task("(A) Todo +DogHouse") - self.assertEqual([], pick_action.next_actions([task], excluded_projects={"DogHouse"})) + arguments = Arguments([]) + arguments.filters = ["-+DogHouse"] + self.assertEqual([], pick_action.next_actions([task], arguments)) def test_excluded_projects(self): """ Test that projects can be excluded. """ task = todotxt.Task("(A) Todo +DogHouse +PaintHouse") - self.assertEqual([], pick_action.next_actions([task], excluded_projects={"DogHouse"})) + arguments = Arguments([]) + arguments.filters = ["-+DogHouse"] + self.assertEqual([], pick_action.next_actions([task], arguments)) def test_not_excluded_project(self): """ Test that a task is not excluded if it doesn't belong to the excluded project. """ task = todotxt.Task("(A) Todo +DogHouse") - self.assertEqual([task], pick_action.next_actions([task], excluded_projects={"PaintHouse"})) + arguments = Arguments([]) + arguments.filters = ["-+PaintHouse"] + self.assertEqual([task], pick_action.next_actions([task], arguments)) def test_project_and_context(self): """ Test that the next action can be limited to a specific project and context. """ task1 = todotxt.Task("Todo 1 +ProjectX @office") task2 = todotxt.Task("(B) Todo 2 +ProjectX") task3 = todotxt.Task("(A) Todo 3 +ProjectY") - self.assertEqual([task1], - pick_action.next_actions([task1, task2, task3], projects={"ProjectX"}, contexts={"office"})) + arguments = Arguments([]) + arguments.filters = ["+ProjectX", "@office"] + self.assertEqual([task1], pick_action.next_actions([task1, task2, task3], arguments)) class IgnoredTasksTest(unittest.TestCase): @@ -144,17 +164,32 @@ class IgnoredTasksTest(unittest.TestCase): """ If there's one completed and one uncompleted task, the uncompleted one is the next action. """ completed_task = todotxt.Task("x Completed") uncompleted_task = todotxt.Task("Todo") - self.assertEqual([uncompleted_task], pick_action.next_actions([completed_task, uncompleted_task])) + arguments = Arguments([]) + self.assertEqual([uncompleted_task], pick_action.next_actions([completed_task, uncompleted_task], arguments)) def test_ignore_future_task(self): """ Ignore tasks with a start date in the future. """ future_task = todotxt.Task("(A) 9999-01-01 Start preparing for five-digit years") regular_task = todotxt.Task("(B) Look busy") - self.assertEqual([regular_task], pick_action.next_actions([future_task, regular_task])) + arguments = Arguments([]) + self.assertEqual([regular_task], pick_action.next_actions([future_task, regular_task], arguments)) def test_ignore_these_tasks(self): """ If all tasks are completed or future tasks, there's no next action. """ completed_task1 = todotxt.Task("x Completed") completed_task2 = todotxt.Task("x Completed too") future_task = todotxt.Task("(A) 9999-01-01 Start preparing for five-digit years") - self.assertEqual([], pick_action.next_actions([completed_task1, completed_task2, future_task])) + arguments = Arguments([]) + self.assertEqual([], pick_action.next_actions([completed_task1, completed_task2, future_task], arguments)) + + +class OverdueTasks(unittest.TestCase): + """ Unit tests for the overdue filter. """ + def test_overdue_tasks(self): + """ Test that tasks that not overdue are filtered. """ + no_duedate = todotxt.Task("Task") + future_duedate = todotxt.Task("Task due:9999-01-01") + overdue = todotxt.Task("Task due:2000-01-01") + arguments = Arguments([]) + arguments.overdue = True + self.assertEqual([overdue], pick_action.next_actions([no_duedate, future_duedate, overdue], arguments)) diff --git a/tests/unittests/todotxt/test_task.py b/tests/unittests/todotxt/test_task.py index efbb5b6..fee0c91 100644 --- a/tests/unittests/todotxt/test_task.py +++ b/tests/unittests/todotxt/test_task.py @@ -115,19 +115,39 @@ class DueDateTest(unittest.TestCase): def test_no_due_date(self): """ Test that tasks have no due date by default. """ - self.assertEqual(None, todotxt.Task("Todo").due_date()) + task = todotxt.Task("Todo") + self.assertEqual(None, task.due_date()) + self.assertFalse(task.is_overdue()) def test_due_date(self): """ Test a valid due date. """ - self.assertEqual(datetime.date(2018, 1, 2), todotxt.Task("Todo due:2018-01-02").due_date()) + task = todotxt.Task("Todo due:2018-01-02") + self.assertEqual(datetime.date(2018, 1, 2), task.due_date()) + self.assertTrue(task.is_overdue()) + + def test_future_due_date(self): + """ Test a future due date. """ + task = todotxt.Task("Todo due:9999-01-01") + self.assertEqual(datetime.date(9999, 1, 1), task.due_date()) + self.assertFalse(task.is_overdue()) + + def test_due_today(self): + """ Test a future due date. """ + task = todotxt.Task("Todo due:{0}".format(datetime.date.today().isoformat())) + self.assertEqual(datetime.date.today(), task.due_date()) + self.assertFalse(task.is_overdue()) def test_invalid_date(self): """ Test an invalid due date. """ - self.assertEqual(None, todotxt.Task("Todo due:2018-01-32").due_date()) + task = todotxt.Task("Todo due:2018-01-32") + self.assertEqual(None, task.due_date()) + self.assertFalse(task.is_overdue()) def test_no_space_after(self): """ Test a due date without a word boundary following it. """ - self.assertEqual(None, todotxt.Task("Todo due:2018-01-023").due_date()) + task = todotxt.Task("Todo due:2018-01-023") + self.assertEqual(None, task.due_date()) + self.assertFalse(task.is_overdue()) def test_single_digits(self): """ Test a due date with single digits for day and/or month. """
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 9 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
Cerberus==1.2 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@b19f717b5bab95a8cbbd0f9ce33d0ad7813451d7#egg=next_action packaging==24.2 pluggy==1.5.0 pytest==8.3.5 PyYAML==3.12 tomli==2.2.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cerberus==1.2 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pyyaml==3.12 - tomli==2.2.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_arguments.py::FilenameArgumentsTest::test_default_filenames", "tests/unittests/arguments/test_arguments.py::FilenameArgumentsTest::test_remove_default", "tests/unittests/arguments/test_arguments.py::FilenameArgumentsTest::test_remove_default_once", "tests/unittests/arguments/test_arguments.py::FilenameArgumentsTest::test_set_filenames", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key", "tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files", "tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_config.py::NumberTest::test_all_false", "tests/unittests/arguments/test_config.py::NumberTest::test_all_true", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_valid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_zero", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters", "tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice", "tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename", "tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default", "tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument", "tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_default_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_number", "tests/unittests/test_cli.py::CLITest::test_help", "tests/unittests/test_cli.py::CLITest::test_missing_file", "tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_due_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first", "tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks", "tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks", "tests/unittests/test_pick_action.py::PickActionTest::test_one_task", "tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date", "tests/unittests/test_pick_action.py::PickActionTest::test_project", "tests/unittests/test_pick_action.py::PickActionTest::test_projects", "tests/unittests/test_pick_action.py::FilterTasksTest::test_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_contexts", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_contexts", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_projects", "tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_project_and_context", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_completed_task", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_future_task", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_these_tasks", "tests/unittests/test_pick_action.py::OverdueTasks::test_overdue_tasks", "tests/unittests/todotxt/test_task.py::DueDateTest::test_due_date", "tests/unittests/todotxt/test_task.py::DueDateTest::test_due_today", "tests/unittests/todotxt/test_task.py::DueDateTest::test_future_due_date", "tests/unittests/todotxt/test_task.py::DueDateTest::test_invalid_date", "tests/unittests/todotxt/test_task.py::DueDateTest::test_no_due_date", "tests/unittests/todotxt/test_task.py::DueDateTest::test_no_space_after" ]
[]
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config", "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_version", "tests/unittests/todotxt/test_task.py::TodoTest::test_task_repr", "tests/unittests/todotxt/test_task.py::TodoTest::test_task_text", "tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_context", "tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_space_before_at_sign", "tests/unittests/todotxt/test_task.py::TodoContextTest::test_one_context", "tests/unittests/todotxt/test_task.py::TodoContextTest::test_two_contexts", "tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_projects", "tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_space_before_at_sign", "tests/unittests/todotxt/test_task.py::TaskProjectTest::test_one_project", "tests/unittests/todotxt/test_task.py::TaskProjectTest::test_two_projects", "tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_faulty_priorities", "tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_no_priority", "tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priorities", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date_after_priority", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_invalid_creation_date", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_is_future_task", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_creation_date", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_space_after", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_single_digits", "tests/unittests/todotxt/test_task.py::DueDateTest::test_single_digits", "tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_completed", "tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_not_completed", "tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_space_after_x", "tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_x_must_be_lowercase", "tests/unittests/todotxt/test_task.py::ActionableTest::test_completed_task", "tests/unittests/todotxt/test_task.py::ActionableTest::test_default", "tests/unittests/todotxt/test_task.py::ActionableTest::test_future_creation_date", "tests/unittests/todotxt/test_task.py::ActionableTest::test_past_creation_date", "tests/unittests/todotxt/test_task.py::ActionableTest::test_two_dates" ]
[]
Apache License 2.0
2,582
[ "docs/todo.txt", "next_action/arguments/arguments.py", "next_action/arguments/parser.py", "next_action/pick_action.py", "CHANGELOG.md", "next_action/arguments/__init__.py", "next_action/todotxt/task.py", "README.md", "next_action/cli.py" ]
[ "docs/todo.txt", "next_action/arguments/arguments.py", "next_action/arguments/parser.py", "next_action/pick_action.py", "CHANGELOG.md", "next_action/arguments/__init__.py", "next_action/todotxt/task.py", "README.md", "next_action/cli.py" ]
mgerst__flag-slurper-22
1f40a7114313537d02472290381845841767d028
2018-05-24 23:50:51
dca0114c619f7a091d852d4f23cacb73c3c93ed4
diff --git a/flag_slurper/autolib/governor.py b/flag_slurper/autolib/governor.py new file mode 100644 index 0000000..5ace3ae --- /dev/null +++ b/flag_slurper/autolib/governor.py @@ -0,0 +1,64 @@ +import logging +import socket +import time +from collections import defaultdict +from datetime import datetime, timedelta +from typing import Optional + +logger = logging.getLogger(__name__) + + +class Governor: + """ + The governor tracks the number of connections over time + to a given ip address. This is used for fail2ban evasion. + + This can be configured in the flagrc. + + .. warning:: + + The governor only tracks withing it's worker process, for a single run. + It **DOES NOT** persist across invocations. + + * ``autopwn->governor`` (default false) whether the governor is enabled. + * ``autopwn->delay`` (default 5m) how long to wait after limiting. + * ``autopwn->window`` (default 30m) the window to track attempts in. + * ``autopwn->times`` (default 3) max attempts inside of the window. + """ + instance = None + + def __init__(self, enabled: bool, delay: int = 5 * 60, window: int = 30 * 60, times: int = 3): + self.enabled = enabled + self.delay = delay + self.window = window + self.times = times + + # Dict[IP, timestamp] + self.limits = defaultdict(list) + + @classmethod + def get_instance(cls, enabled: Optional[bool] = False, delay: Optional[int] = 5 * 60, + window: Optional[int] = 30 * 60, times: Optional[int] = 3) -> 'Governor': + if not Governor.instance: + Governor.instance = cls(enabled, delay, window, times) + return Governor.instance + + def filter(self, ipaddr: str): + def _filter(x: datetime): + return x > datetime.now() - timedelta(seconds=self.window) + + self.limits[ipaddr] = list(filter(_filter, self.limits[ipaddr])) + + def attempt(self, ipaddr: str): + if not self.enabled: + return + + self.filter(ipaddr) + self.limits[ipaddr].append(datetime.now()) + if len(self.limits[ipaddr]) > self.times: + logger.info("Attempting %d second delay for %s", self.delay, ipaddr) + time.sleep(self.delay) + + @staticmethod + def resolve_url(url: str) -> str: + return socket.gethostbyname(url) diff --git a/flag_slurper/autolib/protocols.py b/flag_slurper/autolib/protocols.py index 8abf1d9..a655a8e 100644 --- a/flag_slurper/autolib/protocols.py +++ b/flag_slurper/autolib/protocols.py @@ -5,6 +5,7 @@ from typing import Tuple import paramiko from flag_slurper.autolib.exploit import get_file_contents, get_system_info +from flag_slurper.autolib.governor import Governor from .exploit import find_flags, FlagConf, can_sudo from .models import Service, CredentialBag, Credential, Flag, CaptureNote from .post import post_ssh @@ -26,6 +27,10 @@ def pwn_ssh(url: str, port: int, service: Service, flag_conf: FlagConf) -> Tuple working = set() credentials = CredentialBag.select() for credential in credentials: + # Govern if necessary (and enabled) + gov = Governor.get_instance() + gov.attempt(gov.resolve_url(url)) + try: cred = credential.credentials.where(Credential.service == service).get() except Credential.DoesNotExist: diff --git a/flag_slurper/autopwn.py b/flag_slurper/autopwn.py index b0a625d..4d77997 100644 --- a/flag_slurper/autopwn.py +++ b/flag_slurper/autopwn.py @@ -4,6 +4,7 @@ from multiprocessing import Pool import click +from flag_slurper.autolib.governor import Governor from flag_slurper.autolib.models import SUDO_FLAG from . import utils, autolib from .autolib import models diff --git a/flag_slurper/config.py b/flag_slurper/config.py index 2f43948..09c969a 100644 --- a/flag_slurper/config.py +++ b/flag_slurper/config.py @@ -7,6 +7,8 @@ import requests from click import echo, prompt from jinja2 import Environment +from flag_slurper.autolib.governor import Governor + ROOT = Path(__file__).parent @@ -31,9 +33,19 @@ class Config(ConfigParser): conffiles.append(extra) conf.read(conffiles) + conf.configure_governor() + cls.instance = conf return conf + def configure_governor(self): + from .utils import parse_duration + gov = Governor.get_instance() + gov.enabled = self.getboolean('autopwn', 'governor') + gov.delay = parse_duration(self['autopwn']['delay']) + gov.window = parse_duration(self['autopwn']['window']) + gov.times = self.getint('autopwn', 'times') + @staticmethod def get_instance(): if not Config.instance: diff --git a/flag_slurper/default.ini b/flag_slurper/default.ini index 5ab9cbd..72ae3f2 100644 --- a/flag_slurper/default.ini +++ b/flag_slurper/default.ini @@ -5,3 +5,9 @@ api_version=v1 [database] url=sqlite:///{{ project }}/db.sqlite3 + +[autopwn] +governor=false +delay=5m +window=30m +times=3 diff --git a/flag_slurper/utils.py b/flag_slurper/utils.py index d44fa83..b06dd61 100644 --- a/flag_slurper/utils.py +++ b/flag_slurper/utils.py @@ -2,6 +2,7 @@ import os import shutil import zipfile from typing import Tuple, Dict, Union, Callable, Optional +import string import click import requests @@ -167,3 +168,43 @@ def conditional_page(output: str, size: int): click.echo_via_pager(output) else: click.echo(output) + + +def parse_duration(duration: str) -> int: + """ + Parses a duration of the form 10m or 5s and converts + them into seconds. + + >>> parse_duration('5s') + ... 5 + >>> parse_duration('10m') + ... 600 + + .. note:: + + Only one unit is supported. For example 1h30m is not supported, but 90m is. + + Supported suffixes: + + - ``h`` hours + - ``m`` minutes + - ``s`` seconds + + An omitted suffix will be interpreted as seconds. + + :param duration: The duration in string form + :return: The duration in seconds + """ + if duration[-1] in string.digits: + return int(duration) + + if duration[-1].lower() == 'h': + return int(duration[:-1]) * 60 * 60 + + if duration[-1].lower() == 'm': + return int(duration[:-1]) * 60 + + if duration[-1].lower() == 's': + return int(duration[:-1]) + + raise ValueError("Unable to parse {duration} as a duration".format(duration=duration))
Add delay to AutoPWN to avoid fail2ban Fail2ban's default configuration bans an IP if it fails to login 3 times in a 10 minutes window. The default credential list, *in theory*, should not trip this since it only makes two attempts (`root:cdc` and `cdc:cdc`). AutoPWN should either add a delay in between each attempt or add a delay after `maxretry - 1` attempts. Either way it should be configurable.
mgerst/flag-slurper
diff --git a/tests/autolib/test_governor.py b/tests/autolib/test_governor.py new file mode 100644 index 0000000..f9812b5 --- /dev/null +++ b/tests/autolib/test_governor.py @@ -0,0 +1,64 @@ +from datetime import datetime, timedelta + +from flag_slurper.autolib.governor import Governor + + +def test_governor_singleton(): + Governor.instance = None + Governor.get_instance(True) + gov = Governor.get_instance() + assert gov.enabled + assert gov.delay == 5 * 60 + assert gov.window == 30 * 60 + assert gov.times == 3 + + +def test_governor_tracks(mock): + Governor.instance = None + gov = Governor.get_instance(True) + sleep = mock.patch('flag_slurper.autolib.governor.time.sleep') + gov.attempt('192.168.1.113') + assert not sleep.called + + +def test_governor_filter(): + Governor.instance = None + gov = Governor.get_instance(True) + gov.limits['192.168.1.113'] = [datetime.now() - timedelta(minutes=3), + datetime.now() - timedelta(minutes=29), + datetime.now() - timedelta(minutes=1), + datetime.now() - timedelta(minutes=35)] + gov.filter('192.168.1.113') + assert len(gov.limits['192.168.1.113']) == 3 + + +def test_governor_limits(mock): + Governor.instance = None + gov = Governor.get_instance(True) + gov.limits['192.168.1.113'] = [datetime.now() - timedelta(minutes=3), + datetime.now() - timedelta(minutes=29), + datetime.now() - timedelta(minutes=1), + datetime.now() - timedelta(minutes=35)] + sleep = mock.patch('flag_slurper.autolib.governor.time.sleep') + gov.attempt('192.168.1.113') + assert sleep.called + + +def test_governer_doesnt_limit_when_disabled(mock): + Governor.instance = None + gov = Governor.get_instance(False) + gov.limits['192.168.1.113'] = [datetime.now() - timedelta(minutes=3), + datetime.now() - timedelta(minutes=29), + datetime.now() - timedelta(minutes=1), + datetime.now() - timedelta(minutes=35)] + sleep = mock.patch('flag_slurper.autolib.governor.time.sleep') + gov.attempt('192.168.1.113') + assert not sleep.called + + +def test_governor_resolve(mock): + addrhost = mock.patch('flag_slurper.autolib.governor.socket.gethostbyname') + addrhost.return_value = '192.168.1.113' + ipaddr = Governor.resolve_url('example.com') + assert addrhost.called_with('example.com') + assert ipaddr == '192.168.1.113' diff --git a/tests/test_config.py b/tests/test_config.py index f142137..565e575 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -4,6 +4,7 @@ from unittest import mock from click.testing import CliRunner +from flag_slurper.autolib.governor import Governor from flag_slurper.cli import cli from flag_slurper.config import Config from flag_slurper.models import User @@ -97,3 +98,13 @@ def test_config_login(tmpdir): c.read_file(tmpdir.join('flagrc').open('r')) assert 'iscore' in c and 'api_token' in c['iscore'] assert c['iscore']['api_token'] == 'abcdef' + + +def test_config_governor(tmpdir): + rc = tmpdir.join("flagrc.ini") + rc.write("[autopwn]\ngovernor=yes\ndelay=6m\n") + + Config.load(str(rc), noflagrc=True) + gov = Governor.get_instance() + assert gov.enabled + assert gov.delay == 6 * 60 diff --git a/tests/test_utils.py b/tests/test_utils.py index 14bd39a..0dd9ed6 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -168,3 +168,25 @@ def test_get_teams(config): def test_parse_creds(given, expected): result = utils.parse_creds(given) assert result == expected + + [email protected]('given,expected', ( + ('3', 3), + ('5s', 5), + ('10m', 10 * 60), + ('3h', 3 * 60 * 60), +)) +def test_parse_duration(given, expected): + result = utils.parse_duration(given) + assert result == expected + + [email protected]('given', ( + 'abc', + '30y', + '2d', +)) +def test_parse_duration_invalid(given): + with pytest.raises(ValueError, match=r'Unable to parse \w+ as a duration$'): + utils.parse_duration(given) +
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 5 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[remote,parallel,tests]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-sugar", "pytest-mock", "tox", "vcrpy", "responses", "pretend" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 bcrypt==4.0.1 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 cryptography==40.0.2 distlib==0.3.9 filelock==3.4.1 -e git+https://github.com/mgerst/flag-slurper.git@1f40a7114313537d02472290381845841767d028#egg=flag_slurper idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 Jinja2==3.0.3 MarkupSafe==2.0.1 multidict==5.2.0 packaging==21.3 paramiko==3.5.1 peewee==3.17.9 platformdirs==2.4.0 pluggy==1.0.0 pretend==1.0.9 psycopg2-binary==2.9.5 py==1.11.0 pycparser==2.21 PyNaCl==1.5.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-sugar==0.9.6 PyYAML==6.0.1 requests==2.27.1 responses==0.17.0 schema==0.7.7 six==1.17.0 termcolor==1.1.0 terminaltables==3.1.10 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 vcrpy==4.1.1 virtualenv==20.17.1 wrapt==1.16.0 yarl==1.7.2 zipp==3.6.0
name: flag-slurper channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - bcrypt==4.0.1 - cffi==1.15.1 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - cryptography==40.0.2 - distlib==0.3.9 - filelock==3.4.1 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jinja2==3.0.3 - markupsafe==2.0.1 - multidict==5.2.0 - packaging==21.3 - paramiko==3.5.1 - peewee==3.17.9 - platformdirs==2.4.0 - pluggy==1.0.0 - pretend==1.0.9 - psycopg2-binary==2.9.5 - py==1.11.0 - pycparser==2.21 - pynacl==1.5.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-sugar==0.9.6 - pyyaml==6.0.1 - requests==2.27.1 - responses==0.17.0 - schema==0.7.7 - six==1.17.0 - termcolor==1.1.0 - terminaltables==3.1.10 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - vcrpy==4.1.1 - virtualenv==20.17.1 - wrapt==1.16.0 - yarl==1.7.2 - zipp==3.6.0 prefix: /opt/conda/envs/flag-slurper
[ "tests/autolib/test_governor.py::test_governor_singleton", "tests/autolib/test_governor.py::test_governor_filter", "tests/test_config.py::test_config_singleton", "tests/test_config.py::test_config_creation", "tests/test_config.py::test_config_load_extra", "tests/test_config.py::test_config_cond_set", "tests/test_config.py::test_config_api_url", "tests/test_config.py::test_config_request_extras_token", "tests/test_config.py::test_config_request_extras_creds", "tests/test_config.py::test_config_user", "tests/test_config.py::test_config_prompt_token", "tests/test_config.py::test_config_prompt_creds", "tests/test_config.py::test_config_login", "tests/test_config.py::test_config_governor", "tests/test_utils.py::test_remote[shell.team1-expected0]", "tests/test_utils.py::test_remote[[email protected]]", "tests/test_utils.py::test_remote[shell.team1:2222-expected2]", "tests/test_utils.py::test_remote[[email protected]:2222-expected3]", "tests/test_utils.py::test_prompt_choice[options0-1.", "tests/test_utils.py::test_prompt_choice[options1-Test", "tests/test_utils.py::test_prompt_choice[options2-1.", "tests/test_utils.py::test_prompt_choice[options3-Test", "tests/test_utils.py::test_prompt_choice[options4-Test", "tests/test_utils.py::test_report_utils[report_success-It", "tests/test_utils.py::test_report_utils[report_status-Status", "tests/test_utils.py::test_report_utils[report_warning-Warning", "tests/test_utils.py::test_report_utils[report_error-Error", "tests/test_utils.py::test_team_map", "tests/test_utils.py::test_save_flags", "tests/test_utils.py::test_save_flags_all_teams", "tests/test_utils.py::test_check_user[user0-0]", "tests/test_utils.py::test_check_user[user1-0]", "tests/test_utils.py::test_check_user[user2-2]", "tests/test_utils.py::test_get_service_status", "tests/test_utils.py::test_get_teams", "tests/test_utils.py::test_parse_creds[root-expected0]", "tests/test_utils.py::test_parse_creds[root:cdc-expected1]", "tests/test_utils.py::test_parse_duration[3-3]", "tests/test_utils.py::test_parse_duration[5s-5]", "tests/test_utils.py::test_parse_duration[10m-600]", "tests/test_utils.py::test_parse_duration[3h-10800]", "tests/test_utils.py::test_parse_duration_invalid[abc]", "tests/test_utils.py::test_parse_duration_invalid[30y]", "tests/test_utils.py::test_parse_duration_invalid[2d]" ]
[]
[]
[]
MIT License
2,583
[ "flag_slurper/autolib/governor.py", "flag_slurper/default.ini", "flag_slurper/config.py", "flag_slurper/utils.py", "flag_slurper/autopwn.py", "flag_slurper/autolib/protocols.py" ]
[ "flag_slurper/autolib/governor.py", "flag_slurper/default.ini", "flag_slurper/config.py", "flag_slurper/utils.py", "flag_slurper/autopwn.py", "flag_slurper/autolib/protocols.py" ]
nipy__nipype-2595
9eaa2a32c8cb3569633a79d6f7968270453f9aed
2018-05-25 01:03:48
704b97dee7848283692bac38f04541c5af2a87b5
diff --git a/doc/users/config_file.rst b/doc/users/config_file.rst index 279dc1aad..8d296556c 100644 --- a/doc/users/config_file.rst +++ b/doc/users/config_file.rst @@ -237,16 +237,23 @@ Debug configuration To enable debug mode, one can insert the following lines:: - from nipype import config, logging + from nipype import config config.enable_debug_mode() - logging.update_logging(config) In this mode the following variables are set:: config.set('execution', 'stop_on_first_crash', 'true') config.set('execution', 'remove_unnecessary_outputs', 'false') + config.set('execution', 'keep_inputs', 'true') config.set('logging', 'workflow_level', 'DEBUG') config.set('logging', 'interface_level', 'DEBUG') + config.set('logging', 'utils_level', 'DEBUG') + +The primary loggers (``workflow``, ``interface`` and ``utils``) are also reset +to level ``DEBUG``. +You may wish to adjust these manually using:: + from nipype import logging + logging.getLogger(<logger>).setLevel(<level>) .. include:: ../links_names.txt diff --git a/doc/users/debug.rst b/doc/users/debug.rst index d5064fd37..fcaa79ea4 100644 --- a/doc/users/debug.rst +++ b/doc/users/debug.rst @@ -20,15 +20,17 @@ performance issues. from nipype import config config.enable_debug_mode() - as the first import of your nipype script. To enable debug logging use:: - - from nipype import logging - logging.update_logging(config) + as the first import of your nipype script. .. note:: - Turning on debug will rerun your workflows and will rerun them after debugging - is turned off. + Turning on debug will rerun your workflows and will rerun them after + debugging is turned off. + + Turning on debug mode will also override log levels specified elsewhere, + such as in the nipype configuration. + ``workflow``, ``interface`` and ``utils`` loggers will all be set to + level ```DEBUG``. #. There are several configuration options that can help with debugging. See :ref:`config_file` for more details:: diff --git a/nipype/utils/config.py b/nipype/utils/config.py index 30b826d23..843748dfe 100644 --- a/nipype/utils/config.py +++ b/nipype/utils/config.py @@ -147,11 +147,14 @@ class NipypeConfig(object): def enable_debug_mode(self): """Enables debug configuration""" + from .. import logging self._config.set('execution', 'stop_on_first_crash', 'true') self._config.set('execution', 'remove_unnecessary_outputs', 'false') self._config.set('execution', 'keep_inputs', 'true') self._config.set('logging', 'workflow_level', 'DEBUG') self._config.set('logging', 'interface_level', 'DEBUG') + self._config.set('logging', 'utils_level', 'DEBUG') + logging.update_logging(self._config) def set_log_dir(self, log_dir): """Sets logging directory
config.enable_debug_mode() does not work as advertised config.enable_debug_mode() is not equivalent to: ``` mkdir ~/.nipype echo "[logging]" > ~/.nipype/nipype.cfg echo "workflow_level = DEBUG" ~/.nipype/nipype.cfg echo "interface_level = DEBUG" >> ~/.nipype/nipype.cfg echo "filemanip_level = DEBUG" >> ~/.nipype/nipype.cfg ```
nipy/nipype
diff --git a/nipype/utils/tests/test_config.py b/nipype/utils/tests/test_config.py index 65ada4c64..38a55b6a0 100644 --- a/nipype/utils/tests/test_config.py +++ b/nipype/utils/tests/test_config.py @@ -241,3 +241,52 @@ def test_cwd_cached(tmpdir): oldcwd = config.cwd tmpdir.chdir() assert config.cwd == oldcwd + + +def test_debug_mode(): + from ... import logging + + sofc_config = config.get('execution', 'stop_on_first_crash') + ruo_config = config.get('execution', 'remove_unnecessary_outputs') + ki_config = config.get('execution', 'keep_inputs') + wf_config = config.get('logging', 'workflow_level') + if_config = config.get('logging', 'interface_level') + ut_config = config.get('logging', 'utils_level') + + wf_level = logging.getLogger('workflow').level + if_level = logging.getLogger('interface').level + ut_level = logging.getLogger('utils').level + + config.enable_debug_mode() + + # Check config is updated and logging levels, too + assert config.get('execution', 'stop_on_first_crash') == 'true' + assert config.get('execution', 'remove_unnecessary_outputs') == 'false' + assert config.get('execution', 'keep_inputs') == 'true' + assert config.get('logging', 'workflow_level') == 'DEBUG' + assert config.get('logging', 'interface_level') == 'DEBUG' + assert config.get('logging', 'utils_level') == 'DEBUG' + + assert logging.getLogger('workflow').level == 10 + assert logging.getLogger('interface').level == 10 + assert logging.getLogger('utils').level == 10 + + # Restore config and levels + config.set('execution', 'stop_on_first_crash', sofc_config) + config.set('execution', 'remove_unnecessary_outputs', ruo_config) + config.set('execution', 'keep_inputs', ki_config) + config.set('logging', 'workflow_level', wf_config) + config.set('logging', 'interface_level', if_config) + config.set('logging', 'utils_level', ut_config) + logging.update_logging(config) + + assert config.get('execution', 'stop_on_first_crash') == sofc_config + assert config.get('execution', 'remove_unnecessary_outputs') == ruo_config + assert config.get('execution', 'keep_inputs') == ki_config + assert config.get('logging', 'workflow_level') == wf_config + assert config.get('logging', 'interface_level') == if_config + assert config.get('logging', 'utils_level') == ut_config + + assert logging.getLogger('workflow').level == wf_level + assert logging.getLogger('interface').level == if_level + assert logging.getLogger('utils').level == ut_level
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 3 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 codecov==2.1.13 configparser==5.2.0 coverage==6.2 cycler==0.11.0 decorator==4.4.2 docutils==0.18.1 execnet==1.9.0 funcsigs==1.0.2 future==1.0.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 isodate==0.6.1 Jinja2==3.0.3 kiwisolver==1.3.1 lxml==5.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mock==5.2.0 networkx==2.5.1 nibabel==3.2.2 -e git+https://github.com/nipy/nipype.git@9eaa2a32c8cb3569633a79d6f7968270453f9aed#egg=nipype numpy==1.19.5 numpydoc==1.1.0 packaging==21.3 Pillow==8.4.0 pluggy==1.0.0 prov==1.5.0 py==1.11.0 pydot==1.4.2 pydotplus==2.0.2 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-env==0.6.2 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2025.2 rdflib==5.0.0 requests==2.27.1 scipy==1.5.4 simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 traits==6.4.1 typing_extensions==4.1.1 urllib3==1.26.20 yapf==0.32.0 zipp==3.6.0
name: nipype channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - codecov==2.1.13 - configparser==5.2.0 - coverage==6.2 - cycler==0.11.0 - decorator==4.4.2 - docutils==0.18.1 - execnet==1.9.0 - funcsigs==1.0.2 - future==1.0.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isodate==0.6.1 - jinja2==3.0.3 - kiwisolver==1.3.1 - lxml==5.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mock==5.2.0 - networkx==2.5.1 - nibabel==3.2.2 - numpy==1.19.5 - numpydoc==1.1.0 - packaging==21.3 - pillow==8.4.0 - pluggy==1.0.0 - prov==1.5.0 - py==1.11.0 - pydot==1.4.2 - pydotplus==2.0.2 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-env==0.6.2 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - rdflib==5.0.0 - requests==2.27.1 - scipy==1.5.4 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - traits==6.4.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - yapf==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/nipype
[ "nipype/utils/tests/test_config.py::test_debug_mode" ]
[]
[ "nipype/utils/tests/test_config.py::test_display_parse[localhost:12]", "nipype/utils/tests/test_config.py::test_cwd_cached", "nipype/utils/tests/test_config.py::test_display_parse[localhost:12.1]", "nipype/utils/tests/test_config.py::test_display_config[1]", "nipype/utils/tests/test_config.py::test_display_noconfig_nosystem_patched_oldxvfbwrapper", "nipype/utils/tests/test_config.py::test_display_system[2]", "nipype/utils/tests/test_config.py::test_display_system[3]", "nipype/utils/tests/test_config.py::test_display_noconfig_nosystem_patched", "nipype/utils/tests/test_config.py::test_display_config[2]", "nipype/utils/tests/test_config.py::test_display_empty_patched_oldxvfbwrapper", "nipype/utils/tests/test_config.py::test_display_system[4]", "nipype/utils/tests/test_config.py::test_display_parse[:12]", "nipype/utils/tests/test_config.py::test_display_noconfig_nosystem_notinstalled", "nipype/utils/tests/test_config.py::test_display_empty_notinstalled", "nipype/utils/tests/test_config.py::test_display_config_and_system", "nipype/utils/tests/test_config.py::test_display_config[3]", "nipype/utils/tests/test_config.py::test_display_empty_macosx", "nipype/utils/tests/test_config.py::test_display_system[1]", "nipype/utils/tests/test_config.py::test_display_system[0]", "nipype/utils/tests/test_config.py::test_display_config[0]", "nipype/utils/tests/test_config.py::test_display_empty_patched", "nipype/utils/tests/test_config.py::test_display_config[4]" ]
[]
Apache License 2.0
2,584
[ "doc/users/debug.rst", "nipype/utils/config.py", "doc/users/config_file.rst" ]
[ "doc/users/debug.rst", "nipype/utils/config.py", "doc/users/config_file.rst" ]
elastic__rally-512
a446d872b6cadc35041d7f15ee05005fa4f7ac4b
2018-05-25 12:18:56
085e3d482717d88dfc2d41aa34502eb108abbfe9
diff --git a/docs/adding_tracks.rst b/docs/adding_tracks.rst index 43f9ab18..dde2e4ca 100644 --- a/docs/adding_tracks.rst +++ b/docs/adding_tracks.rst @@ -96,6 +96,124 @@ For details on the allowed syntax, see the Elasticsearch documentation on `mappi Finally, store the track as ``track.json`` in the tutorial directory:: + { + "version": 2, + "description": "Tutorial benchmark for Rally", + "indices": [ + { + "name": "geonames", + "body": "index.json", + "types": [ "docs" ] + } + ], + "corpora": [ + { + "name": "rally-tutorial", + "documents": [ + { + "source-file": "documents.json", + "document-count": 11658903, + "uncompressed-bytes": 1544799789 + } + ] + } + ], + "schedule": [ + { + "operation": { + "operation-type": "delete-index" + } + }, + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + } + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "operation-type": "force-merge" + } + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 8, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] + } + + +The numbers under the ``documents`` property are needed to verify integrity and provide progress reports. Determine the correct document count with ``wc -l documents.json`` and the size in bytes with ``stat -f "%z" documents.json``. + +.. note:: + + You can store any supporting scripts along with your track. However, you need to place them in a directory starting with "_", e.g. "_support". Rally loads track plugins (see below) from any directory but will ignore directories starting with "_". + +.. note:: + + We have defined a `JSON schema for tracks <https://github.com/elastic/rally/blob/master/esrally/resources/track-schema.json>`_ which you can use to check how to define your track. You should also check the tracks provided by Rally for inspiration. + +The new track appears when you run ``esrally list tracks --track-path=~/rally-tracks/tutorial``:: + + dm@io:~ $ esrally list tracks --track-path=~/rally-tracks/tutorial + + ____ ____ + / __ \____ _/ / /_ __ + / /_/ / __ `/ / / / / / + / _, _/ /_/ / / / /_/ / + /_/ |_|\__,_/_/_/\__, / + /____/ + Available tracks: + + Name Description Documents Compressed Size Uncompressed Size + ---------- ----------------------------- ----------- --------------- ----------------- + tutorial Tutorial benchmark for Rally 11658903 N/A 1.4 GB + +Congratulations, you have created your first track! You can test it with ``esrally --distribution-version=6.0.0 --track-path=~/rally-tracks/tutorial``. + +.. _add_track_test_mode: + +Adding support for test mode +---------------------------- + +You can check your track very quickly for syntax errors when you invoke Rally with ``--test-mode``. Rally postprocesses its internal track representation as follows: + +* Iteration-based tasks run at most one warmup iteration and one measurement iteration. +* Time-period-based tasks run at most for 10 seconds without warmup. + +Rally also postprocesses all data file names. Instead of ``documents.json``, Rally expects ``documents-1k.json`` and assumes the file contains 1.000 documents. You need to prepare these data files though. Pick 1.000 documents for every data file in your track and store them in a file with the suffix ``-1k``. We choose the first 1.000 with ``head -n 1000 documents.json > documents-1k.json``. + +Challenges +---------- + +To specify different workloads in the same track you can use so-called challenges. Instead of specifying the ``schedule`` property on top-level you specify a ``challenges`` array:: + { "version": 2, "description": "Tutorial benchmark for Rally", @@ -174,46 +292,14 @@ Finally, store the track as ``track.json`` in the tutorial directory:: ] } - -The numbers under the ``documents`` property are needed to verify integrity and provide progress reports. Determine the correct document count with ``wc -l documents.json`` and the size in bytes with ``stat -f "%z" documents.json``. - -.. note:: - - You can store any supporting scripts along with your track. However, you need to place them in a directory starting with "_", e.g. "_support". Rally loads track plugins (see below) from any directory but will ignore directories starting with "_". - .. note:: - We have defined a `JSON schema for tracks <https://github.com/elastic/rally/blob/master/esrally/resources/track-schema.json>`_ which you can use to check how to define your track. You should also check the tracks provided by Rally for inspiration. - -The new track appears when you run ``esrally list tracks --track-path=~/rally-tracks/tutorial``:: - - dm@io:~ $ esrally list tracks --track-path=~/rally-tracks/tutorial - - ____ ____ - / __ \____ _/ / /_ __ - / /_/ / __ `/ / / / / / - / _, _/ /_/ / / / /_/ / - /_/ |_|\__,_/_/_/\__, / - /____/ - Available tracks: - - Name Description Documents Compressed Size Uncompressed Size Default Challenge All Challenges - ---------- ----------------------------- ----------- --------------- ----------------- ----------------- --------------- - tutorial Tutorial benchmark for Rally 11658903 N/A 1.4 GB index-and-query index-and-query - -Congratulations, you have created your first track! You can test it with ``esrally --distribution-version=6.0.0 --track-path=~/rally-tracks/tutorial``. - -.. _add_track_test_mode: - -Adding support for test mode ----------------------------- - -You can check your track very quickly for syntax errors when you invoke Rally with ``--test-mode``. Rally postprocesses its internal track representation as follows: + If you define multiple challenges, Rally runs the challenge where ``default`` is set to ``true``. If you want to run a different challenge, provide the command line option ``--challenge=YOUR_CHALLENGE_NAME``. -* Iteration-based tasks run at most one warmup iteration and one measurement iteration. -* Time-period-based tasks run at most for 10 seconds without warmup. +When should you use challenges? Challenges are useful when you want to run completely different workloads based on the same track but for the majority of cases you should get away without using challenges: -Rally also postprocesses all data file names. Instead of ``documents.json``, Rally expects ``documents-1k.json`` and assumes the file contains 1.000 documents. You need to prepare these data files though. Pick 1.000 documents for every data file in your track and store them in a file with the suffix ``-1k``. We choose the first 1.000 with ``head -n 1000 documents.json > documents-1k.json``. +* To run only a subset of the tasks, you can use :ref:`task filtering <clr_include_tasks>`, e.g. ``--include-tasks="create-index,bulk"` will only run these two tasks in the track above. +* To vary parameters, e.g. the number of clients, you can use :ref:`track parameters <clr_track_params>` Structuring your track ---------------------- @@ -477,10 +563,6 @@ The changes are: Rally's log file contains the fully rendered track after it has loaded it successfully. -.. note:: - - If you define multiple challenges, Rally runs the challenge where ``default`` is set to ``true``. If you want to run a different challenge, provide the command line option ``--challenge=YOUR_CHALLENGE_NAME``. - You can even use `Jinja2 variables <http://jinja.pocoo.org/docs/2.9/templates/#assignments>`_ but then you need to import the Rally helpers a bit differently. You also need to declare all variables before the ``import`` statement:: {% set clients = 16 %} diff --git a/docs/command_line_reference.rst b/docs/command_line_reference.rst index 41dcd3ba..027d9d67 100644 --- a/docs/command_line_reference.rst +++ b/docs/command_line_reference.rst @@ -69,6 +69,8 @@ Selects the track repository that Rally should use to resolve tracks. By default Selects the track that Rally should run. By default the ``geonames`` track is run. For more details on how tracks work, see :doc:`adding tracks </adding_tracks>` or the :doc:`track reference </track>`. ``--track-path`` and ``--track-repository`` as well as ``--track`` are mutually exclusive. +.. _clr_track_params: + ``track-params`` ~~~~~~~~~~~~~~~~ diff --git a/docs/track.rst b/docs/track.rst index aaa93ee1..33eca156 100644 --- a/docs/track.rst +++ b/docs/track.rst @@ -112,7 +112,7 @@ A track JSON file consists of the following sections: * templates * corpora * operations -* challenges +* schedule In the ``indices`` and ``templates`` sections you define the relevant indices and index templates. These sections are optional but recommended if you want to create indices and index templates with the help of Rally. @@ -120,7 +120,7 @@ In the ``corpora`` section you define all document corpora (i.e. data files) tha In the ``operations`` section you describe which operations are available for this track and how they are parametrized. This section is optional and you can also define any operations directly per challenge. You can use it, if you want to share operation definitions between challenges. -In the ``challenge`` or ``challenges`` section you describe one or more execution schedules respectively. Each schedule either uses the operations defined in the ``operations`` block or defines the operations to execute inline. Think of a challenge as a scenario that you want to test for your data. An example challenge is to index with two clients at maximum throughput while searching with another two clients with ten operations per second. +In the ``schedule`` section you describe the workload for the benchmark, for example index with two clients at maximum throughput while searching with another two clients with ten operations per second. The schedule either uses the operations defined in the ``operations`` block or defines the operations to execute inline. Track elements ============== @@ -293,7 +293,7 @@ We can also define default values on document corpus level but override some of operations .......... -The ``operations`` section contains a list of all operations that are available later when specifying challenges. Operations define the static properties of a request against Elasticsearch whereas the ``schedule`` element defines the dynamic properties (such as the target throughput). +The ``operations`` section contains a list of all operations that are available later when specifying a schedule. Operations define the static properties of a request against Elasticsearch whereas the ``schedule`` element defines the dynamic properties (such as the target throughput). Each operation consists of the following properties: @@ -658,27 +658,10 @@ With the operation ``raw-request`` you can execute arbitrary HTTP requests again * ``request-params`` (optional): A structure containing HTTP request parameters. * ``ignore`` (optional): An array of HTTP response status codes to ignore (i.e. consider as successful). -challenge -......... - -If you track has only one challenge, you can use the ``challenge`` element. If you have multiple challenges, you can define an array of ``challenges``. - -This section contains one or more challenges which describe the benchmark scenarios for this data set. A challenge can reference all operations that are defined in the ``operations`` section. - -Each challenge consists of the following properties: - -* ``name`` (mandatory): A descriptive name of the challenge. Should not contain spaces in order to simplify handling on the command line for users. -* ``description`` (optional): A human readable description of the challenge. -* ``default`` (optional): If true, Rally selects this challenge by default if the user did not specify a challenge on the command line. If your track only defines one challenge, it is implicitly selected as default, otherwise you need define ``"default": true`` on exactly one challenge. -* ``schedule`` (mandatory): Defines the concrete execution order of operations. It is described in more detail below. - -.. note:: - You should strive to minimize the number of challenges. If you just want to run a subset of the tasks in a challenge, use :ref:`task filtering <clr_include_tasks>`. - schedule ~~~~~~~~ -The ``schedule`` element contains a list of tasks that are executed by Rally. Each task consists of the following properties: +The ``schedule`` element contains a list of tasks that are executed by Rally, i.e. it describes the workload. Each task consists of the following properties: * ``name`` (optional): This property defines an explicit name for the given task. By default the operation's name is implicitly used as the task name but if the same operation is run multiple times, a unique task name must be specified using this property. * ``operation`` (mandatory): This property refers either to the name of an operation that has been defined in the ``operations`` section or directly defines an operation inline. @@ -696,100 +679,91 @@ Defining operations In the following snippet we define two operations ``force-merge`` and a ``match-all`` query separately in an operations block:: - { - "operations": [ - { - "name": "force-merge", - "operation-type": "force-merge" - }, - { - "name": "match-all-query", - "operation-type": "search", - "body": { - "query": { - "match_all": {} - } - } - } - ], - "challenge": { - "name": "just-query", - "schedule": [ - { - "operation": "force-merge", - "clients": 1 - }, - { - "operation": "match-all-query", - "clients": 4, - "warmup-iterations": 1000, - "iterations": 1000, - "target-throughput": 100 - } - ] - } - } + { + "operations": [ + { + "name": "force-merge", + "operation-type": "force-merge" + }, + { + "name": "match-all-query", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + } + ], + "schedule": [ + { + "operation": "force-merge", + "clients": 1 + }, + { + "operation": "match-all-query", + "clients": 4, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] + } If we do not want to reuse these operations, we can also define them inline. Note that the ``operations`` section is gone:: - { - "challenge": { - "name": "just-query", - "schedule": [ - { - "operation": { - "name": "force-merge", - "operation-type": "force-merge" - }, - "clients": 1 - }, - { - "operation": { - "name": "match-all-query", - "operation-type": "search", - "body": { - "query": { - "match_all": {} - } - } - }, - "clients": 4, - "warmup-iterations": 1000, - "iterations": 1000, - "target-throughput": 100 - } - ] - } - } + { + "schedule": [ + { + "operation": { + "name": "force-merge", + "operation-type": "force-merge" + }, + "clients": 1 + }, + { + "operation": { + "name": "match-all-query", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 4, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] + } Contrary to the ``query``, the ``force-merge`` operation does not take any parameters, so Rally allows us to just specify the ``operation-type`` for this operation. It's name will be the same as the operation's type:: - { - "challenge": { - "name": "just-query", - "schedule": [ - { - "operation": "force-merge", - "clients": 1 - }, - { - "operation": { - "name": "match-all-query", - "operation-type": "search", - "body": { - "query": { - "match_all": {} - } - } - }, - "clients": 4, - "warmup-iterations": 1000, - "iterations": 1000, - "target-throughput": 100 - } - ] - } - } + { + "schedule": [ + { + "operation": "force-merge", + "clients": 1 + }, + { + "operation": { + "name": "match-all-query", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 4, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] + } Choosing a schedule ................... @@ -831,6 +805,23 @@ All tasks in the ``schedule`` list are executed sequentially in the order in whi Specify the number of clients on each task separately. If you specify this number on the ``parallel`` element instead, Rally will only use that many clients in total and you will only want to use this behavior in very rare cases (see examples)! +challenge +......... + +If your track defines only one benchmarking scenario specify the ``schedule`` on top-level. Use the ``challenge`` element if you want to specify additional properties like a name or a description. You can think of a challenge as a benchmarking scenario. If you have multiple challenges, you can define an array of ``challenges``. + +This section contains one or more challenges which describe the benchmark scenarios for this data set. A challenge can reference all operations that are defined in the ``operations`` section. + +Each challenge consists of the following properties: + +* ``name`` (mandatory): A descriptive name of the challenge. Should not contain spaces in order to simplify handling on the command line for users. +* ``description`` (optional): A human readable description of the challenge. +* ``default`` (optional): If true, Rally selects this challenge by default if the user did not specify a challenge on the command line. If your track only defines one challenge, it is implicitly selected as default, otherwise you need to define ``"default": true`` on exactly one challenge. +* ``schedule`` (mandatory): Defines the workload. It is described in more detail above. + +.. note:: + + You should strive to minimize the number of challenges. If you just want to run a subset of the tasks in a challenge, use :ref:`task filtering <clr_include_tasks>`. Examples ======== @@ -841,29 +832,26 @@ A track with a single task To get started with custom tracks, you can benchmark a single task, e.g. a match_all query:: { - "challenge": { - "name": "just-search", - "schedule": [ - { - "operation": { - "operation-type": "search", - "index": "_all", - "body": { - "query": { - "match_all": {} - } + "schedule": [ + { + "operation": { + "operation-type": "search", + "index": "_all", + "body": { + "query": { + "match_all": {} } - }, - "warmup-iterations": 100, - "iterations": 100, - "target-throughput": 10 - } - ] - } + } + }, + "warmup-iterations": 100, + "iterations": 100, + "target-throughput": 10 + } + ] } -This track assumes that you have an existing cluster with pre-populated data. It will run the provided match_all query at 10 operations per second with one client and use 100 iterations as warmup and the next 100 iterations to measure. +This track assumes that you have an existing cluster with pre-populated data. It will run the provided ``match_all`` query at 10 operations per second with one client and use 100 iterations as warmup and the next 100 iterations to measure. For the examples below, note that we do not show the operation definition but you should be able to infer from the operation name what it is doing. diff --git a/esrally/metrics.py b/esrally/metrics.py index 24dfa0e7..937f54e2 100644 --- a/esrally/metrics.py +++ b/esrally/metrics.py @@ -294,7 +294,7 @@ class MetricsStore: """ Opens a metrics store for a specific trial, track, challenge and car. - :param trial_id: The trial id. This attribute is sufficient to uniquely identify a challenge. + :param trial_id: The trial id. This attribute is sufficient to uniquely identify a race. :param trial_timestamp: The trial timestamp as a datetime. :param track_name: Track name. :param challenge_name: Challenge name. @@ -1053,7 +1053,7 @@ def list_races(cfg): races = [] for race in race_store(cfg).list(): - races.append([time.to_iso8601(race.trial_timestamp), race.track, format_dict(race.track_params), race.challenge, race.car_name, + races.append([time.to_iso8601(race.trial_timestamp), race.track, format_dict(race.track_params), race.challenge_name, race.car_name, format_dict(race.user_tags)]) if len(races) > 0: @@ -1107,7 +1107,7 @@ class Race: @property def challenge_name(self): - return str(self.challenge) + return str(self.challenge) if self.challenge else None @property def car_name(self): @@ -1140,12 +1140,13 @@ class Race: "pipeline": self.pipeline, "user-tags": self.user_tags, "track": self.track_name, - "challenge": self.challenge_name, "car": self.car, "total-laps": self.total_laps, "cluster": self.cluster.as_dict(), "results": self.results.as_dict() } + if not self.challenge.auto_generated: + d["challenge"] = self.challenge_name if self.track_params: d["track-params"] = self.track_params return d @@ -1163,7 +1164,6 @@ class Race: "distribution-major-version": versions.major_version(self.cluster.distribution_version), "user-tags": self.user_tags, "track": self.track_name, - "challenge": self.challenge_name, "car": self.car_name, "node-count": len(self.cluster.nodes), # allow to logically delete records, e.g. for UI purposes when we only want to show the latest result on graphs @@ -1176,6 +1176,8 @@ class Race: if plugins: result_template["plugins"] = list(plugins) + if not self.challenge.auto_generated: + result_template["challenge"] = self.challenge_name if self.track_params: result_template["track-params"] = self.track_params @@ -1201,7 +1203,7 @@ class Race: # Don't restore a few properties like cluster because they (a) cannot be reconstructed easily without knowledge of other modules # and (b) it is not necessary for this use case. return Race(d["rally-version"], d["environment"], d["trial-id"], time.from_is8601(d["trial-timestamp"]), d["pipeline"], user_tags, - d["track"], d.get("track-params"), d["challenge"], d["car"], d["total-laps"], results=d["results"]) + d["track"], d.get("track-params"), d.get("challenge"), d["car"], d["total-laps"], results=d["results"]) class RaceStore: diff --git a/esrally/racecontrol.py b/esrally/racecontrol.py index 5971b0b6..bf76e16b 100644 --- a/esrally/racecontrol.py +++ b/esrally/racecontrol.py @@ -105,8 +105,12 @@ class BenchmarkActor(actor.RallyActor): self.metrics_store.meta_info = msg.system_meta_info cluster = msg.cluster_meta_info self.race.cluster = cluster - console.info("Racing on track [%s], challenge [%s] and car %s with version [%s].\n" - % (self.race.track_name, self.race.challenge_name, self.race.car, self.race.cluster.distribution_version)) + if self.race.challenge.auto_generated: + console.info("Racing on track [{}] and car {} with version [{}].\n" + .format(self.race.track_name, self.race.car, self.race.cluster.distribution_version)) + else: + console.info("Racing on track [{}], challenge [{}] and car {} with version [{}].\n" + .format(self.race.track_name, self.race.challenge_name, self.race.car, self.race.cluster.distribution_version)) # start running we assume that each race has at least one lap self.run() @@ -198,7 +202,7 @@ class BenchmarkActor(actor.RallyActor): self.lap_counter = LapCounter(self.race, self.metrics_store, self.cfg) self.race_store = metrics.race_store(self.cfg) self.logger.info("Asking mechanic to start the engine.") - cluster_settings = self.race.challenge.cluster_settings + cluster_settings = challenge.cluster_settings self.send(self.mechanic, mechanic.StartEngine(self.cfg, self.metrics_store.open_context, cluster_settings, msg.sources, msg.build, msg.distribution, msg.external, msg.docker)) diff --git a/esrally/reporter.py b/esrally/reporter.py index 156f0bd3..67d371bd 100644 --- a/esrally/reporter.py +++ b/esrally/reporter.py @@ -554,12 +554,14 @@ class ComparisonReporter: print_internal("") print_internal("Comparing baseline") print_internal(" Race timestamp: %s" % r1.trial_timestamp) - print_internal(" Challenge: %s" % r1.challenge_name) + if r1.challenge_name: + print_internal(" Challenge: %s" % r1.challenge_name) print_internal(" Car: %s" % r1.car_name) print_internal("") print_internal("with contender") print_internal(" Race timestamp: %s" % r2.trial_timestamp) - print_internal(" Challenge: %s" % r2.challenge_name) + if r2.challenge_name: + print_internal(" Challenge: %s" % r2.challenge_name) print_internal(" Car: %s" % r2.car_name) print_internal("") print_header("------------------------------------------------------") diff --git a/esrally/resources/track-schema.json b/esrally/resources/track-schema.json index 8e9c3829..6078f355 100644 --- a/esrally/resources/track-schema.json +++ b/esrally/resources/track-schema.json @@ -4,6 +4,160 @@ "description": "Specification of tracks for Rally", "type": "object", "definitions": { + "schedule": { + "title": "Schedule", + "type": "array", + "minItems": 1, + "description": "Defines the concrete execution order of operations.", + "items": { + "type": "object", + "properties": { + "parallel": { + "type": "object", + "description": "This element allows to define tasks that should be run in parallel. We do not support nested parallel tasks.", + "properties": { + "clients": { + "type": "integer", + "minimum": 1 + }, + "warmup-iterations": { + "type": "integer", + "minimum": 0 + }, + "iterations": { + "type": "integer", + "minimum": 1 + }, + "warmup-time-period": { + "type": "integer", + "minimum": 0, + "description": "Defines the time period in seconds to run the operation in order to warmup the benchmark candidate. The warmup time period will not be considered in the benchmark result." + }, + "time-period": { + "type": "integer", + "minimum": 1, + "description": "Defines the time period in seconds to run the operation. Note that the parameter source may be exhausted before the specified time period has elapsed." + }, + "completed-by": { + "type": "string", + "description": "The name of an operation in the 'tasks' block. When this operation is completed, the whole parallel element is considered to be completed." + }, + "tasks": { + "type": "array", + "minItems": 1, + "description": "Defines the operations that will be run in parallel", + "items": { + "type": "object", + "description": "Defines an individual operation that is executed", + "properties": { + "name": { + "type": "string", + "description": "Explicit name of the task. By default the operation's name is implicitly used as the task's name but if the same operation is run multiple times, a unique task name must be specified." + }, + "operation": { + "description": "The name of an operation that should be executed. This name must match the operation name in the 'operations' block." + }, + "meta": { + "type": "object", + "description": "Meta-information which will be added to each metrics-record of this task." + }, + "clients": { + "type": "integer", + "minimum": 1 + }, + "warmup-iterations": { + "type": "integer", + "minimum": 0, + "description": "Defines the number of times to run the operation in order to warmup the benchmark candidate. Warmup iterations will not be considered in the benchmark result." + }, + "iterations": { + "type": "integer", + "minimum": 1, + "description": "Defines the number of times to run the operation." + }, + "warmup-time-period": { + "type": "integer", + "minimum": 0, + "description": "Defines the time period in seconds to run the operation in order to warmup the benchmark candidate. The warmup time period will not be considered in the benchmark result." + }, + "time-period": { + "type": "integer", + "minimum": 1, + "description": "Defines the time period in seconds to run the operation. Note that the parameter source may be exhausted before the specified time period has elapsed." + }, + "schedule": { + "type": "string", + "description": "Defines the scheduling strategy that is used for throughput throttled operations. Out of the box, Rally supports 'deterministic' (default) and 'poisson' but you can implement your own schedules." + }, + "target-throughput": { + "type": "number", + "minimum": 0, + "description": "Defines the number of operations per second that Rally should attempt to run." + }, + "target-interval": { + "type": "number", + "minimum": 0, + "description": "Defines the number of seconds to wait between operations (inverse of target-throughput). Only one of 'target-throughput' or 'target-interval' may be defined." + } + }, + "required": [ + "operation" + ] + } + } + }, + "required": [ + "tasks" + ] + }, + "name": { + "type": "string", + "description": "Explicit name of the task. By default the operation's name is implicitly used as the task's name but if the same operation is run multiple times, a unique task name must be specified." + }, + "operation": { + "description": "The name of an operation that should be executed. This name must match the operation name in the 'operations' block." + }, + "meta": { + "type": "object", + "description": "Meta-information which will be added to each metrics-record of this task." + }, + "clients": { + "type": "integer", + "minimum": 1 + }, + "warmup-iterations": { + "type": "integer", + "minimum": 0, + "description": "Defines the number of times to run the operation in order to warmup the benchmark candidate. Warmup iterations will not be considered in the benchmark result." + }, + "iterations": { + "type": "integer", + "minimum": 1, + "description": "Defines the number of times to run the operation." + }, + "warmup-time-period": { + "type": "integer", + "minimum": 0, + "description": "Defines the time period in seconds to run the operation in order to warmup the benchmark candidate. The warmup time period will not be considered in the benchmark result." + }, + "time-period": { + "type": "integer", + "minimum": 1, + "description": "Defines the time period in seconds to run the operation. Note that the parameter source may be exhausted before the specified time period has elapsed." + }, + "target-throughput": { + "type": "number", + "minimum": 0, + "description": "Defines the number of operations per second that Rally should attempt to run." + }, + "target-interval": { + "type": "number", + "minimum": 0, + "description": "Defines the number of seconds to wait between operations (inverse of target-throughput). Only one of 'target-throughput' or 'target-interval' may be defined." + } + } + } + }, "challenge": { "title": "Challenge", "type": "object", @@ -30,157 +184,7 @@ "description": "Defines the cluster settings of the benchmark candidate." }, "schedule": { - "type": "array", - "minItems": 1, - "description": "Defines the concrete execution order of operations.", - "items": { - "type": "object", - "properties": { - "parallel": { - "type": "object", - "description": "This element allows to define tasks that should be run in parallel. We do not support nested parallel tasks.", - "properties": { - "clients": { - "type": "integer", - "minimum": 1 - }, - "warmup-iterations": { - "type": "integer", - "minimum": 0 - }, - "iterations": { - "type": "integer", - "minimum": 1 - }, - "warmup-time-period": { - "type": "integer", - "minimum": 0, - "description": "Defines the time period in seconds to run the operation in order to warmup the benchmark candidate. The warmup time period will not be considered in the benchmark result." - }, - "time-period": { - "type": "integer", - "minimum": 1, - "description": "Defines the time period in seconds to run the operation. Note that the parameter source may be exhausted before the specified time period has elapsed." - }, - "completed-by": { - "type": "string", - "description": "The name of an operation in the 'tasks' block. When this operation is completed, the whole parallel element is considered to be completed." - }, - "tasks": { - "type": "array", - "minItems": 1, - "description": "Defines the operations that will be run in parallel", - "items": { - "type": "object", - "description": "Defines an individual operation that is executed", - "properties": { - "name": { - "type": "string", - "description": "Explicit name of the task. By default the operation's name is implicitly used as the task's name but if the same operation is run multiple times, a unique task name must be specified." - }, - "operation": { - "description": "The name of an operation that should be executed. This name must match the operation name in the 'operations' block." - }, - "meta": { - "type": "object", - "description": "Meta-information which will be added to each metrics-record of this task." - }, - "clients": { - "type": "integer", - "minimum": 1 - }, - "warmup-iterations": { - "type": "integer", - "minimum": 0, - "description": "Defines the number of times to run the operation in order to warmup the benchmark candidate. Warmup iterations will not be considered in the benchmark result." - }, - "iterations": { - "type": "integer", - "minimum": 1, - "description": "Defines the number of times to run the operation." - }, - "warmup-time-period": { - "type": "integer", - "minimum": 0, - "description": "Defines the time period in seconds to run the operation in order to warmup the benchmark candidate. The warmup time period will not be considered in the benchmark result." - }, - "time-period": { - "type": "integer", - "minimum": 1, - "description": "Defines the time period in seconds to run the operation. Note that the parameter source may be exhausted before the specified time period has elapsed." - }, - "schedule": { - "type": "string", - "description": "Defines the scheduling strategy that is used for throughput throttled operations. Out of the box, Rally supports 'deterministic' (default) and 'poisson' but you can implement your own schedules." - }, - "target-throughput": { - "type": "number", - "minimum": 0, - "description": "Defines the number of operations per second that Rally should attempt to run." - }, - "target-interval": { - "type": "number", - "minimum": 0, - "description": "Defines the number of seconds to wait between operations (inverse of target-throughput). Only one of 'target-throughput' or 'target-interval' may be defined." - } - }, - "required": [ - "operation" - ] - } - } - }, - "required": [ - "tasks" - ] - }, - "name": { - "type": "string", - "description": "Explicit name of the task. By default the operation's name is implicitly used as the task's name but if the same operation is run multiple times, a unique task name must be specified." - }, - "operation": { - "description": "The name of an operation that should be executed. This name must match the operation name in the 'operations' block." - }, - "meta": { - "type": "object", - "description": "Meta-information which will be added to each metrics-record of this task." - }, - "clients": { - "type": "integer", - "minimum": 1 - }, - "warmup-iterations": { - "type": "integer", - "minimum": 0, - "description": "Defines the number of times to run the operation in order to warmup the benchmark candidate. Warmup iterations will not be considered in the benchmark result." - }, - "iterations": { - "type": "integer", - "minimum": 1, - "description": "Defines the number of times to run the operation." - }, - "warmup-time-period": { - "type": "integer", - "minimum": 0, - "description": "Defines the time period in seconds to run the operation in order to warmup the benchmark candidate. The warmup time period will not be considered in the benchmark result." - }, - "time-period": { - "type": "integer", - "minimum": 1, - "description": "Defines the time period in seconds to run the operation. Note that the parameter source may be exhausted before the specified time period has elapsed." - }, - "target-throughput": { - "type": "number", - "minimum": 0, - "description": "Defines the number of operations per second that Rally should attempt to run." - }, - "target-interval": { - "type": "number", - "minimum": 0, - "description": "Defines the number of seconds to wait between operations (inverse of target-throughput). Only one of 'target-throughput' or 'target-interval' may be defined." - } - } - } + "$ref": "#/definitions/schedule" } }, "required": [ @@ -450,6 +454,9 @@ }, "challenge": { "$ref": "#/definitions/challenge" + }, + "schedule": { + "$ref": "#/definitions/schedule" } } } diff --git a/esrally/track/loader.py b/esrally/track/loader.py index d7bed3c1..cfa25949 100644 --- a/esrally/track/loader.py +++ b/esrally/track/loader.py @@ -38,14 +38,25 @@ def tracks(cfg): def list_tracks(cfg): + available_tracks = tracks(cfg) + only_auto_generated_challenges = all(t.default_challenge.auto_generated for t in available_tracks) + + data = [] + for t in available_tracks: + line = [t.name, t.description, t.number_of_documents, convert.bytes_to_human_string(t.compressed_size_in_bytes), + convert.bytes_to_human_string(t.uncompressed_size_in_bytes)] + if not only_auto_generated_challenges: + line.append(t.default_challenge) + line.append(",".join(map(str, t.challenges))) + data.append(line) + + headers = ["Name", "Description", "Documents", "Compressed Size", "Uncompressed Size"] + if not only_auto_generated_challenges: + headers.append("Default Challenge") + headers.append("All Challenges") + console.println("Available tracks:\n") - console.println(tabulate.tabulate( - tabular_data=[ - [t.name, t.description, t.number_of_documents, convert.bytes_to_human_string(t.compressed_size_in_bytes), - convert.bytes_to_human_string(t.uncompressed_size_in_bytes), t.default_challenge, - ",".join(map(str, t.challenges))] for t in tracks(cfg) - ], - headers=["Name", "Description", "Documents", "Compressed Size", "Uncompressed Size", "Default Challenge", "All Challenges"])) + console.println(tabulate.tabulate(tabular_data=data, headers=headers)) def load_track(cfg): @@ -819,7 +830,7 @@ class TrackSpecificationReader: challenges = [] known_challenge_names = set() default_challenge = None - challenge_specs = self._get_challenge_specs(track_spec) + challenge_specs, auto_generated = self._get_challenge_specs(track_spec) number_of_challenges = len(challenge_specs) for challenge_spec in challenge_specs: name = self._r(challenge_spec, "name", error_ctx="challenges") @@ -862,6 +873,7 @@ class TrackSpecificationReader: user_info=user_info, cluster_settings=cluster_settings, default=default, + auto_generated=auto_generated, schedule=schedule) if default: default_challenge = challenge @@ -874,17 +886,27 @@ class TrackSpecificationReader: return challenges def _get_challenge_specs(self, track_spec): + schedule = self._r(track_spec, "schedule", mandatory=False) challenge = self._r(track_spec, "challenge", mandatory=False) challenges = self._r(track_spec, "challenges", mandatory=False) - if challenge is not None and challenges is not None: - self._error("'challenge' and 'challenges' are defined but only one of them is allowed.") + count_defined = len(list(filter(lambda e: e is not None, [schedule, challenge, challenges]))) + + if count_defined == 0: + self._error("You must define 'challenge', 'challenges' or 'schedule' but none is specified.") + elif count_defined > 1: + self._error("Multiple out of 'challenge', 'challenges' or 'schedule' are defined but only one of them is allowed.") elif challenge is not None: - return [challenge] + return [challenge], False elif challenges is not None: - return challenges + return challenges, False + elif schedule is not None: + return [{ + "name": "default", + "schedule": schedule + }], True else: - self._error("You must define either 'challenge' or 'challenges' but none is specified.") + raise AssertionError("Unexpected: schedule=[{}], challenge=[{}], challenges=[{}]".format(schedule, challenge, challenges)) def parse_parallel(self, ops_spec, ops, challenge_name): # use same default values as #parseTask() in case the 'parallel' element did not specify anything diff --git a/esrally/track/track.py b/esrally/track/track.py index 39b1528f..dcdbe72b 100644 --- a/esrally/track/track.py +++ b/esrally/track/track.py @@ -348,6 +348,7 @@ class Challenge: user_info=None, cluster_settings=None, default=False, + auto_generated=False, meta_data=None, schedule=None): self.name = name @@ -356,6 +357,7 @@ class Challenge: self.user_info = user_info self.cluster_settings = cluster_settings if cluster_settings else {} self.default = default + self.auto_generated = auto_generated self.schedule = schedule if schedule else [] def prepend_tasks(self, tasks): @@ -375,12 +377,12 @@ class Challenge: def __hash__(self): return hash(self.name) ^ hash(self.description) ^ hash(self.cluster_settings) ^ hash(self.default) ^ \ - hash(self.meta_data) ^ hash(self.schedule) + hash(self.auto_generated) ^ hash(self.meta_data) ^ hash(self.schedule) def __eq__(self, othr): return (isinstance(othr, type(self)) and - (self.name, self.description, self.cluster_settings, self.default, self.meta_data, self.schedule) == - (othr.name, othr.description, othr.cluster_settings, othr.default, othr.meta_data, othr.schedule)) + (self.name, self.description, self.cluster_settings, self.default, self.auto_generated, self.meta_data, self.schedule) == + (othr.name, othr.description, othr.cluster_settings, othr.default, othr.auto_generated, othr.meta_data, othr.schedule)) @unique
Allow to use Rally without knowing about challenges _Note: This is a follow-up from #455._ ### Purpose In order to make it simpler for new users, "challenges" will become optional in Rally. We will however not get rid of them because it makes sense to keep them to provide structure for more complex tracks. ### Tasks * [x] Simplify the track format so if there is only one challenge, users can specify the `schedule` element on top-level. * [x] Hide the notion of a challenge from UI output in these simple cases. * [x] State more clearly in the docs that challenges are a more advanced concept and that it is not necessary to use them when getting started.
elastic/rally
diff --git a/tests/track/loader_test.py b/tests/track/loader_test.py index 179bdbdd..e487640a 100644 --- a/tests/track/loader_test.py +++ b/tests/track/loader_test.py @@ -1074,7 +1074,7 @@ class TrackSpecificationReaderTests(TestCase): })) with self.assertRaises(loader.TrackSyntaxError) as ctx: reader("unittest", track_specification, "/mappings") - self.assertEqual("Track 'unittest' is invalid. You must define either 'challenge' or 'challenges' but none is specified.", + self.assertEqual("Track 'unittest' is invalid. You must define 'challenge', 'challenges' or 'schedule' but none is specified.", ctx.exception.args[0]) def test_parse_challenge_and_challenges_are_defined(self): @@ -1109,8 +1109,8 @@ class TrackSpecificationReaderTests(TestCase): })) with self.assertRaises(loader.TrackSyntaxError) as ctx: reader("unittest", track_specification, "/mappings") - self.assertEqual("Track 'unittest' is invalid. 'challenge' and 'challenges' are defined but only one of them is allowed.", - ctx.exception.args[0]) + self.assertEqual("Track 'unittest' is invalid. Multiple out of 'challenge', 'challenges' or 'schedule' are defined but only " + "one of them is allowed.", ctx.exception.args[0]) def test_parse_with_mixed_warmup_time_period_and_iterations(self): track_specification = { @@ -1629,6 +1629,28 @@ class TrackSpecificationReaderTests(TestCase): self.assertEqual("challenge", resulting_track.challenges[0].name) self.assertTrue(resulting_track.challenges[0].default) + def test_auto_generates_challenge_from_schedule(self): + track_specification = { + "description": "description for unit test", + "indices": [{"name": "test-index"}], + "operations": [ + { + "name": "index-append", + "operation-type": "bulk" + } + ], + "schedule": [ + { + "operation": "index-append" + } + ] + } + reader = loader.TrackSpecificationReader() + resulting_track = reader("unittest", track_specification, "/mappings") + self.assertEqual(1, len(resulting_track.challenges)) + self.assertTrue(resulting_track.challenges[0].auto_generated) + self.assertTrue(resulting_track.challenges[0].default) + def test_inline_operations(self): track_specification = { "description": "description for unit test",
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 9 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-benchmark" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 elasticsearch==6.2.0 -e git+https://github.com/elastic/rally.git@a446d872b6cadc35041d7f15ee05005fa4f7ac4b#egg=esrally importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==2.9.5 jsonschema==2.5.1 MarkupSafe==2.0.1 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==5.4.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work py-cpuinfo==3.2.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-benchmark==3.4.1 tabulate==0.8.1 thespian==3.9.2 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.22 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: rally channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - elasticsearch==6.2.0 - jinja2==2.9.5 - jsonschema==2.5.1 - markupsafe==2.0.1 - psutil==5.4.0 - py-cpuinfo==3.2.0 - pytest-benchmark==3.4.1 - tabulate==0.8.1 - thespian==3.9.2 - urllib3==1.22 prefix: /opt/conda/envs/rally
[ "tests/track/loader_test.py::TrackSpecificationReaderTests::test_auto_generates_challenge_from_schedule", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_challenge_and_challenges_are_defined", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_missing_challenge_or_challenges" ]
[]
[ "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_directory", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_directory_without_track", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_file", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_file_but_not_json", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_named_pipe", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_non_existing_path", "tests/track/loader_test.py::GitRepositoryTests::test_track_from_existing_repo", "tests/track/loader_test.py::TrackPreparationTests::test_decompresses_if_archive_available", "tests/track/loader_test.py::TrackPreparationTests::test_does_nothing_if_document_file_available", "tests/track/loader_test.py::TrackPreparationTests::test_download_document_archive_if_no_file_available", "tests/track/loader_test.py::TrackPreparationTests::test_download_document_file_if_no_file_available", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_decompresses_compressed_docs", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_does_nothing_if_no_document_files", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_error_compressed_docs_wrong_size", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_if_document_file_available", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_uncompressed_docs_wrong_size", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_if_no_url_provided_and_file_missing", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_if_no_url_provided_and_wrong_file_size", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_if_offline", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_no_test_mode_file", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_on_connection_problems", "tests/track/loader_test.py::TrackPreparationTests::test_raise_error_if_compressed_does_not_contain_expected_document_file", "tests/track/loader_test.py::TrackPreparationTests::test_raise_error_on_wrong_uncompressed_file_size", "tests/track/loader_test.py::TemplateRenderTests::test_render_simple_template", "tests/track/loader_test.py::TemplateRenderTests::test_render_template_with_external_variables", "tests/track/loader_test.py::TemplateRenderTests::test_render_template_with_globbing", "tests/track/loader_test.py::TemplateRenderTests::test_render_template_with_variables", "tests/track/loader_test.py::TrackPostProcessingTests::test_post_processes_track_spec", "tests/track/loader_test.py::TrackPathTests::test_sets_absolute_path", "tests/track/loader_test.py::TrackFilterTests::test_create_filters_from_empty_included_tasks", "tests/track/loader_test.py::TrackFilterTests::test_create_filters_from_mixed_included_tasks", "tests/track/loader_test.py::TrackFilterTests::test_filters_tasks", "tests/track/loader_test.py::TrackFilterTests::test_rejects_invalid_syntax", "tests/track/loader_test.py::TrackFilterTests::test_rejects_unknown_filter_type", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_at_least_one_default_challenge", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_can_read_track_info", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_description_is_optional", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_document_count_mandatory_if_file_present", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_exactly_one_default_challenge", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_inline_operations", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_not_more_than_one_default_challenge_possible", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_completed_by_set", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_completed_by_set_multiple_tasks_match", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_completed_by_set_no_task_matches", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_default_clients_does_not_propagate", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_default_values", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_duplicate_explicit_task_names", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_duplicate_implicit_task_names", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_unique_task_names", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_valid_track_specification", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_valid_track_specification_with_index_template", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_with_mixed_warmup_iterations_and_measurement", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_with_mixed_warmup_time_period_and_iterations", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_selects_sole_challenge_implicitly_as_default", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_supports_target_interval", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_supports_target_throughput", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_unique_challenge_names" ]
[]
Apache License 2.0
2,585
[ "esrally/reporter.py", "esrally/metrics.py", "docs/command_line_reference.rst", "esrally/track/track.py", "esrally/resources/track-schema.json", "docs/track.rst", "docs/adding_tracks.rst", "esrally/racecontrol.py", "esrally/track/loader.py" ]
[ "esrally/reporter.py", "esrally/metrics.py", "docs/command_line_reference.rst", "esrally/track/track.py", "esrally/resources/track-schema.json", "docs/track.rst", "docs/adding_tracks.rst", "esrally/racecontrol.py", "esrally/track/loader.py" ]
nipy__nipype-2597
9eaa2a32c8cb3569633a79d6f7968270453f9aed
2018-05-25 13:56:19
704b97dee7848283692bac38f04541c5af2a87b5
diff --git a/nipype/pipeline/engine/utils.py b/nipype/pipeline/engine/utils.py index 08d357ff6..0a59aac26 100644 --- a/nipype/pipeline/engine/utils.py +++ b/nipype/pipeline/engine/utils.py @@ -1054,12 +1054,14 @@ def generate_expanded_graph(graph_in): for src_id in list(old_edge_dict.keys()): # Drop the original JoinNodes; only concerned with # generated Nodes - if hasattr(node, 'joinfield'): + if hasattr(node, 'joinfield') and node.itername == src_id: continue # Patterns: # - src_id : Non-iterable node - # - src_id.[a-z]\d+ : IdentityInterface w/ iterables - # - src_id.[a-z]I.[a-z]\d+ : Non-IdentityInterface w/ iterables + # - src_id.[a-z]\d+ : + # IdentityInterface w/ iterables or nested JoinNode + # - src_id.[a-z]I.[a-z]\d+ : + # Non-IdentityInterface w/ iterables # - src_idJ\d+ : JoinNode(IdentityInterface) if re.match(src_id + r'((\.[a-z](I\.[a-z])?|J)\d+)?$', node.itername):
PR #2479 has broken my package ### Summary PR #2479 has broken my package (https://pypi.org/project/arcana/) I am not quite sure what the rationale behind the changes are so it is difficult to know how to debug or whether there is something I can change in my package. ### Actual behavior Workflow exits with error ``` File "/Users/tclose/git/ni/arcana/test/mwe/nipype_pr2479/test.py", line 71, in <module> study.data('out') File "/Users/tclose/git/ni/arcana/arcana/study/base.py", line 325, in data visit_ids=visit_ids) File "/Users/tclose/git/ni/arcana/arcana/runner/base.py", line 37, in run return workflow.run(plugin=self._plugin) File "/Users/tclose/git/ni/nipype/nipype/pipeline/engine/workflows.py", line 595, in run runner.run(execgraph, updatehash=updatehash, config=self.config) File "/Users/tclose/git/ni/nipype/nipype/pipeline/plugins/linear.py", line 44, in run node.run(updatehash=updatehash) File "/Users/tclose/git/ni/nipype/nipype/pipeline/engine/nodes.py", line 480, in run result = self._run_interface(execute=True) File "/Users/tclose/git/ni/nipype/nipype/pipeline/engine/nodes.py", line 564, in _run_interface return self._run_command(execute) File "/Users/tclose/git/ni/arcana/arcana/node.py", line 59, in _run_command result = self.nipype_cls._run_command(self, *args, **kwargs) File "/Users/tclose/git/ni/nipype/nipype/pipeline/engine/nodes.py", line 888, in _run_command self._collate_join_field_inputs() File "/Users/tclose/git/ni/nipype/nipype/pipeline/engine/nodes.py", line 898, in _collate_join_field_inputs val = self._collate_input_value(field) File "/Users/tclose/git/ni/nipype/nipype/pipeline/engine/nodes.py", line 928, in _collate_input_value for idx in range(self._next_slot_index) File "/Users/tclose/git/ni/nipype/nipype/pipeline/engine/nodes.py", line 947, in _slot_value field, index, e)) AttributeError: The join node pipeline1.pipeline1_subject_session_outputs does not have a slot field subject_session_pairsJ1 to hold the subject_session_pairs value at index 0: 'DynamicTraitedSpec' object has no attribute 'subject_session_pairsJ1' ``` ### Expected behavior The workflow runs without error ### How to replicate the behavior See script below ### Script/Workflow details I have tried to come up with a MWE that doesn't use my package but it was proving difficult. However, you can now install my package with pip `pip install arcana` and run the following ``` import os.path import shutil from nipype import config config.enable_debug_mode() import nipype # @IgnorePep8 from nipype.interfaces.utility import IdentityInterface # @IgnorePep8 from arcana.dataset import DatasetMatch, DatasetSpec # @IgnorePep8 from arcana.data_format import text_format # @IgnorePep8 from arcana.study.base import Study, StudyMetaClass # @IgnorePep8 from arcana.archive.local import LocalArchive # @IgnorePep8 from arcana.runner import LinearRunner # @IgnorePep8 BASE_ARCHIVE_DIR = os.path.join(os.path.dirname(__file__), 'archives') BASE_WORK_DIR = os.path.join(os.path.dirname(__file__), 'work') print(nipype.get_info()) print(nipype.__version__) class TestStudy(Study): __metaclass__ = StudyMetaClass add_data_specs = [ DatasetSpec('in', text_format), DatasetSpec('out', text_format, 'pipeline')] def pipeline(self, **kwargs): pipeline = self.create_pipeline( name='pipeline1', inputs=[DatasetSpec('in', text_format)], outputs=[DatasetSpec('out', text_format)], desc="A dummy pipeline used to test 'run_pipeline' method", version=1, citations=[], **kwargs) ident = pipeline.create_node(IdentityInterface(['a']), name="ident") # Connect inputs pipeline.connect_input('in', ident, 'a') # Connect outputs pipeline.connect_output('out', ident, 'a') return pipeline # Create archives shutil.rmtree(BASE_ARCHIVE_DIR, ignore_errors=True) shutil.rmtree(BASE_WORK_DIR, ignore_errors=True) os.makedirs(BASE_ARCHIVE_DIR) for sess in (['ARCHIVE1', 'SUBJECT', 'VISIT'], ['ARCHIVE2', 'SUBJECT1', 'VISIT1'], ['ARCHIVE2', 'SUBJECT1', 'VISIT2'], ['ARCHIVE2', 'SUBJECT2', 'VISIT1'], ['ARCHIVE2', 'SUBJECT2', 'VISIT2']): sess_dir = os.path.join(*([BASE_ARCHIVE_DIR] + sess)) os.makedirs(sess_dir) with open(os.path.join(sess_dir, 'in.txt'), 'w') as f: f.write('in') archive1_path = os.path.join(BASE_ARCHIVE_DIR, 'ARCHIVE1') archive2_path = os.path.join(BASE_ARCHIVE_DIR, 'ARCHIVE2') work1_path = os.path.join(BASE_WORK_DIR, 'WORK1') work2_path = os.path.join(BASE_WORK_DIR, 'WORK2') # Attempt to run with archive with 2 subjects and 2 visits study = TestStudy('two', LocalArchive(archive2_path), LinearRunner(work2_path), inputs=[DatasetMatch('in', text_format, 'in')]) # Fails here study2.data('out') print("Ran study 2") # study1 = TestStudy('one', LocalArchive(archive1_path), LinearRunner(work1_path), inputs=[DatasetMatch('in', text_format, 'in')]) study1.data('out') print("Ran study 1") ``` to reproduce the error ### Platform details: {'nibabel_version': '2.2.1', 'sys_executable': '/usr/local/opt/python@2/bin/python2.7', 'networkx_version': '1.9', 'numpy_version': '1.14.3', 'sys_platform': 'darwin', 'sys_version': '2.7.15 (default, May 1 2018, 16:44:08) \n[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)]', 'commit_source': 'repository', 'commit_hash': '5a96ea54a', 'pkg_path': '/Users/tclose/git/ni/nipype/nipype', 'nipype_version': '1.0.4-dev+g5a96ea54a', 'traits_version': '4.6.0', 'scipy_version': '1.1.0'} 1.0.4-dev+g5a96ea54a (problem arose in 1.0.1) ### Execution environment My Homebrew python 2 environment outside container
nipy/nipype
diff --git a/nipype/pipeline/engine/tests/test_join.py b/nipype/pipeline/engine/tests/test_join.py index 54ff15048..77fc0f2fd 100644 --- a/nipype/pipeline/engine/tests/test_join.py +++ b/nipype/pipeline/engine/tests/test_join.py @@ -627,3 +627,35 @@ def test_name_prefix_join(tmpdir): joinfield=['in1']) wf.connect(square, 'out', square_join, "in1") wf.run() + + +def test_join_nestediters(tmpdir): + tmpdir.chdir() + + def exponent(x, p): + return x ** p + + wf = pe.Workflow('wf', base_dir=tmpdir.strpath) + + xs = pe.Node(IdentityInterface(['x']), + iterables=[('x', [1, 2])], + name='xs') + ps = pe.Node(IdentityInterface(['p']), + iterables=[('p', [3, 4])], + name='ps') + exp = pe.Node(Function(function=exponent), name='exp') + exp_joinx = pe.JoinNode(Merge(1, ravel_inputs=True), + name='exp_joinx', + joinsource='xs', + joinfield=['in1']) + exp_joinp = pe.JoinNode(Merge(1, ravel_inputs=True), + name='exp_joinp', + joinsource='ps', + joinfield=['in1']) + wf.connect([ + (xs, exp, [('x', 'x')]), + (ps, exp, [('p', 'p')]), + (exp, exp_joinx, [('out', 'in1')]), + (exp_joinx, exp_joinp, [('out', 'in1')])]) + + wf.run()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 codecov==2.1.13 configparser==5.2.0 coverage==6.2 cycler==0.11.0 decorator==4.4.2 docutils==0.18.1 execnet==1.9.0 funcsigs==1.0.2 future==1.0.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 isodate==0.6.1 Jinja2==3.0.3 kiwisolver==1.3.1 lxml==5.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mock==5.2.0 networkx==2.5.1 nibabel==3.2.2 -e git+https://github.com/nipy/nipype.git@9eaa2a32c8cb3569633a79d6f7968270453f9aed#egg=nipype numpy==1.19.5 numpydoc==1.1.0 packaging==21.3 Pillow==8.4.0 pluggy==1.0.0 prov==1.5.0 py==1.11.0 pydot==1.4.2 pydotplus==2.0.2 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-env==0.6.2 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2025.2 rdflib==5.0.0 requests==2.27.1 scipy==1.5.4 simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 traits==6.4.1 typing_extensions==4.1.1 urllib3==1.26.20 yapf==0.32.0 zipp==3.6.0
name: nipype channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - codecov==2.1.13 - configparser==5.2.0 - coverage==6.2 - cycler==0.11.0 - decorator==4.4.2 - docutils==0.18.1 - execnet==1.9.0 - funcsigs==1.0.2 - future==1.0.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isodate==0.6.1 - jinja2==3.0.3 - kiwisolver==1.3.1 - lxml==5.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mock==5.2.0 - networkx==2.5.1 - nibabel==3.2.2 - numpy==1.19.5 - numpydoc==1.1.0 - packaging==21.3 - pillow==8.4.0 - pluggy==1.0.0 - prov==1.5.0 - py==1.11.0 - pydot==1.4.2 - pydotplus==2.0.2 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-env==0.6.2 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - rdflib==5.0.0 - requests==2.27.1 - scipy==1.5.4 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - traits==6.4.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - yapf==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/nipype
[ "nipype/pipeline/engine/tests/test_join.py::test_join_nestediters" ]
[]
[ "nipype/pipeline/engine/tests/test_join.py::test_node_joinsource", "nipype/pipeline/engine/tests/test_join.py::test_set_join_node_file_input", "nipype/pipeline/engine/tests/test_join.py::test_nested_workflow_join", "nipype/pipeline/engine/tests/test_join.py::test_name_prefix_join", "nipype/pipeline/engine/tests/test_join.py::test_identity_join_node", "nipype/pipeline/engine/tests/test_join.py::test_multiple_join_nodes", "nipype/pipeline/engine/tests/test_join.py::test_unique_join_node", "nipype/pipeline/engine/tests/test_join.py::test_join_expansion", "nipype/pipeline/engine/tests/test_join.py::test_set_join_node", "nipype/pipeline/engine/tests/test_join.py::test_multifield_join_node", "nipype/pipeline/engine/tests/test_join.py::test_synchronize_join_node", "nipype/pipeline/engine/tests/test_join.py::test_itersource_join_source_node", "nipype/pipeline/engine/tests/test_join.py::test_itersource_two_join_nodes" ]
[]
Apache License 2.0
2,586
[ "nipype/pipeline/engine/utils.py" ]
[ "nipype/pipeline/engine/utils.py" ]
dask__dask-3536
d1f00aece8a48ccafdb040208c27cc14c4b4abfa
2018-05-25 21:29:46
279fdf7a6a78a1dfaa0974598aead3e1b44f9194
diff --git a/dask/array/__init__.py b/dask/array/__init__.py index 02e13575f..804732df2 100644 --- a/dask/array/__init__.py +++ b/dask/array/__init__.py @@ -4,7 +4,7 @@ from ..utils import ignoring from .core import (Array, block, concatenate, stack, from_array, store, map_blocks, atop, to_hdf5, to_npy_stack, from_npy_stack, from_delayed, asarray, asanyarray, - broadcast_arrays, broadcast_to) + broadcast_arrays, broadcast_to, from_zarr, to_zarr) from .routines import (take, choose, argwhere, where, coarsen, insert, ravel, roll, unique, squeeze, ptp, diff, ediff1d, gradient, bincount, digitize, histogram, cov, array, diff --git a/dask/array/core.py b/dask/array/core.py index f53f63627..3ecc6d9e6 100644 --- a/dask/array/core.py +++ b/dask/array/core.py @@ -47,6 +47,7 @@ from .. import threaded, core from .. import sharedict from ..sharedict import ShareDict from .numpy_compat import _Recurser +from ..bytes.core import get_mapper, get_fs_token_paths config.update_defaults({'array': { @@ -1887,6 +1888,15 @@ class Array(DaskMethodsMixin): from .routines import nonzero return nonzero(self) + def to_zarr(self, *args, **kwargs): + """Save array to the zarr storage format + + See https://zarr.readthedocs.io for details about the format. + + See function ``to_zarr()`` for parameters. + """ + return to_zarr(self, *args, **kwargs) + def ensure_int(f): i = int(f) @@ -2189,6 +2199,128 @@ def from_array(x, chunks, name=None, lock=False, asarray=True, fancy=True, return Array(dsk, name, chunks, dtype=x.dtype) +def from_zarr(url, component=None, storage_options=None, chunks=None, **kwargs): + """Load array from the zarr storage format + + See https://zarr.readthedocs.io for details about the format. + + Parameters + ---------- + url: str or MutableMapping + Location of the data. A URL can include a protocol specifier like s3:// + for remote data. Can also be any MutableMapping instance, which should + be serializable if used in multiple processes. + component: str or None + If the location is a zarr group rather than an array, this is the + subcomponent that should be loaded, something like ``'foo/bar'``. + storage_options: dict + Any additional parameters for the storage backend (ignored for local + paths) + chunks: tuple of ints or tuples of ints + Passed to ``da.from_array``, allows setting the chunks on + initialisation, if the chunking scheme in the on-disc dataset is not + optimal for the calculations to follow. + kwargs: passed to ``zarr.Array``. + """ + import zarr + storage_options = storage_options or {} + if isinstance(url, str): + fs, fs_token, path = get_fs_token_paths( + url, 'rb', storage_options=storage_options) + assert len(path) == 1 + mapper = get_mapper(fs, path[0]) + else: + mapper = url + z = zarr.Array(mapper, read_only=True, path=component, **kwargs) + chunks = chunks if chunks is not None else z.chunks + return from_array(z, chunks, name='zarr-%s' % url) + + +def to_zarr(arr, url, component=None, storage_options=None, + overwrite=False, compute=True, return_stored=False, **kwargs): + """Save array to the zarr storage format + + See https://zarr.readthedocs.io for details about the format. + + Parameters + ---------- + arr: dask.array + Data to store + url: str or MutableMapping + Location of the data. A URL can include a protocol specifier like s3:// + for remote data. Can also be any MutableMapping instance, which should + be serializable if used in multiple processes. + component: str or None + If the location is a zarr group rather than an array, this is the + subcomponent that should be created/over-written. + storage_options: dict + Any additional parameters for the storage backend (ignored for local + paths) + overwrite: bool + If given array already exists, overwrite=False will cause an error, + where overwrite=True will replace the existing data. + compute, return_stored: see ``store()`` + kwargs: passed to the ``zarr.create()`` function, e.g., compression options + """ + import zarr + if not _check_regular_chunks(arr.chunks): + raise ValueError('Attempt to save array to zarr with irregular ' + 'chunking, please call `arr.rechunk(...)` first.') + storage_options = storage_options or {} + if isinstance(url, str): + fs, fs_token, path = get_fs_token_paths( + url, 'rb', storage_options=storage_options) + assert len(path) == 1 + mapper = get_mapper(fs, path[0]) + else: + # assume the object passed is already a mapper + mapper = url + chunks = [c[0] for c in arr.chunks] + z = zarr.create(shape=arr.shape, chunks=chunks, dtype=arr.dtype, + store=mapper, path=component, overwrite=overwrite, **kwargs) + return store(arr, z, compute=compute, return_stored=return_stored) + + +def _check_regular_chunks(chunkset): + """Check if the chunks are regular + + "Regular" in this context means that along every axis, the chunks all + have the same size, except the last one, which may be smaller + + Parameters + ---------- + chunkset: tuple of tuples of ints + From the ``.chunks`` attribute of an ``Array`` + + Returns + ------- + True if chunkset passes, else False + + Examples + -------- + >>> import dask.array as da + >>> arr = da.zeros(10, chunks=(5, )) + >>> _check_regular_chunks(arr.chunks) + True + + >>> arr = da.zeros(10, chunks=((3, 3, 3, 1), )) + >>> _check_regular_chunks(arr.chunks) + True + + >>> arr = da.zeros(10, chunks=((3, 1, 3, 3), )) + >>> _check_regular_chunks(arr.chunks) + False + """ + for chunks in chunkset: + if len(chunks) == 1: + continue + if len(set(chunks[:-1])) > 1: + return False + if chunks[-1] > chunks[0]: + return False + return True + + def from_delayed(value, shape, dtype, name=None): """ Create a dask array from a dask delayed value diff --git a/dask/array/fft.py b/dask/array/fft.py index abcd2ffaa..b1e624d62 100644 --- a/dask/array/fft.py +++ b/dask/array/fft.py @@ -168,8 +168,8 @@ def fft_wrap(fft_func, kind=None, dtype=None): _dtype = dtype if _dtype is None: - _dtype = fft_func(np.ones(len(axes) * (8,), - dtype=a.dtype)).dtype + sample = np.ones(a.ndim * (8,), dtype=a.dtype) + _dtype = fft_func(sample).dtype for each_axis in axes: if len(a.chunks[each_axis]) != 1: @@ -210,20 +210,20 @@ def fft_wrap(fft_func, kind=None, dtype=None): return func -fft = fft_wrap(np.fft.fft, dtype=np.complex_) -fft2 = fft_wrap(np.fft.fft2, dtype=np.complex_) -fftn = fft_wrap(np.fft.fftn, dtype=np.complex_) -ifft = fft_wrap(np.fft.ifft, dtype=np.complex_) -ifft2 = fft_wrap(np.fft.ifft2, dtype=np.complex_) -ifftn = fft_wrap(np.fft.ifftn, dtype=np.complex_) -rfft = fft_wrap(np.fft.rfft, dtype=np.complex_) -rfft2 = fft_wrap(np.fft.rfft2, dtype=np.complex_) -rfftn = fft_wrap(np.fft.rfftn, dtype=np.complex_) -irfft = fft_wrap(np.fft.irfft, dtype=np.float_) -irfft2 = fft_wrap(np.fft.irfft2, dtype=np.float_) -irfftn = fft_wrap(np.fft.irfftn, dtype=np.float_) -hfft = fft_wrap(np.fft.hfft, dtype=np.float_) -ihfft = fft_wrap(np.fft.ihfft, dtype=np.complex_) +fft = fft_wrap(np.fft.fft) +fft2 = fft_wrap(np.fft.fft2) +fftn = fft_wrap(np.fft.fftn) +ifft = fft_wrap(np.fft.ifft) +ifft2 = fft_wrap(np.fft.ifft2) +ifftn = fft_wrap(np.fft.ifftn) +rfft = fft_wrap(np.fft.rfft) +rfft2 = fft_wrap(np.fft.rfft2) +rfftn = fft_wrap(np.fft.rfftn) +irfft = fft_wrap(np.fft.irfft) +irfft2 = fft_wrap(np.fft.irfft2) +irfftn = fft_wrap(np.fft.irfftn) +hfft = fft_wrap(np.fft.hfft) +ihfft = fft_wrap(np.fft.ihfft) def _fftfreq_block(i, n, d): diff --git a/dask/bytes/core.py b/dask/bytes/core.py index c2f7499d9..73b0eae33 100644 --- a/dask/bytes/core.py +++ b/dask/bytes/core.py @@ -313,10 +313,30 @@ def get_fs_token_paths(urlpath, mode='rb', num=1, name_function=None, else: raise TypeError('url type not understood: %s' % urlpath) + fs.protocol = protocol return fs, fs_token, paths +def get_mapper(fs, path): + # This is not the right way to do this. + # At the very least, we should have the correct failed import messages + if fs.protocol == 'file': + from zarr.storage import DirectoryStore + return DirectoryStore(path) + elif fs.protocol == 's3': + from s3fs.mapping import S3Map + return S3Map(path, fs) + elif fs.protocol in ['gcs', 'gs']: + from gcsfs.mapping import GCSMap + return GCSMap(path, fs) + elif fs.protocol == 'hdfs': + from hdfs3.mapping import HDFSMap + return HDFSMap(fs, path) + else: + raise ValueError('No mapper for protocol "%s"' % fs.protocol) + + def open_text_files(urlpath, compression=None, mode='rt', encoding='utf8', errors='strict', **kwargs): """ Given path return dask.delayed file-like objects in text mode diff --git a/dask/dataframe/core.py b/dask/dataframe/core.py index 54f256c24..86bf3277f 100644 --- a/dask/dataframe/core.py +++ b/dask/dataframe/core.py @@ -2359,7 +2359,7 @@ class DataFrame(_Frame): elif isinstance(key, slice): return self.loc[key] - if isinstance(key, list): + if isinstance(key, (pd.Series, np.ndarray, pd.Index, list)): # error is raised from pandas meta = self._meta[_extract_meta(key)] diff --git a/docs/source/array-api.rst b/docs/source/array-api.rst index 773061acd..6c004289d 100644 --- a/docs/source/array-api.rst +++ b/docs/source/array-api.rst @@ -321,8 +321,10 @@ Create and Store Arrays from_array from_delayed from_npy_stack + from_zarr store to_hdf5 + to_zarr to_npy_stack Generalized Ufuncs diff --git a/docs/source/array-creation.rst b/docs/source/array-creation.rst index 51eb859da..fb3692683 100644 --- a/docs/source/array-creation.rst +++ b/docs/source/array-creation.rst @@ -11,6 +11,7 @@ supports Numpy-style slicing. from_array from_delayed from_npy_stack + from_zarr stack concatenate @@ -177,6 +178,7 @@ Store Dask Arrays store to_hdf5 to_npy_stack + to_zarr compute In Memory @@ -243,6 +245,36 @@ Store several arrays in one computation with the function >>> da.to_hdf5('myfile.hdf5', {'/x': x, '/y': y}) # doctest: +SKIP +Zarr +---- + +The `zarr`_ format is a chunk-wise binary array storage file format, with a good selection +of encoding and compression options. Due to each chunk being stored in a separate file, it +is ideal for parallel access in both reading and writing (for the latter, if the dask array +chunks are alligned with the target). Furthermore, storage in +:doc:`remote data services<remote_data_services>`_ such as +S3 and GCS is supported. + +.. _zarr: https://zarr.readthedocs.io + +For example, to save data to a local zarr dataset: + +.. code-block:: Python + + >>> arr.to_zarr('output.zarr') + +or to save to a particular bucket on S3: + +.. code-block:: Python + + >>> arr.to_zarr('s3://mybucket/output.zarr', storage_option={'key': 'mykey', + 'secret': 'mysecret'}) + +To retrieve those data, you would do ``da.read_zarr`` with exactly the same arguments. The +chunking of the resultant dask.Array is defined by how the files were saved, unless +otherwise specified. + + Plugins ======= diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 6bc853540..cfb948819 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -8,6 +8,9 @@ Changelog Array +++++ +- Fix ``rechunk`` with chunksize of -1 in a dict (:pr:`3469`) `Stephan Hoyer`_ +- ``einsum`` now accepts the ``split_every`` parameter (:pr:`3396`) `Guido Imperiale`_ +- Add to/read_zarr for Zarr-format datasets and arrays (:pr:`3460`) `Martin Durant`_ - Experimental addition of generalized ufunc support, ``apply_gufunc``, ``gufunc``, and ``as_gufunc`` (:pr:`#3109`) `Markus Gonser`_ Dataframe @@ -15,6 +18,7 @@ Dataframe - Add to/read_json (:pr:`3494`) `Martin Durant`_ - Adds ``index`` to unsupported arguments for ``DataFrame.rename`` method (:pr:`3522`) `James Bourbeau`_ +- Adds support to subset Dask DataFrame columns using ``numpy.ndarray``, ``pandas.Series``, and ``pandas.Index`` objects (:pr:`3536`) `James Bourbeau`_ Bag +++
Subset dask.dataframe columns with an Index I think this should be doable: ```python In [1]: import pandas as pd; import dask.dataframe as dd In [2]: df = pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}) In [3]: df[pd.Index(['C', 'A', 'B'])] Out[3]: C A B 0 5 1 3 1 6 2 4 In [4]: ddf = dd.from_pandas(df, 2) In [5]: ddf[pd.Index(['C', 'A', 'B'])] --------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) <ipython-input-5-3ae043d06f34> in <module>() ----> 1 ddf[pd.Index(['C', 'A', 'B'])] ~/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/dataframe/core.py in __getitem__(self, key) 2157 return new_dd_object(merge(self.dask, key.dask, dsk), name, 2158 self, self.divisions) -> 2159 raise NotImplementedError(key) 2160 2161 def __setitem__(self, key, value): NotImplementedError: Index(['C', 'A', 'B'], dtype='object') ``` We check for `isinstance(key, list)`. That could probably be relaxed a bit.
dask/dask
diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py index b70c506d3..973aada17 100644 --- a/dask/array/tests/test_array_core.py +++ b/dask/array/tests/test_array_core.py @@ -3328,3 +3328,81 @@ def test_normalize_chunks_nan(): with pytest.raises(ValueError) as info: normalize_chunks(((np.nan, np.nan), 'auto'), (10, 10), limit=10, dtype=np.uint8) assert "auto" in str(info.value) + + +def test_zarr_roundtrip(): + pytest.importorskip('zarr') + with tmpdir() as d: + a = da.zeros((3, 3), chunks=(1, 1)) + a.to_zarr(d) + a2 = da.from_zarr(d) + assert_eq(a, a2) + assert a2.chunks == a.chunks + + +def test_read_zarr_chunks(): + pytest.importorskip('zarr') + a = da.zeros((9, ), chunks=(3, )) + with tmpdir() as d: + a.to_zarr(d) + arr = da.from_zarr(d, chunks=(5, )) + assert arr.chunks == ((5, 4), ) + + +def test_zarr_pass_mapper(): + pytest.importorskip('zarr') + import zarr.storage + with tmpdir() as d: + mapper = zarr.storage.DirectoryStore(d) + a = da.zeros((3, 3), chunks=(1, 1)) + a.to_zarr(mapper) + a2 = da.from_zarr(mapper) + assert_eq(a, a2) + assert a2.chunks == a.chunks + + +def test_zarr_group(): + zarr = pytest.importorskip('zarr') + with tmpdir() as d: + a = da.zeros((3, 3), chunks=(1, 1)) + a.to_zarr(d, component='test') + with pytest.raises((OSError, ValueError)): + a.to_zarr(d, component='test', overwrite=False) + a.to_zarr(d, component='test', overwrite=True) + + # second time is fine, group exists + a.to_zarr(d, component='test2', overwrite=False) + a.to_zarr(d, component='nested/test', overwrite=False) + group = zarr.open_group(d, mode='r') + assert list(group) == ['nested', 'test', 'test2'] + assert 'test' in group['nested'] + + a2 = da.from_zarr(d, component='test') + assert_eq(a, a2) + assert a2.chunks == a.chunks + + [email protected]('data', [[( ), True], + [((1, ),), True], + [((1, 1, 1),), True], + [((1, ), (1, )), True], + [((2, 2, 1), ), True], + [((2, 2, 3), ), False], + [((1, 1, 1), (2, 2, 3)), False], + [((1, 2, 1), ), False] + ]) +def test_regular_chunks(data): + chunkset, expected = data + assert da.core._check_regular_chunks(chunkset) == expected + + +def test_zarr_nocompute(): + pytest.importorskip('zarr') + with tmpdir() as d: + a = da.zeros((3, 3), chunks=(1, 1)) + out = a.to_zarr(d, compute=False) + assert isinstance(out, Delayed) + dask.compute(out) + a2 = da.from_zarr(d) + assert_eq(a, a2) + assert a2.chunks == a.chunks diff --git a/dask/dataframe/tests/test_dataframe.py b/dask/dataframe/tests/test_dataframe.py index 75caaa623..b155de6c9 100644 --- a/dask/dataframe/tests/test_dataframe.py +++ b/dask/dataframe/tests/test_dataframe.py @@ -2621,6 +2621,15 @@ def test_getitem_string_subclass(): assert_eq(df[column_1], ddf[column_1]) [email protected]('col_type', [list, np.array, pd.Series, pd.Index]) +def test_getitem_column_types(col_type): + df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]}) + ddf = dd.from_pandas(df, 2) + cols = col_type(['C', 'A', 'B']) + + assert_eq(df[cols], ddf[cols]) + + def test_diff(): df = pd.DataFrame(np.random.randn(100, 5), columns=list('abcde')) ddf = dd.from_pandas(df, 5)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 8 }
0.17
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 click==8.0.4 cloudpickle==2.2.1 -e git+https://github.com/dask/dask.git@d1f00aece8a48ccafdb040208c27cc14c4b4abfa#egg=dask distributed==1.21.8 HeapDict==1.0.1 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work locket==1.0.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work msgpack==1.0.5 numpy==1.19.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 partd==1.2.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==7.0.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 python-dateutil==2.9.0.post0 pytz==2025.2 six==1.17.0 sortedcontainers==2.4.0 tblib==1.7.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work toolz==0.12.0 tornado==6.1 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zict==2.1.0 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - click==8.0.4 - cloudpickle==2.2.1 - distributed==1.21.8 - heapdict==1.0.1 - locket==1.0.0 - msgpack==1.0.5 - numpy==1.19.5 - pandas==1.1.5 - partd==1.2.0 - psutil==7.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - six==1.17.0 - sortedcontainers==2.4.0 - tblib==1.7.0 - toolz==0.12.0 - tornado==6.1 - zict==2.1.0 prefix: /opt/conda/envs/dask
[ "dask/array/tests/test_array_core.py::test_regular_chunks[data0]", "dask/array/tests/test_array_core.py::test_regular_chunks[data1]", "dask/array/tests/test_array_core.py::test_regular_chunks[data2]", "dask/array/tests/test_array_core.py::test_regular_chunks[data3]", "dask/array/tests/test_array_core.py::test_regular_chunks[data4]", "dask/array/tests/test_array_core.py::test_regular_chunks[data5]", "dask/array/tests/test_array_core.py::test_regular_chunks[data6]", "dask/array/tests/test_array_core.py::test_regular_chunks[data7]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[array]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[Series]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[Index]" ]
[ "dask/array/tests/test_array_core.py::test_field_access", "dask/array/tests/test_array_core.py::test_field_access_with_shape", "dask/array/tests/test_array_core.py::test_matmul", "dask/dataframe/tests/test_dataframe.py::test_Dataframe", "dask/dataframe/tests/test_dataframe.py::test_attributes", "dask/dataframe/tests/test_dataframe.py::test_timezone_freq[npartitions1]", "dask/dataframe/tests/test_dataframe.py::test_clip[2-5]", "dask/dataframe/tests/test_dataframe.py::test_clip[2.5-3.5]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_picklable", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_divisions", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_month", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include0-None]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[None-exclude1]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include2-exclude2]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include3-None]", "dask/dataframe/tests/test_dataframe.py::test_to_timestamp", "dask/dataframe/tests/test_dataframe.py::test_apply", "dask/dataframe/tests/test_dataframe.py::test_apply_warns", "dask/dataframe/tests/test_dataframe.py::test_apply_infer_columns", "dask/dataframe/tests/test_dataframe.py::test_info", "dask/dataframe/tests/test_dataframe.py::test_groupby_multilevel_info", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx2-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx2-False]", "dask/dataframe/tests/test_dataframe.py::test_shift", "dask/dataframe/tests/test_dataframe.py::test_shift_with_freq", "dask/dataframe/tests/test_dataframe.py::test_first_and_last[first]", "dask/dataframe/tests/test_dataframe.py::test_first_and_last[last]", "dask/dataframe/tests/test_dataframe.py::test_datetime_loc_open_slicing" ]
[ "dask/array/tests/test_array_core.py::test_getem", "dask/array/tests/test_array_core.py::test_top", "dask/array/tests/test_array_core.py::test_top_supports_broadcasting_rules", "dask/array/tests/test_array_core.py::test_top_literals", "dask/array/tests/test_array_core.py::test_atop_literals", "dask/array/tests/test_array_core.py::test_concatenate3_on_scalars", "dask/array/tests/test_array_core.py::test_chunked_dot_product", "dask/array/tests/test_array_core.py::test_chunked_transpose_plus_one", "dask/array/tests/test_array_core.py::test_broadcast_dimensions_works_with_singleton_dimensions", "dask/array/tests/test_array_core.py::test_broadcast_dimensions", "dask/array/tests/test_array_core.py::test_Array", "dask/array/tests/test_array_core.py::test_uneven_chunks", "dask/array/tests/test_array_core.py::test_numblocks_suppoorts_singleton_block_dims", "dask/array/tests/test_array_core.py::test_keys", "dask/array/tests/test_array_core.py::test_Array_computation", "dask/array/tests/test_array_core.py::test_stack", "dask/array/tests/test_array_core.py::test_short_stack", "dask/array/tests/test_array_core.py::test_stack_scalars", "dask/array/tests/test_array_core.py::test_stack_promote_type", "dask/array/tests/test_array_core.py::test_stack_rechunk", "dask/array/tests/test_array_core.py::test_concatenate", "dask/array/tests/test_array_core.py::test_concatenate_types[dtypes0]", "dask/array/tests/test_array_core.py::test_concatenate_types[dtypes1]", "dask/array/tests/test_array_core.py::test_concatenate_unknown_axes", "dask/array/tests/test_array_core.py::test_concatenate_rechunk", "dask/array/tests/test_array_core.py::test_concatenate_fixlen_strings", "dask/array/tests/test_array_core.py::test_block_simple_row_wise", "dask/array/tests/test_array_core.py::test_block_simple_column_wise", "dask/array/tests/test_array_core.py::test_block_with_1d_arrays_row_wise", "dask/array/tests/test_array_core.py::test_block_with_1d_arrays_multiple_rows", "dask/array/tests/test_array_core.py::test_block_with_1d_arrays_column_wise", "dask/array/tests/test_array_core.py::test_block_mixed_1d_and_2d", "dask/array/tests/test_array_core.py::test_block_complicated", "dask/array/tests/test_array_core.py::test_block_nested", "dask/array/tests/test_array_core.py::test_block_3d", "dask/array/tests/test_array_core.py::test_block_with_mismatched_shape", "dask/array/tests/test_array_core.py::test_block_no_lists", "dask/array/tests/test_array_core.py::test_block_invalid_nesting", "dask/array/tests/test_array_core.py::test_block_empty_lists", "dask/array/tests/test_array_core.py::test_block_tuple", "dask/array/tests/test_array_core.py::test_binops", "dask/array/tests/test_array_core.py::test_broadcast_shapes", "dask/array/tests/test_array_core.py::test_elemwise_on_scalars", "dask/array/tests/test_array_core.py::test_elemwise_with_ndarrays", "dask/array/tests/test_array_core.py::test_elemwise_differently_chunked", "dask/array/tests/test_array_core.py::test_elemwise_dtype", "dask/array/tests/test_array_core.py::test_operators", "dask/array/tests/test_array_core.py::test_operator_dtype_promotion", "dask/array/tests/test_array_core.py::test_T", "dask/array/tests/test_array_core.py::test_norm", "dask/array/tests/test_array_core.py::test_broadcast_to", "dask/array/tests/test_array_core.py::test_broadcast_to_array", "dask/array/tests/test_array_core.py::test_broadcast_to_scalar", "dask/array/tests/test_array_core.py::test_broadcast_to_chunks", "dask/array/tests/test_array_core.py::test_broadcast_arrays", "dask/array/tests/test_array_core.py::test_broadcast_operator[u_shape0-v_shape0]", "dask/array/tests/test_array_core.py::test_broadcast_operator[u_shape1-v_shape1]", "dask/array/tests/test_array_core.py::test_broadcast_operator[u_shape2-v_shape2]", "dask/array/tests/test_array_core.py::test_broadcast_operator[u_shape3-v_shape3]", "dask/array/tests/test_array_core.py::test_broadcast_operator[u_shape4-v_shape4]", "dask/array/tests/test_array_core.py::test_broadcast_operator[u_shape5-v_shape5]", "dask/array/tests/test_array_core.py::test_broadcast_operator[u_shape6-v_shape6]", "dask/array/tests/test_array_core.py::test_reshape[original_shape0-new_shape0-chunks0]", "dask/array/tests/test_array_core.py::test_reshape[original_shape1-new_shape1-5]", "dask/array/tests/test_array_core.py::test_reshape[original_shape2-new_shape2-5]", "dask/array/tests/test_array_core.py::test_reshape[original_shape3-new_shape3-12]", "dask/array/tests/test_array_core.py::test_reshape[original_shape4-new_shape4-12]", "dask/array/tests/test_array_core.py::test_reshape[original_shape5-new_shape5-chunks5]", "dask/array/tests/test_array_core.py::test_reshape[original_shape6-new_shape6-4]", "dask/array/tests/test_array_core.py::test_reshape[original_shape7-new_shape7-4]", "dask/array/tests/test_array_core.py::test_reshape[original_shape8-new_shape8-4]", "dask/array/tests/test_array_core.py::test_reshape[original_shape9-new_shape9-2]", "dask/array/tests/test_array_core.py::test_reshape[original_shape10-new_shape10-2]", "dask/array/tests/test_array_core.py::test_reshape[original_shape11-new_shape11-2]", "dask/array/tests/test_array_core.py::test_reshape[original_shape12-new_shape12-2]", "dask/array/tests/test_array_core.py::test_reshape[original_shape13-new_shape13-2]", "dask/array/tests/test_array_core.py::test_reshape[original_shape14-new_shape14-2]", "dask/array/tests/test_array_core.py::test_reshape[original_shape15-new_shape15-2]", "dask/array/tests/test_array_core.py::test_reshape[original_shape16-new_shape16-chunks16]", "dask/array/tests/test_array_core.py::test_reshape[original_shape17-new_shape17-3]", "dask/array/tests/test_array_core.py::test_reshape[original_shape18-new_shape18-4]", "dask/array/tests/test_array_core.py::test_reshape[original_shape19-new_shape19-chunks19]", "dask/array/tests/test_array_core.py::test_reshape[original_shape20-new_shape20-1]", "dask/array/tests/test_array_core.py::test_reshape[original_shape21-new_shape21-1]", "dask/array/tests/test_array_core.py::test_reshape[original_shape22-new_shape22-24]", "dask/array/tests/test_array_core.py::test_reshape[original_shape23-new_shape23-6]", "dask/array/tests/test_array_core.py::test_reshape[original_shape24-new_shape24-6]", "dask/array/tests/test_array_core.py::test_reshape[original_shape25-new_shape25-6]", "dask/array/tests/test_array_core.py::test_reshape[original_shape26-new_shape26-chunks26]", "dask/array/tests/test_array_core.py::test_reshape[original_shape27-new_shape27-chunks27]", "dask/array/tests/test_array_core.py::test_reshape[original_shape28-new_shape28-chunks28]", "dask/array/tests/test_array_core.py::test_reshape[original_shape29-new_shape29-chunks29]", "dask/array/tests/test_array_core.py::test_reshape[original_shape30-new_shape30-chunks30]", "dask/array/tests/test_array_core.py::test_reshape[original_shape31-new_shape31-chunks31]", "dask/array/tests/test_array_core.py::test_reshape[original_shape32-new_shape32-chunks32]", "dask/array/tests/test_array_core.py::test_reshape[original_shape33-new_shape33-chunks33]", "dask/array/tests/test_array_core.py::test_reshape[original_shape34-new_shape34-chunks34]", "dask/array/tests/test_array_core.py::test_reshape_exceptions", "dask/array/tests/test_array_core.py::test_reshape_splat", "dask/array/tests/test_array_core.py::test_reshape_fails_for_dask_only", "dask/array/tests/test_array_core.py::test_reshape_unknown_dimensions", "dask/array/tests/test_array_core.py::test_full", "dask/array/tests/test_array_core.py::test_map_blocks", "dask/array/tests/test_array_core.py::test_map_blocks2", "dask/array/tests/test_array_core.py::test_map_blocks_with_constants", "dask/array/tests/test_array_core.py::test_map_blocks_with_kwargs", "dask/array/tests/test_array_core.py::test_map_blocks_with_chunks", "dask/array/tests/test_array_core.py::test_map_blocks_dtype_inference", "dask/array/tests/test_array_core.py::test_from_function_requires_block_args", "dask/array/tests/test_array_core.py::test_repr", "dask/array/tests/test_array_core.py::test_slicing_with_ellipsis", "dask/array/tests/test_array_core.py::test_slicing_with_ndarray", "dask/array/tests/test_array_core.py::test_dtype", "dask/array/tests/test_array_core.py::test_blockdims_from_blockshape", "dask/array/tests/test_array_core.py::test_coerce", "dask/array/tests/test_array_core.py::test_bool", "dask/array/tests/test_array_core.py::test_store_kwargs", "dask/array/tests/test_array_core.py::test_store_delayed_target", "dask/array/tests/test_array_core.py::test_store", "dask/array/tests/test_array_core.py::test_store_regions", "dask/array/tests/test_array_core.py::test_store_compute_false", "dask/array/tests/test_array_core.py::test_store_locks", "dask/array/tests/test_array_core.py::test_store_method_return", "dask/array/tests/test_array_core.py::test_to_dask_dataframe", "dask/array/tests/test_array_core.py::test_np_array_with_zero_dimensions", "dask/array/tests/test_array_core.py::test_dtype_complex", "dask/array/tests/test_array_core.py::test_astype", "dask/array/tests/test_array_core.py::test_arithmetic", "dask/array/tests/test_array_core.py::test_elemwise_consistent_names", "dask/array/tests/test_array_core.py::test_optimize", "dask/array/tests/test_array_core.py::test_slicing_with_non_ndarrays", "dask/array/tests/test_array_core.py::test_getter", "dask/array/tests/test_array_core.py::test_size", "dask/array/tests/test_array_core.py::test_nbytes", "dask/array/tests/test_array_core.py::test_itemsize", "dask/array/tests/test_array_core.py::test_Array_normalizes_dtype", "dask/array/tests/test_array_core.py::test_from_array_with_lock", "dask/array/tests/test_array_core.py::test_from_array_tasks_always_call_getter", "dask/array/tests/test_array_core.py::test_from_array_no_asarray", "dask/array/tests/test_array_core.py::test_from_array_getitem", "dask/array/tests/test_array_core.py::test_from_array_minus_one", "dask/array/tests/test_array_core.py::test_asarray", "dask/array/tests/test_array_core.py::test_asanyarray", "dask/array/tests/test_array_core.py::test_from_func", "dask/array/tests/test_array_core.py::test_concatenate3_2", "dask/array/tests/test_array_core.py::test_map_blocks3", "dask/array/tests/test_array_core.py::test_from_array_with_missing_chunks", "dask/array/tests/test_array_core.py::test_normalize_chunks", "dask/array/tests/test_array_core.py::test_raise_on_no_chunks", "dask/array/tests/test_array_core.py::test_chunks_is_immutable", "dask/array/tests/test_array_core.py::test_raise_on_bad_kwargs", "dask/array/tests/test_array_core.py::test_long_slice", "dask/array/tests/test_array_core.py::test_ellipsis_slicing", "dask/array/tests/test_array_core.py::test_point_slicing", "dask/array/tests/test_array_core.py::test_point_slicing_with_full_slice", "dask/array/tests/test_array_core.py::test_slice_with_floats", "dask/array/tests/test_array_core.py::test_slice_with_integer_types", "dask/array/tests/test_array_core.py::test_index_with_integer_types", "dask/array/tests/test_array_core.py::test_vindex_basic", "dask/array/tests/test_array_core.py::test_vindex_nd", "dask/array/tests/test_array_core.py::test_vindex_negative", "dask/array/tests/test_array_core.py::test_vindex_errors", "dask/array/tests/test_array_core.py::test_vindex_merge", "dask/array/tests/test_array_core.py::test_empty_array", "dask/array/tests/test_array_core.py::test_memmap", "dask/array/tests/test_array_core.py::test_to_npy_stack", "dask/array/tests/test_array_core.py::test_view", "dask/array/tests/test_array_core.py::test_view_fortran", "dask/array/tests/test_array_core.py::test_map_blocks_with_changed_dimension", "dask/array/tests/test_array_core.py::test_broadcast_chunks", "dask/array/tests/test_array_core.py::test_chunks_error", "dask/array/tests/test_array_core.py::test_array_compute_forward_kwargs", "dask/array/tests/test_array_core.py::test_dont_fuse_outputs", "dask/array/tests/test_array_core.py::test_dont_dealias_outputs", "dask/array/tests/test_array_core.py::test_timedelta_op", "dask/array/tests/test_array_core.py::test_to_delayed", "dask/array/tests/test_array_core.py::test_to_delayed_optimize_graph", "dask/array/tests/test_array_core.py::test_cumulative", "dask/array/tests/test_array_core.py::test_atop_names", "dask/array/tests/test_array_core.py::test_atop_new_axes", "dask/array/tests/test_array_core.py::test_atop_kwargs", "dask/array/tests/test_array_core.py::test_atop_chunks", "dask/array/tests/test_array_core.py::test_atop_raises_on_incorrect_indices", "dask/array/tests/test_array_core.py::test_from_delayed", "dask/array/tests/test_array_core.py::test_A_property", "dask/array/tests/test_array_core.py::test_copy_mutate", "dask/array/tests/test_array_core.py::test_npartitions", "dask/array/tests/test_array_core.py::test_astype_gh1151", "dask/array/tests/test_array_core.py::test_elemwise_name", "dask/array/tests/test_array_core.py::test_map_blocks_name", "dask/array/tests/test_array_core.py::test_array_picklable", "dask/array/tests/test_array_core.py::test_from_array_raises_on_bad_chunks", "dask/array/tests/test_array_core.py::test_concatenate_axes", "dask/array/tests/test_array_core.py::test_atop_concatenate", "dask/array/tests/test_array_core.py::test_common_blockdim", "dask/array/tests/test_array_core.py::test_uneven_chunks_that_fit_neatly", "dask/array/tests/test_array_core.py::test_elemwise_uneven_chunks", "dask/array/tests/test_array_core.py::test_uneven_chunks_atop", "dask/array/tests/test_array_core.py::test_warn_bad_rechunking", "dask/array/tests/test_array_core.py::test_optimize_fuse_keys", "dask/array/tests/test_array_core.py::test_concatenate_stack_dont_warn", "dask/array/tests/test_array_core.py::test_map_blocks_delayed", "dask/array/tests/test_array_core.py::test_no_chunks", "dask/array/tests/test_array_core.py::test_no_chunks_2d", "dask/array/tests/test_array_core.py::test_no_chunks_yes_chunks", "dask/array/tests/test_array_core.py::test_raise_informative_errors_no_chunks", "dask/array/tests/test_array_core.py::test_no_chunks_slicing_2d", "dask/array/tests/test_array_core.py::test_index_array_with_array_1d", "dask/array/tests/test_array_core.py::test_index_array_with_array_2d", "dask/array/tests/test_array_core.py::test_setitem_1d", "dask/array/tests/test_array_core.py::test_setitem_2d", "dask/array/tests/test_array_core.py::test_setitem_errs", "dask/array/tests/test_array_core.py::test_zero_slice_dtypes", "dask/array/tests/test_array_core.py::test_zero_sized_array_rechunk", "dask/array/tests/test_array_core.py::test_atop_zero_shape", "dask/array/tests/test_array_core.py::test_atop_zero_shape_new_axes", "dask/array/tests/test_array_core.py::test_broadcast_against_zero_shape", "dask/array/tests/test_array_core.py::test_from_array_name", "dask/array/tests/test_array_core.py::test_concatenate_errs", "dask/array/tests/test_array_core.py::test_stack_errs", "dask/array/tests/test_array_core.py::test_atop_with_numpy_arrays", "dask/array/tests/test_array_core.py::test_elemwise_with_lists[other0-100]", "dask/array/tests/test_array_core.py::test_elemwise_with_lists[other0-6]", "dask/array/tests/test_array_core.py::test_elemwise_with_lists[other1-100]", "dask/array/tests/test_array_core.py::test_elemwise_with_lists[other1-6]", "dask/array/tests/test_array_core.py::test_elemwise_with_lists[other2-100]", "dask/array/tests/test_array_core.py::test_elemwise_with_lists[other2-6]", "dask/array/tests/test_array_core.py::test_constructor_plugin", "dask/array/tests/test_array_core.py::test_no_warnings_on_metadata", "dask/array/tests/test_array_core.py::test_delayed_array_key_hygeine", "dask/array/tests/test_array_core.py::test_empty_chunks_in_array_len", "dask/array/tests/test_array_core.py::test_meta[None]", "dask/array/tests/test_array_core.py::test_meta[dtype1]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_1d[100-10-expected0]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_1d[20-10-expected1]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_1d[20-5-expected2]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_1d[24-5-expected3]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_1d[23-5-expected4]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_1d[1000-167-expected5]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_2d[shape0-chunks0-20-expected0]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_2d[shape1-chunks1-20-expected1]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_2d[shape2-auto-10-expected2]", "dask/array/tests/test_array_core.py::test_normalize_chunks_auto_3d", "dask/array/tests/test_array_core.py::test_constructors_chunks_dict", "dask/array/tests/test_array_core.py::test_from_array_chunks_dict", "dask/array/tests/test_array_core.py::test_normalize_chunks_object_dtype[object]", "dask/array/tests/test_array_core.py::test_normalize_chunks_object_dtype[dtype1]", "dask/array/tests/test_array_core.py::test_normalize_chunks_tuples_of_tuples", "dask/array/tests/test_array_core.py::test_normalize_chunks_nan", "dask/dataframe/tests/test_dataframe.py::test_head_tail", "dask/dataframe/tests/test_dataframe.py::test_head_npartitions", "dask/dataframe/tests/test_dataframe.py::test_head_npartitions_warn", "dask/dataframe/tests/test_dataframe.py::test_index_head", "dask/dataframe/tests/test_dataframe.py::test_Series", "dask/dataframe/tests/test_dataframe.py::test_Index", "dask/dataframe/tests/test_dataframe.py::test_Scalar", "dask/dataframe/tests/test_dataframe.py::test_column_names", "dask/dataframe/tests/test_dataframe.py::test_index_names", "dask/dataframe/tests/test_dataframe.py::test_timezone_freq[1]", "dask/dataframe/tests/test_dataframe.py::test_rename_columns", "dask/dataframe/tests/test_dataframe.py::test_rename_series", "dask/dataframe/tests/test_dataframe.py::test_rename_series_method", "dask/dataframe/tests/test_dataframe.py::test_describe", "dask/dataframe/tests/test_dataframe.py::test_describe_empty", "dask/dataframe/tests/test_dataframe.py::test_cumulative", "dask/dataframe/tests/test_dataframe.py::test_dropna", "dask/dataframe/tests/test_dataframe.py::test_squeeze", "dask/dataframe/tests/test_dataframe.py::test_where_mask", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_multi_argument", "dask/dataframe/tests/test_dataframe.py::test_map_partitions", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_names", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_column_info", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_method_names", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_keeps_kwargs_readable", "dask/dataframe/tests/test_dataframe.py::test_metadata_inference_single_partition_aligned_args", "dask/dataframe/tests/test_dataframe.py::test_drop_duplicates", "dask/dataframe/tests/test_dataframe.py::test_drop_duplicates_subset", "dask/dataframe/tests/test_dataframe.py::test_get_partition", "dask/dataframe/tests/test_dataframe.py::test_ndim", "dask/dataframe/tests/test_dataframe.py::test_dtype", "dask/dataframe/tests/test_dataframe.py::test_value_counts", "dask/dataframe/tests/test_dataframe.py::test_unique", "dask/dataframe/tests/test_dataframe.py::test_isin", "dask/dataframe/tests/test_dataframe.py::test_len", "dask/dataframe/tests/test_dataframe.py::test_size", "dask/dataframe/tests/test_dataframe.py::test_nbytes", "dask/dataframe/tests/test_dataframe.py::test_quantile", "dask/dataframe/tests/test_dataframe.py::test_quantile_missing", "dask/dataframe/tests/test_dataframe.py::test_empty_quantile", "dask/dataframe/tests/test_dataframe.py::test_dataframe_quantile", "dask/dataframe/tests/test_dataframe.py::test_index", "dask/dataframe/tests/test_dataframe.py::test_assign", "dask/dataframe/tests/test_dataframe.py::test_map", "dask/dataframe/tests/test_dataframe.py::test_concat", "dask/dataframe/tests/test_dataframe.py::test_args", "dask/dataframe/tests/test_dataframe.py::test_known_divisions", "dask/dataframe/tests/test_dataframe.py::test_unknown_divisions", "dask/dataframe/tests/test_dataframe.py::test_align[inner]", "dask/dataframe/tests/test_dataframe.py::test_align[outer]", "dask/dataframe/tests/test_dataframe.py::test_align[left]", "dask/dataframe/tests/test_dataframe.py::test_align[right]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[inner]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[outer]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[left]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[right]", "dask/dataframe/tests/test_dataframe.py::test_combine", "dask/dataframe/tests/test_dataframe.py::test_combine_first", "dask/dataframe/tests/test_dataframe.py::test_random_partitions", "dask/dataframe/tests/test_dataframe.py::test_series_round", "dask/dataframe/tests/test_dataframe.py::test_repartition_divisions", "dask/dataframe/tests/test_dataframe.py::test_repartition_on_pandas_dataframe", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions_same_limits", "dask/dataframe/tests/test_dataframe.py::test_repartition_object_index", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_errors", "dask/dataframe/tests/test_dataframe.py::test_embarrassingly_parallel_operations", "dask/dataframe/tests/test_dataframe.py::test_fillna", "dask/dataframe/tests/test_dataframe.py::test_fillna_multi_dataframe", "dask/dataframe/tests/test_dataframe.py::test_ffill_bfill", "dask/dataframe/tests/test_dataframe.py::test_fillna_series_types", "dask/dataframe/tests/test_dataframe.py::test_sample", "dask/dataframe/tests/test_dataframe.py::test_sample_without_replacement", "dask/dataframe/tests/test_dataframe.py::test_datetime_accessor", "dask/dataframe/tests/test_dataframe.py::test_str_accessor", "dask/dataframe/tests/test_dataframe.py::test_empty_max", "dask/dataframe/tests/test_dataframe.py::test_deterministic_apply_concat_apply_names", "dask/dataframe/tests/test_dataframe.py::test_aca_meta_infer", "dask/dataframe/tests/test_dataframe.py::test_aca_split_every", "dask/dataframe/tests/test_dataframe.py::test_reduction_method", "dask/dataframe/tests/test_dataframe.py::test_reduction_method_split_every", "dask/dataframe/tests/test_dataframe.py::test_pipe", "dask/dataframe/tests/test_dataframe.py::test_gh_517", "dask/dataframe/tests/test_dataframe.py::test_drop_axis_1", "dask/dataframe/tests/test_dataframe.py::test_gh580", "dask/dataframe/tests/test_dataframe.py::test_rename_dict", "dask/dataframe/tests/test_dataframe.py::test_rename_function", "dask/dataframe/tests/test_dataframe.py::test_rename_index", "dask/dataframe/tests/test_dataframe.py::test_to_frame", "dask/dataframe/tests/test_dataframe.py::test_applymap", "dask/dataframe/tests/test_dataframe.py::test_abs", "dask/dataframe/tests/test_dataframe.py::test_round", "dask/dataframe/tests/test_dataframe.py::test_cov", "dask/dataframe/tests/test_dataframe.py::test_corr", "dask/dataframe/tests/test_dataframe.py::test_cov_corr_meta", "dask/dataframe/tests/test_dataframe.py::test_cov_corr_mixed", "dask/dataframe/tests/test_dataframe.py::test_autocorr", "dask/dataframe/tests/test_dataframe.py::test_index_time_properties", "dask/dataframe/tests/test_dataframe.py::test_nlargest_nsmallest", "dask/dataframe/tests/test_dataframe.py::test_reset_index", "dask/dataframe/tests/test_dataframe.py::test_dataframe_compute_forward_kwargs", "dask/dataframe/tests/test_dataframe.py::test_series_iteritems", "dask/dataframe/tests/test_dataframe.py::test_dataframe_iterrows", "dask/dataframe/tests/test_dataframe.py::test_dataframe_itertuples", "dask/dataframe/tests/test_dataframe.py::test_astype", "dask/dataframe/tests/test_dataframe.py::test_astype_categoricals", "dask/dataframe/tests/test_dataframe.py::test_astype_categoricals_known", "dask/dataframe/tests/test_dataframe.py::test_groupby_callable", "dask/dataframe/tests/test_dataframe.py::test_methods_tokenize_differently", "dask/dataframe/tests/test_dataframe.py::test_categorize_info", "dask/dataframe/tests/test_dataframe.py::test_gh_1301", "dask/dataframe/tests/test_dataframe.py::test_timeseries_sorted", "dask/dataframe/tests/test_dataframe.py::test_column_assignment", "dask/dataframe/tests/test_dataframe.py::test_columns_assignment", "dask/dataframe/tests/test_dataframe.py::test_attribute_assignment", "dask/dataframe/tests/test_dataframe.py::test_setitem_triggering_realign", "dask/dataframe/tests/test_dataframe.py::test_inplace_operators", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx0-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx0-False]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx1-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx1-False]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin_empty_partitions", "dask/dataframe/tests/test_dataframe.py::test_getitem_meta", "dask/dataframe/tests/test_dataframe.py::test_getitem_multilevel", "dask/dataframe/tests/test_dataframe.py::test_getitem_string_subclass", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[list]", "dask/dataframe/tests/test_dataframe.py::test_diff", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-20]", "dask/dataframe/tests/test_dataframe.py::test_split_out_drop_duplicates[None]", "dask/dataframe/tests/test_dataframe.py::test_split_out_drop_duplicates[2]", "dask/dataframe/tests/test_dataframe.py::test_split_out_value_counts[None]", "dask/dataframe/tests/test_dataframe.py::test_split_out_value_counts[2]", "dask/dataframe/tests/test_dataframe.py::test_values", "dask/dataframe/tests/test_dataframe.py::test_copy", "dask/dataframe/tests/test_dataframe.py::test_del", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[True-True]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[True-False]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[False-True]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[False-False]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[sum]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[mean]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[std]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[var]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[count]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[min]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[max]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[idxmin]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[idxmax]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[prod]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[all]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[sem]", "dask/dataframe/tests/test_dataframe.py::test_to_datetime", "dask/dataframe/tests/test_dataframe.py::test_to_timedelta", "dask/dataframe/tests/test_dataframe.py::test_isna[values0]", "dask/dataframe/tests/test_dataframe.py::test_isna[values1]", "dask/dataframe/tests/test_dataframe.py::test_slice_on_filtered_boundary[0]", "dask/dataframe/tests/test_dataframe.py::test_slice_on_filtered_boundary[9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_nonmonotonic", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1-None-False-False-drop0]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1-None-False-True-drop1]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3-False-False-drop2]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3-True-False-drop3]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-0.5-None-False-False-drop4]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-0.5-None-False-True-drop5]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1.5-None-False-True-drop6]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3.5-False-False-drop7]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3.5-True-False-drop8]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-2.5-False-False-drop9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index0-0-9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index1--1-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index2-None-10]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index3-None-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index4--1-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index5-None-2]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index6--2-3]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index7-None-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index8-left8-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index9-None-right9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index10-left10-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index11-None-right11]", "dask/dataframe/tests/test_dataframe.py::test_better_errors_object_reductions", "dask/dataframe/tests/test_dataframe.py::test_sample_empty_partitions", "dask/dataframe/tests/test_dataframe.py::test_coerce", "dask/dataframe/tests/test_dataframe.py::test_bool", "dask/dataframe/tests/test_dataframe.py::test_cumulative_multiple_columns", "dask/dataframe/tests/test_dataframe.py::test_map_partition_array[asarray]", "dask/dataframe/tests/test_dataframe.py::test_map_partition_array[func1]", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_operations", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_operations_errors", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_multi_dimensional", "dask/dataframe/tests/test_dataframe.py::test_meta_raises" ]
[]
BSD 3-Clause "New" or "Revised" License
2,587
[ "docs/source/array-creation.rst", "docs/source/array-api.rst", "dask/bytes/core.py", "dask/dataframe/core.py", "dask/array/fft.py", "dask/array/core.py", "dask/array/__init__.py", "docs/source/changelog.rst" ]
[ "docs/source/array-creation.rst", "docs/source/array-api.rst", "dask/bytes/core.py", "dask/dataframe/core.py", "dask/array/fft.py", "dask/array/core.py", "dask/array/__init__.py", "docs/source/changelog.rst" ]
nipy__nipype-2598
fa864aad744126437080867d07d05888332ab174
2018-05-26 01:18:40
704b97dee7848283692bac38f04541c5af2a87b5
codecov-io: # [Codecov](https://codecov.io/gh/nipy/nipype/pull/2598?src=pr&el=h1) Report > Merging [#2598](https://codecov.io/gh/nipy/nipype/pull/2598?src=pr&el=desc) into [master](https://codecov.io/gh/nipy/nipype/commit/9eaa2a32c8cb3569633a79d6f7968270453f9aed?src=pr&el=desc) will **decrease** coverage by `3.53%`. > The diff coverage is `100%`. [![Impacted file tree graph](https://codecov.io/gh/nipy/nipype/pull/2598/graphs/tree.svg?src=pr&token=Tu0EnSSGVZ&width=650&height=150)](https://codecov.io/gh/nipy/nipype/pull/2598?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #2598 +/- ## ========================================== - Coverage 67.62% 64.09% -3.54% ========================================== Files 336 334 -2 Lines 42711 42650 -61 Branches 5278 5275 -3 ========================================== - Hits 28883 27336 -1547 - Misses 13151 14278 +1127 - Partials 677 1036 +359 ``` | Flag | Coverage Δ | | |---|---|---| | #smoketests | `?` | | | #unittests | `64.09% <100%> (-1.01%)` | :arrow_down: | | [Impacted Files](https://codecov.io/gh/nipy/nipype/pull/2598?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [nipype/pipeline/plugins/multiproc.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL3BpcGVsaW5lL3BsdWdpbnMvbXVsdGlwcm9jLnB5) | `77.84% <100%> (-4.3%)` | :arrow_down: | | [nipype/interfaces/nilearn.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL2ludGVyZmFjZXMvbmlsZWFybi5weQ==) | `40% <0%> (-56.67%)` | :arrow_down: | | [nipype/utils/spm\_docs.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL3V0aWxzL3NwbV9kb2NzLnB5) | `25.92% <0%> (-44.45%)` | :arrow_down: | | [nipype/interfaces/nitime/analysis.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL2ludGVyZmFjZXMvbml0aW1lL2FuYWx5c2lzLnB5) | `43.15% <0%> (-36.85%)` | :arrow_down: | | [nipype/interfaces/freesurfer/base.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL2ludGVyZmFjZXMvZnJlZXN1cmZlci9iYXNlLnB5) | `49.59% <0%> (-30.9%)` | :arrow_down: | | [nipype/algorithms/rapidart.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL2FsZ29yaXRobXMvcmFwaWRhcnQucHk=) | `35.39% <0%> (-29.21%)` | :arrow_down: | | [nipype/interfaces/spm/base.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL2ludGVyZmFjZXMvc3BtL2Jhc2UucHk=) | `58.41% <0%> (-29.05%)` | :arrow_down: | | [nipype/utils/provenance.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL3V0aWxzL3Byb3ZlbmFuY2UucHk=) | `55.73% <0%> (-28.99%)` | :arrow_down: | | [nipype/interfaces/fsl/model.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL2ludGVyZmFjZXMvZnNsL21vZGVsLnB5) | `55.26% <0%> (-25.35%)` | :arrow_down: | | [nipype/utils/logger.py](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree#diff-bmlweXBlL3V0aWxzL2xvZ2dlci5weQ==) | `55.55% <0%> (-23.81%)` | :arrow_down: | | ... and [44 more](https://codecov.io/gh/nipy/nipype/pull/2598/diff?src=pr&el=tree-more) | | ------ [Continue to review full report at Codecov](https://codecov.io/gh/nipy/nipype/pull/2598?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/nipy/nipype/pull/2598?src=pr&el=footer). Last update [9eaa2a3...7b92109](https://codecov.io/gh/nipy/nipype/pull/2598?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments). effigies: Huh, apparently futures gets bundled with Python 2.7 in conda. Should probably still add it to the dependencies, but this looks to be passing, so far. satra: looks good to me. we should check it in a basic system python 2.7 environment and see if that requires any backports or a specific version of py2.7. effigies: Is there a reason we're using Miniconda in Travis? It supports vanilla Python installations, and I think all dependencies can be installed with `pip`. Nibabel has [URLs](https://github.com/nipy/nibabel/blob/master/.travis.yml#L20-L21) for wheels for anything that would otherwise need compilation. satra: perhaps we should switch since we can pip install all of nipype's requirements at this point. effigies: Opened a PR to test independently of these changes. Will merge into this branch if everything goes well. effigies: @oesteban Just a bump on this. If we want to have a futures-based plugin, we should decide what we're doing here.
diff --git a/nipype/info.py b/nipype/info.py index fdf0a37f3..aaa3fa45e 100644 --- a/nipype/info.py +++ b/nipype/info.py @@ -147,6 +147,7 @@ REQUIRES = [ 'pydotplus', 'pydot>=%s' % PYDOT_MIN_VERSION, 'packaging', + 'futures; python_version == "2.7"', ] if sys.version_info <= (3, 4): diff --git a/nipype/pipeline/plugins/__init__.py b/nipype/pipeline/plugins/__init__.py index 6d2467afd..e3c797a10 100644 --- a/nipype/pipeline/plugins/__init__.py +++ b/nipype/pipeline/plugins/__init__.py @@ -12,6 +12,7 @@ from .sge import SGEPlugin from .condor import CondorPlugin from .dagman import CondorDAGManPlugin from .multiproc import MultiProcPlugin +from .legacymultiproc import LegacyMultiProcPlugin from .ipython import IPythonPlugin from .somaflow import SomaFlowPlugin from .pbsgraph import PBSGraphPlugin diff --git a/nipype/pipeline/plugins/legacymultiproc.py b/nipype/pipeline/plugins/legacymultiproc.py new file mode 100644 index 000000000..a6e330f86 --- /dev/null +++ b/nipype/pipeline/plugins/legacymultiproc.py @@ -0,0 +1,382 @@ +# -*- coding: utf-8 -*- +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +"""Parallel workflow execution via multiprocessing + +Support for child processes running as non-daemons based on +http://stackoverflow.com/a/8963618/1183453 +""" +from __future__ import (print_function, division, unicode_literals, + absolute_import) + +# Import packages +import os +from multiprocessing import Process, Pool, cpu_count, pool +from traceback import format_exception +import sys +from logging import INFO +import gc + +from copy import deepcopy +import numpy as np +from ... import logging +from ...utils.profiler import get_system_total_memory_gb +from ..engine import MapNode +from .base import DistributedPluginBase + +try: + from textwrap import indent +except ImportError: + + def indent(text, prefix): + """ A textwrap.indent replacement for Python < 3.3 """ + if not prefix: + return text + splittext = text.splitlines(True) + return prefix + prefix.join(splittext) + + +# Init logger +logger = logging.getLogger('workflow') + + +# Run node +def run_node(node, updatehash, taskid): + """Function to execute node.run(), catch and log any errors and + return the result dictionary + + Parameters + ---------- + node : nipype Node instance + the node to run + updatehash : boolean + flag for updating hash + taskid : int + an identifier for this task + + Returns + ------- + result : dictionary + dictionary containing the node runtime results and stats + """ + + # Init variables + result = dict(result=None, traceback=None, taskid=taskid) + + # Try and execute the node via node.run() + try: + result['result'] = node.run(updatehash=updatehash) + except: # noqa: E722, intendedly catch all here + result['traceback'] = format_exception(*sys.exc_info()) + result['result'] = node.result + + # Return the result dictionary + return result + + +class NonDaemonProcess(Process): + """A non-daemon process to support internal multiprocessing. + """ + + def _get_daemon(self): + return False + + def _set_daemon(self, value): + pass + + daemon = property(_get_daemon, _set_daemon) + + +class NonDaemonPool(pool.Pool): + """A process pool with non-daemon processes. + """ + Process = NonDaemonProcess + + +class LegacyMultiProcPlugin(DistributedPluginBase): + """ + Execute workflow with multiprocessing, not sending more jobs at once + than the system can support. + + The plugin_args input to run can be used to control the multiprocessing + execution and defining the maximum amount of memory and threads that + should be used. When those parameters are not specified, + the number of threads and memory of the system is used. + + System consuming nodes should be tagged:: + + memory_consuming_node.mem_gb = 8 + thread_consuming_node.n_procs = 16 + + The default number of threads and memory are set at node + creation, and are 1 and 0.25GB respectively. + + Currently supported options are: + + - non_daemon : boolean flag to execute as non-daemon processes + - n_procs: maximum number of threads to be executed in parallel + - memory_gb: maximum memory (in GB) that can be used at once. + - raise_insufficient: raise error if the requested resources for + a node over the maximum `n_procs` and/or `memory_gb` + (default is ``True``). + - scheduler: sort jobs topologically (``'tsort'``, default value) + or prioritize jobs by, first, memory consumption and, second, + number of threads (``'mem_thread'`` option). + - maxtasksperchild: number of nodes to run on each process before + refreshing the worker (default: 10). + + """ + + def __init__(self, plugin_args=None): + # Init variables and instance attributes + super(LegacyMultiProcPlugin, self).__init__(plugin_args=plugin_args) + self._taskresult = {} + self._task_obj = {} + self._taskid = 0 + + # Cache current working directory and make sure we + # change to it when workers are set up + self._cwd = os.getcwd() + + # Read in options or set defaults. + non_daemon = self.plugin_args.get('non_daemon', True) + maxtasks = self.plugin_args.get('maxtasksperchild', 10) + self.processors = self.plugin_args.get('n_procs', cpu_count()) + self.memory_gb = self.plugin_args.get( + 'memory_gb', # Allocate 90% of system memory + get_system_total_memory_gb() * 0.9) + self.raise_insufficient = self.plugin_args.get('raise_insufficient', + True) + + # Instantiate different thread pools for non-daemon processes + logger.debug('[LegacyMultiProc] Starting in "%sdaemon" mode (n_procs=%d, ' + 'mem_gb=%0.2f, cwd=%s)', 'non' * int(non_daemon), + self.processors, self.memory_gb, self._cwd) + + NipypePool = NonDaemonPool if non_daemon else Pool + try: + self.pool = NipypePool( + processes=self.processors, + maxtasksperchild=maxtasks, + initializer=os.chdir, + initargs=(self._cwd,) + ) + except TypeError: + # Python < 3.2 does not have maxtasksperchild + # When maxtasksperchild is not set, initializer is not to be + # called + self.pool = NipypePool(processes=self.processors) + + self._stats = None + + def _async_callback(self, args): + # Make sure runtime is not left at a dubious working directory + os.chdir(self._cwd) + self._taskresult[args['taskid']] = args + + def _get_result(self, taskid): + return self._taskresult.get(taskid) + + def _clear_task(self, taskid): + del self._task_obj[taskid] + + def _submit_job(self, node, updatehash=False): + self._taskid += 1 + + # Don't allow streaming outputs + if getattr(node.interface, 'terminal_output', '') == 'stream': + node.interface.terminal_output = 'allatonce' + + self._task_obj[self._taskid] = self.pool.apply_async( + run_node, (node, updatehash, self._taskid), + callback=self._async_callback) + + logger.debug('[LegacyMultiProc] Submitted task %s (taskid=%d).', + node.fullname, self._taskid) + return self._taskid + + def _prerun_check(self, graph): + """Check if any node exeeds the available resources""" + tasks_mem_gb = [] + tasks_num_th = [] + for node in graph.nodes(): + tasks_mem_gb.append(node.mem_gb) + tasks_num_th.append(node.n_procs) + + if np.any(np.array(tasks_mem_gb) > self.memory_gb): + logger.warning( + 'Some nodes exceed the total amount of memory available ' + '(%0.2fGB).', self.memory_gb) + if self.raise_insufficient: + raise RuntimeError('Insufficient resources available for job') + + if np.any(np.array(tasks_num_th) > self.processors): + logger.warning( + 'Some nodes demand for more threads than available (%d).', + self.processors) + if self.raise_insufficient: + raise RuntimeError('Insufficient resources available for job') + + def _postrun_check(self): + self.pool.close() + + def _check_resources(self, running_tasks): + """ + Make sure there are resources available + """ + free_memory_gb = self.memory_gb + free_processors = self.processors + for _, jobid in running_tasks: + free_memory_gb -= min(self.procs[jobid].mem_gb, free_memory_gb) + free_processors -= min(self.procs[jobid].n_procs, free_processors) + + return free_memory_gb, free_processors + + def _send_procs_to_workers(self, updatehash=False, graph=None): + """ + Sends jobs to workers when system resources are available. + """ + + # Check to see if a job is available (jobs with all dependencies run) + # See https://github.com/nipy/nipype/pull/2200#discussion_r141605722 + # See also https://github.com/nipy/nipype/issues/2372 + jobids = np.flatnonzero(~self.proc_done & + (self.depidx.sum(axis=0) == 0).__array__()) + + # Check available resources by summing all threads and memory used + free_memory_gb, free_processors = self._check_resources( + self.pending_tasks) + + stats = (len(self.pending_tasks), len(jobids), free_memory_gb, + self.memory_gb, free_processors, self.processors) + if self._stats != stats: + tasks_list_msg = '' + + if logger.level <= INFO: + running_tasks = [ + ' * %s' % self.procs[jobid].fullname + for _, jobid in self.pending_tasks + ] + if running_tasks: + tasks_list_msg = '\nCurrently running:\n' + tasks_list_msg += '\n'.join(running_tasks) + tasks_list_msg = indent(tasks_list_msg, ' ' * 21) + logger.info( + '[LegacyMultiProc] Running %d tasks, and %d jobs ready. Free ' + 'memory (GB): %0.2f/%0.2f, Free processors: %d/%d.%s', + len(self.pending_tasks), len(jobids), free_memory_gb, + self.memory_gb, free_processors, self.processors, + tasks_list_msg) + self._stats = stats + + if free_memory_gb < 0.01 or free_processors == 0: + logger.debug('No resources available') + return + + if len(jobids) + len(self.pending_tasks) == 0: + logger.debug('No tasks are being run, and no jobs can ' + 'be submitted to the queue. Potential deadlock') + return + + jobids = self._sort_jobs( + jobids, scheduler=self.plugin_args.get('scheduler')) + + # Run garbage collector before potentially submitting jobs + gc.collect() + + # Submit jobs + for jobid in jobids: + # First expand mapnodes + if isinstance(self.procs[jobid], MapNode): + try: + num_subnodes = self.procs[jobid].num_subnodes() + except Exception: + traceback = format_exception(*sys.exc_info()) + self._clean_queue( + jobid, + graph, + result={ + 'result': None, + 'traceback': traceback + }) + self.proc_pending[jobid] = False + continue + if num_subnodes > 1: + submit = self._submit_mapnode(jobid) + if not submit: + continue + + # Check requirements of this job + next_job_gb = min(self.procs[jobid].mem_gb, self.memory_gb) + next_job_th = min(self.procs[jobid].n_procs, self.processors) + + # If node does not fit, skip at this moment + if next_job_th > free_processors or next_job_gb > free_memory_gb: + logger.debug('Cannot allocate job %d (%0.2fGB, %d threads).', + jobid, next_job_gb, next_job_th) + continue + + free_memory_gb -= next_job_gb + free_processors -= next_job_th + logger.debug('Allocating %s ID=%d (%0.2fGB, %d threads). Free: ' + '%0.2fGB, %d threads.', self.procs[jobid].fullname, + jobid, next_job_gb, next_job_th, free_memory_gb, + free_processors) + + # change job status in appropriate queues + self.proc_done[jobid] = True + self.proc_pending[jobid] = True + + # If cached and up-to-date just retrieve it, don't run + if self._local_hash_check(jobid, graph): + continue + + # updatehash and run_without_submitting are also run locally + if updatehash or self.procs[jobid].run_without_submitting: + logger.debug('Running node %s on master thread', + self.procs[jobid]) + try: + self.procs[jobid].run(updatehash=updatehash) + except Exception: + traceback = format_exception(*sys.exc_info()) + self._clean_queue( + jobid, + graph, + result={ + 'result': None, + 'traceback': traceback + }) + + # Release resources + self._task_finished_cb(jobid) + self._remove_node_dirs() + free_memory_gb += next_job_gb + free_processors += next_job_th + # Display stats next loop + self._stats = None + + # Clean up any debris from running node in main process + gc.collect() + continue + + # Task should be submitted to workers + # Send job to task manager and add to pending tasks + if self._status_callback: + self._status_callback(self.procs[jobid], 'start') + tid = self._submit_job( + deepcopy(self.procs[jobid]), updatehash=updatehash) + if tid is None: + self.proc_done[jobid] = False + self.proc_pending[jobid] = False + else: + self.pending_tasks.insert(0, (tid, jobid)) + # Display stats next loop + self._stats = None + + def _sort_jobs(self, jobids, scheduler='tsort'): + if scheduler == 'mem_thread': + return sorted( + jobids, + key=lambda item: (self.procs[item].mem_gb, self.procs[item].n_procs) + ) + return jobids diff --git a/nipype/pipeline/plugins/multiproc.py b/nipype/pipeline/plugins/multiproc.py index c54d268ff..c52b802c4 100644 --- a/nipype/pipeline/plugins/multiproc.py +++ b/nipype/pipeline/plugins/multiproc.py @@ -11,7 +11,8 @@ from __future__ import (print_function, division, unicode_literals, # Import packages import os -from multiprocessing import Process, Pool, cpu_count, pool +from multiprocessing import cpu_count +from concurrent.futures import ProcessPoolExecutor from traceback import format_exception import sys from logging import INFO @@ -74,25 +75,6 @@ def run_node(node, updatehash, taskid): return result -class NonDaemonProcess(Process): - """A non-daemon process to support internal multiprocessing. - """ - - def _get_daemon(self): - return False - - def _set_daemon(self, value): - pass - - daemon = property(_get_daemon, _set_daemon) - - -class NonDaemonPool(pool.Pool): - """A process pool with non-daemon processes. - """ - Process = NonDaemonProcess - - class MultiProcPlugin(DistributedPluginBase): """ Execute workflow with multiprocessing, not sending more jobs at once @@ -139,8 +121,6 @@ class MultiProcPlugin(DistributedPluginBase): self._cwd = os.getcwd() # Read in options or set defaults. - non_daemon = self.plugin_args.get('non_daemon', True) - maxtasks = self.plugin_args.get('maxtasksperchild', 10) self.processors = self.plugin_args.get('n_procs', cpu_count()) self.memory_gb = self.plugin_args.get( 'memory_gb', # Allocate 90% of system memory @@ -149,30 +129,19 @@ class MultiProcPlugin(DistributedPluginBase): True) # Instantiate different thread pools for non-daemon processes - logger.debug('[MultiProc] Starting in "%sdaemon" mode (n_procs=%d, ' - 'mem_gb=%0.2f, cwd=%s)', 'non' * int(non_daemon), + logger.debug('[MultiProc] Starting (n_procs=%d, ' + 'mem_gb=%0.2f, cwd=%s)', self.processors, self.memory_gb, self._cwd) - NipypePool = NonDaemonPool if non_daemon else Pool - try: - self.pool = NipypePool( - processes=self.processors, - maxtasksperchild=maxtasks, - initializer=os.chdir, - initargs=(self._cwd,) - ) - except TypeError: - # Python < 3.2 does not have maxtasksperchild - # When maxtasksperchild is not set, initializer is not to be - # called - self.pool = NipypePool(processes=self.processors) + self.pool = ProcessPoolExecutor(max_workers=self.processors) self._stats = None def _async_callback(self, args): # Make sure runtime is not left at a dubious working directory os.chdir(self._cwd) - self._taskresult[args['taskid']] = args + result = args.result() + self._taskresult[result['taskid']] = result def _get_result(self, taskid): return self._taskresult.get(taskid) @@ -187,9 +156,9 @@ class MultiProcPlugin(DistributedPluginBase): if getattr(node.interface, 'terminal_output', '') == 'stream': node.interface.terminal_output = 'allatonce' - self._task_obj[self._taskid] = self.pool.apply_async( - run_node, (node, updatehash, self._taskid), - callback=self._async_callback) + result_future = self.pool.submit(run_node, node, updatehash, self._taskid) + result_future.add_done_callback(self._async_callback) + self._task_obj[self._taskid] = result_future logger.debug('[MultiProc] Submitted task %s (taskid=%d).', node.fullname, self._taskid) @@ -218,7 +187,7 @@ class MultiProcPlugin(DistributedPluginBase): raise RuntimeError('Insufficient resources available for job') def _postrun_check(self): - self.pool.close() + self.pool.shutdown() def _check_resources(self, running_tasks): """
MultiProc goes into infinite loop (resource management related) ### Actual behavior In particular occasions MultiProc claims a job is running, but actually goes into an infinite loop and never finishes. ### Expected behavior. Tasks should either run and finish or an exception should be raised if there aren't enough resources to run the task. ### How to replicate the behavior Run MRIQC 0.10.4 on https://openneuro.org/datasets/ds001338/versions/00001 with docker being allocated 7GB of RAM and 2 CPUs Full command to use ``` mriqc //d/data/ParanoiaStory_20180421_154028/ParanoiaStory/ //d/scratch/mriqc_out participant --participant_label tb3858 --n_procs 2 --verbose ```
nipy/nipype
diff --git a/nipype/pipeline/plugins/tests/test_multiproc_nondaemon.py b/nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py similarity index 97% rename from nipype/pipeline/plugins/tests/test_multiproc_nondaemon.py rename to nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py index ee5f0bd6f..a83d426ad 100644 --- a/nipype/pipeline/plugins/tests/test_multiproc_nondaemon.py +++ b/nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py @@ -122,11 +122,11 @@ def run_multiproc_nondaemon_with_flag(nondaemon_flag): pipe.config['execution']['stop_on_first_crash'] = True - # execute the pipe using the MultiProc plugin with 2 processes and the + # execute the pipe using the LegacyMultiProc plugin with 2 processes and the # non_daemon flag to enable child processes which start other # multiprocessing jobs execgraph = pipe.run( - plugin="MultiProc", + plugin="LegacyMultiProc", plugin_args={ 'n_procs': 2, 'non_daemon': nondaemon_flag
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 3 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 codecov==2.1.13 configparser==5.2.0 coverage==6.2 cycler==0.11.0 decorator==4.4.2 docutils==0.18.1 execnet==1.9.0 funcsigs==1.0.2 future==1.0.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 isodate==0.6.1 Jinja2==3.0.3 kiwisolver==1.3.1 lxml==5.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mock==5.2.0 networkx==2.5.1 nibabel==3.2.2 -e git+https://github.com/nipy/nipype.git@fa864aad744126437080867d07d05888332ab174#egg=nipype numpy==1.19.5 numpydoc==1.1.0 packaging==21.3 Pillow==8.4.0 pluggy==1.0.0 prov==1.5.0 py==1.11.0 pydot==1.4.2 pydotplus==2.0.2 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-env==0.6.2 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2025.2 rdflib==5.0.0 requests==2.27.1 scipy==1.5.4 simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 traits==6.4.1 typing_extensions==4.1.1 urllib3==1.26.20 yapf==0.32.0 zipp==3.6.0
name: nipype channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - codecov==2.1.13 - configparser==5.2.0 - coverage==6.2 - cycler==0.11.0 - decorator==4.4.2 - docutils==0.18.1 - execnet==1.9.0 - funcsigs==1.0.2 - future==1.0.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isodate==0.6.1 - jinja2==3.0.3 - kiwisolver==1.3.1 - lxml==5.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mock==5.2.0 - networkx==2.5.1 - nibabel==3.2.2 - numpy==1.19.5 - numpydoc==1.1.0 - packaging==21.3 - pillow==8.4.0 - pluggy==1.0.0 - prov==1.5.0 - py==1.11.0 - pydot==1.4.2 - pydotplus==2.0.2 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-env==0.6.2 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - rdflib==5.0.0 - requests==2.27.1 - scipy==1.5.4 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - traits==6.4.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - yapf==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/nipype
[ "nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py::test_run_multiproc_nondaemon_true" ]
[]
[ "nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py::test_run_multiproc_nondaemon_false" ]
[]
Apache License 2.0
2,588
[ "nipype/pipeline/plugins/multiproc.py", "nipype/info.py", "nipype/pipeline/plugins/legacymultiproc.py", "nipype/pipeline/plugins/__init__.py" ]
[ "nipype/pipeline/plugins/multiproc.py", "nipype/info.py", "nipype/pipeline/plugins/legacymultiproc.py", "nipype/pipeline/plugins/__init__.py" ]
jamescooke__flake8-aaa-12
15695f30ea8e2f80f92026468569ed00c6d031dc
2018-05-26 11:56:27
47893db2a642dc33d937e71f661de792a6ce4021
diff --git a/flake8_aaa/act_block.py b/flake8_aaa/act_block.py index 51cd753..a49d5a4 100644 --- a/flake8_aaa/act_block.py +++ b/flake8_aaa/act_block.py @@ -23,11 +23,10 @@ class ActBlock: self.block_type = block_type @classmethod - def build(obj, node, tokens): + def build(obj, node): """ Args: - node (astroid.*): An astroid node. - tokens (asttokens.ASTTokens): Tokens that contain this node. + node (ast.node): A node, decorated with ``ASTTokens``. Returns: ActBlock @@ -41,8 +40,7 @@ class ActBlock: return obj(node, obj.PYTEST_RAISES) # Check if line marked with '# act' - line = next(tokens.get_tokens(node, include_extra=True)).line - if line.strip().lower().endswith('# act'): + if node.first_token.line.strip().endswith('# act'): return obj(node, obj.MARKED_ACT) raise NotActionBlock() diff --git a/flake8_aaa/checker.py b/flake8_aaa/checker.py index cc548c5..1a704f7 100644 --- a/flake8_aaa/checker.py +++ b/flake8_aaa/checker.py @@ -1,4 +1,3 @@ -import astroid import asttokens from .__about__ import __short_name__, __version__ @@ -11,28 +10,27 @@ class Checker: Attributes: ast_tokens (asttokens.ASTTokens): Tokens for the file. filename (str): Name of file under check. - tree (astroid.Module): Astroid tree loaded from file. + lines (list (str)) + tree (ast.Module): Tree passed from flake8. """ name = __short_name__ version = __version__ - def __init__(self, tree, filename): + def __init__(self, tree, lines, filename): """ Args: - tree: Ignored, but is required for flake8 to recognise this as a - plugin. + tree + lines (list (str)) filename (str) """ + self.tree = tree + self.lines = lines self.filename = filename - self.tree = None self.ast_tokens = None def load(self): - with open(self.filename) as f: - file_contents = f.read() - self.tree = astroid.parse(file_contents) - self.ast_tokens = asttokens.ASTTokens(file_contents, tree=self.tree) + self.ast_tokens = asttokens.ASTTokens(''.join(self.lines), tree=self.tree) def run(self): """ @@ -41,7 +39,7 @@ class Checker: if is_test_file(self.filename): self.load() for function_def in find_test_functions(self.tree): - function = Function(function_def, self.ast_tokens) + function = Function(function_def) function.parse() for error in function.check(): yield error + (type(self), ) diff --git a/flake8_aaa/function.py b/flake8_aaa/function.py index 6ce9281..e353135 100644 --- a/flake8_aaa/function.py +++ b/flake8_aaa/function.py @@ -9,21 +9,18 @@ class Function: act_blocks (list (ActBlock)): List of nodes that are considered Act blocks for this test. Defaults to ``None`` when function has not been parsed. - node (astroid.FunctionDef): AST for the test under lint. - tokens (asttokens.ASTTokens): Tokens for the file under test. + node (ast.FunctionDef): AST for the test under lint. is_noop (bool): Function is considered empty. Consists just of comments or ``pass``. parsed (bool): Function's nodes have been parsed. """ - def __init__(self, node, tokens): + def __init__(self, node): """ Args: node (ast.FunctionDef) - tokens (asttokens.ASTTokens) """ self.node = node - self.tokens = tokens self.act_blocks = [] self.is_noop = False self.parsed = False @@ -43,9 +40,9 @@ class Function: self.is_noop = True return 0 - for child_node in self.node.get_children(): + for child_node in self.node.body: try: - self.act_blocks.append(ActBlock.build(child_node, self.tokens)) + self.act_blocks.append(ActBlock.build(child_node)) except NotActionBlock: continue diff --git a/flake8_aaa/helpers.py b/flake8_aaa/helpers.py index 1e3309e..c0e7b63 100644 --- a/flake8_aaa/helpers.py +++ b/flake8_aaa/helpers.py @@ -1,7 +1,6 @@ +import ast import os -import astroid - def is_test_file(filename): """ @@ -27,58 +26,82 @@ def is_test_file(filename): return os.path.basename(filename).startswith('test_') +class TestFuncLister(ast.NodeVisitor): + """ + Helper to walk the ast Tree and find functions that looks like tests. + Matching function nodes are kept in ``_found_func`` attr. + + Attributes: + _found_func (list (ast.node)) + """ + + def __init__(self, *args, **kwargs): + super(TestFuncLister, self).__init__(*args, **kwargs) + self._found_funcs = [] + + def visit_FunctionDef(self, node): + if node.name.startswith('test'): + self._found_funcs.append(node) + + def find_test_functions(tree): """ Args: - tree (astroid.Module) + tree (ast.Module) Returns: - list (astroid.FunctionDef): Fuctions that look like tests. + list (ast.FunctionDef): Functions that look like tests. """ - test_nodes = [] - for node in tree.get_children(): - if node.is_function and node.name.startswith('test'): - test_nodes.append(node) - return test_nodes + function_finder = TestFuncLister() + function_finder.visit(tree) + return function_finder._found_funcs def node_is_result_assignment(node): """ Args: - node: An ``astroid`` node. + node: An ``ast`` node. Returns: bool: ``node`` corresponds to the code ``result =``, assignment to the ``result `` variable. + + Note: + Performs a very weak test that the line starts with 'result =' rather + than testing the tokens. """ - return ( - isinstance(node, astroid.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], astroid.AssignName) - and node.targets[0].name == 'result' - ) + return node.first_token.line.strip().startswith('result =') def node_is_pytest_raises(node): """ Args: - node: An ``astroid`` node. + node: An ``ast`` node, augmented with ASTTokens Returns: bool: ``node`` corresponds to a With node where the context manager is ``pytest.raises``. """ - if (isinstance(node, astroid.With)): - child = next(node.get_children()) - if child.as_string().startswith('pytest.raises'): - return True - return False + return isinstance(node, ast.With) and node.first_token.line.strip().startswith('with pytest.raises') + + +def node_is_noop(node): + """ + Args: + node (ast.node) + + Returns: + bool: Node does nothing. + """ + return (type(node) is ast.Expr and type(node.value) is ast.Str) or (type(node) is ast.Pass) def function_is_noop(function_node): """ Args: - function_node (astroid.FunctionDef): A function. + function_node (ast.FunctionDef): A function. Returns: bool: Function does nothing - is just ``pass`` or docstring. """ - return all(type(node) is astroid.Pass for node in function_node.body) + return all(node_is_noop(n) for n in function_node.body) diff --git a/requirements/base.in b/requirements/base.in index 92fe705..e65fd57 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -1,3 +1,2 @@ -astroid>=1.6 asttokens>=1.1.10 flake8>=3 diff --git a/requirements/base.txt b/requirements/base.txt index b20300d..c02ba77 100644 --- a/requirements/base.txt +++ b/requirements/base.txt @@ -4,12 +4,9 @@ # # pip-compile --output-file base.txt base.in # -astroid==1.6.3 asttokens==1.1.10 flake8==3.5.0 -lazy-object-proxy==1.3.1 # via astroid mccabe==0.6.1 # via flake8 pycodestyle==2.3.1 # via flake8 pyflakes==1.6.0 # via flake8 -six==1.11.0 # via astroid, asttokens -wrapt==1.10.11 # via astroid +six==1.11.0 # via asttokens diff --git a/requirements/dev.txt b/requirements/dev.txt index f385fef..3e8bddd 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -4,7 +4,6 @@ # # pip-compile --output-file dev.txt dev.in # -astroid==1.6.3 asttokens==1.1.10 attrs==18.1.0 backcall==0.1.0 # via ipython @@ -21,7 +20,6 @@ ipython-genutils==0.2.0 # via traitlets ipython==6.4.0 isort==4.3.4 jedi==0.12.0 # via ipython -lazy-object-proxy==1.3.1 mccabe==0.6.1 more-itertools==4.1.0 parso==0.2.0 # via jedi @@ -50,5 +48,4 @@ twine==1.11.0 urllib3==1.22 # via requests virtualenv==15.2.0 wcwidth==0.1.7 # via prompt-toolkit -wrapt==1.10.11 yapf==0.21.0 diff --git a/setup.py b/setup.py index ecfa361..830807d 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ def readme(): about = {} with open(os.path.join(basedir, 'flake8_aaa', '__about__.py')) as f: - exec(f.read(), about) + exec(f.read(), about) # yapf: disable setup( # --- META --- @@ -31,7 +31,6 @@ setup( packages=['flake8_aaa'], py_modules=['flake8_aaa'], install_requires=[ - 'astroid >= 1.6', 'asttokens >= 1.1.10', 'flake8 >= 3', ], diff --git a/tox.ini b/tox.ini index a562e6e..aa37fc8 100644 --- a/tox.ini +++ b/tox.ini @@ -1,9 +1,11 @@ -# install = assert that plugin can be installed and run via flake8 in a clean venv +# install = assert that plugin can be installed and run via flake8 in a clean +# venv # test = run pytest -# lint = run all linting +# lint = run all linting, including on the test suite. Use both py2 and py3 to +# ensure that unicode loads OK. [tox] -envlist = py{27,36}-{install,test},py36-lint +envlist = py{27,36}-{install,test,lint} [testenv] deps = test,lint: -rrequirements/test.txt
Fails when testing unicode files When file is marked with unicode and contains unicode chars: ``` # encoding: utf-8 ``` Then loading the file fails: ``` File "/home/vagrant/pysyncgateway/venv/local/lib/python2.7/site-packages/flake8/checker.py", line 493, in run_ast_checks for (line_number, offset, text, check) in runner: File "/home/vagrant/pysyncgateway/venv/local/lib/python2.7/site-packages/flake8_aaa/checker.py", line 42, in run self.load() File "/home/vagrant/pysyncgateway/venv/local/lib/python2.7/site-packages/flake8_aaa/checker.py", line 34, in load self.tree = astroid.parse(file_contents) File "/home/vagrant/pysyncgateway/venv/local/lib/python2.7/site-packages/astroid/builder.py", line 282, in parse return builder.string_build(code, modname=module_name, path=path) File "/home/vagrant/pysyncgateway/venv/local/lib/python2.7/site-packages/astroid/builder.py", line 158, in string_build module.file_bytes = data.encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1025: ordinal not in range(128) ``` Example test file is at: https://github.com/constructpm/pysyncgateway/blob/master/tests/document/test_create_update.py
jamescooke/flake8-aaa
diff --git a/requirements/test.txt b/requirements/test.txt index df21662..3d9c456 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -4,13 +4,11 @@ # # pip-compile --output-file test.txt test.in # -astroid==1.6.3 asttokens==1.1.10 attrs==18.1.0 # via pytest docutils==0.14 # via restructuredtext-lint flake8==3.5.0 isort==4.3.4 -lazy-object-proxy==1.3.1 mccabe==0.6.1 more-itertools==4.1.0 # via pytest pluggy==0.6.0 # via pytest, tox @@ -23,5 +21,4 @@ restructuredtext-lint==1.1.3 six==1.11.0 tox==3.0.0 virtualenv==15.2.0 # via tox -wrapt==1.10.11 yapf==0.21.0 diff --git a/tests/act_block/test_build.py b/tests/act_block/test_build.py index 6dfb9cb..d8dd526 100644 --- a/tests/act_block/test_build.py +++ b/tests/act_block/test_build.py @@ -1,10 +1,28 @@ -import astroid -import asttokens import pytest from flake8_aaa.act_block import ActBlock from flake8_aaa.exceptions import NotActionBlock +# TODO act blocks need testing with 'result =' indented +# TODO act blocks need testing with indentation in general + + [email protected]( + 'code_str', [ + """ +def test_not_actions(first_node_with_tokens): + with pytest.raises(NotActionBlock): + ActBlock.build(first_node_with_tokens) +""" + ] +) +def test_raises_block(first_node_with_tokens): + result = ActBlock.build(first_node_with_tokens.body[0]) + + assert isinstance(result, ActBlock) + assert result.node == first_node_with_tokens.body[0] + assert result.block_type == ActBlock.PYTEST_RAISES + @pytest.mark.parametrize( 'code_str, expected_type', [ @@ -13,14 +31,11 @@ from flake8_aaa.exceptions import NotActionBlock ('data[new_key] = value # act', ActBlock.MARKED_ACT), ] ) -def test(code_str, expected_type): - node = astroid.extract_node(code_str) - tokens = asttokens.ASTTokens(code_str, tree=node) - - result = ActBlock.build(node, tokens) +def test(expected_type, first_node_with_tokens): + result = ActBlock.build(first_node_with_tokens) assert isinstance(result, ActBlock) - assert result.node == node + assert result.node == first_node_with_tokens assert result.block_type == expected_type @@ -34,9 +49,6 @@ def test(code_str, expected_type): 'with open("data.txt") as f:\n f.read()', ] ) -def test_not_actions(code_str): - node = astroid.extract_node(code_str) - tokens = asttokens.ASTTokens(code_str, tree=node) - +def test_not_actions(first_node_with_tokens): with pytest.raises(NotActionBlock): - ActBlock.build(node, tokens) + ActBlock.build(first_node_with_tokens) diff --git a/tests/checker/test_init.py b/tests/checker/test_init.py index b091b9c..efc8e91 100644 --- a/tests/checker/test_init.py +++ b/tests/checker/test_init.py @@ -2,8 +2,9 @@ from flake8_aaa import Checker def test(): - result = Checker(None, '__FILENAME__') + result = Checker(None, [], '__FILENAME__') - assert result.filename == '__FILENAME__' assert result.tree is None + assert result.lines == [] + assert result.filename == '__FILENAME__' assert result.ast_tokens is None diff --git a/tests/checker/test_load.py b/tests/checker/test_load.py index 3f0962e..2ff2734 100644 --- a/tests/checker/test_load.py +++ b/tests/checker/test_load.py @@ -1,16 +1,17 @@ -import astroid +import ast from flake8_aaa import Checker def test(tmpdir): target_file = tmpdir.join('test.py') - target_file.write('assert 1 + 2 == 3') - checker = Checker(None, target_file.strpath) + target_file.write('assert 1 + 2 == 3\n') + tree = ast.parse(target_file.read()) + checker = Checker(tree, ['assert 1 + 2 == 3\n'], target_file.strpath) result = checker.load() assert result is None assert len(checker.tree.body) == 1 - assert type(checker.tree.body[0]) == astroid.Assert - assert len(checker.ast_tokens.tokens) == 7 + assert type(checker.tree.body[0]) == ast.Assert + assert len(checker.ast_tokens.tokens) == 8 diff --git a/tests/conftest.py b/tests/conftest.py index dd37e10..98682c2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,6 @@ +import ast + +import asttokens import pytest from flake8.defaults import MAX_LINE_LENGTH from flake8.processor import FileProcessor @@ -48,3 +51,17 @@ def first_token(file_tokens): First token of provided list. """ return file_tokens[0] + + [email protected] +def first_node_with_tokens(code_str): + """ + Given ``code_str`` fixture, parse that string with ``ast.parse`` and then + augment it with ``asttokens.ASTTokens``. + + Returns: + ast.node: First node in parsed tree. + """ + tree = ast.parse(code_str) + asttokens.ASTTokens(code_str, tree=tree) + return tree.body[0] diff --git a/tests/function/conftest.py b/tests/function/conftest.py index 79c5d89..3949659 100644 --- a/tests/function/conftest.py +++ b/tests/function/conftest.py @@ -1,32 +1,12 @@ -import astroid -import asttokens import pytest from flake8_aaa.function import Function @pytest.fixture -def function_node(code_str): +def function(first_node_with_tokens): """ - Args: - code_str (str): Should contain only one function which can be - extracted. - - Returns: - astroid.FunctionDef - """ - return astroid.extract_node(code_str) - - [email protected] -def function(function_node, code_str): - """ - Args: - function_node (astroid.FunctionDef) - code_str (str) - Returns: - Function + Function: Loaded with ``first_node_with_tokens`` node. """ - tokens = asttokens.ASTTokens(code_str, tree=function_node) - return Function(function_node, tokens) + return Function(first_node_with_tokens) diff --git a/tests/function/test_fixtures.py b/tests/function/test_fixtures.py index 8f64ce9..015916f 100644 --- a/tests/function/test_fixtures.py +++ b/tests/function/test_fixtures.py @@ -1,4 +1,5 @@ -import astroid +import ast + import pytest @@ -6,11 +7,11 @@ import pytest def test(): pass # act """]) -def test(function): - result = function +def test(first_node_with_tokens): + result = first_node_with_tokens - assert result.node.name == 'test' - pass_node = list(result.node.get_children())[-1] - assert isinstance(pass_node, astroid.Pass) - first_pass_token = next(result.tokens.get_tokens(pass_node, include_extra=True)) - assert first_pass_token.line.strip().endswith('# act') + assert result.name == 'test' + assert len(result.body) == 1 + pass_node = result.body[0] + assert isinstance(pass_node, ast.Pass) + assert pass_node.first_token.line.strip().endswith('# act') diff --git a/tests/function/test_init.py b/tests/function/test_init.py index 904863c..3761e43 100644 --- a/tests/function/test_init.py +++ b/tests/function/test_init.py @@ -1,20 +1,16 @@ -import asttokens import pytest from flake8_aaa.function import Function @pytest.mark.parametrize('code_str', [''' - def test(): - pass - ''']) -def test(function_node, code_str): - tokens = asttokens.ASTTokens(code_str, tree=function_node) +def test(): + pass +''']) +def test(first_node_with_tokens): + result = Function(first_node_with_tokens) - result = Function(function_node, tokens) - - assert result.node == function_node - assert result.tokens == tokens + assert result.node == first_node_with_tokens assert result.act_blocks == [] assert result.parsed is False assert result.is_noop is False diff --git a/tests/function/test_parse.py b/tests/function/test_parse.py index 4cb1d7e..910d0cd 100644 --- a/tests/function/test_parse.py +++ b/tests/function/test_parse.py @@ -23,19 +23,19 @@ def test_one(function): @pytest.mark.parametrize( 'code_str', [ ''' - def test(user): - result = login(user) # Logging in User returns True - assert result is True +def test(user): + result = login(user) # Logging in User returns True + assert result is True - result = login(user) # Already logged in User returns False - assert result is False + result = login(user) # Already logged in User returns False + assert result is False ''', ''' - def test(): - chickens = 1 # act - eggs = 1 # act +def test(): + chickens = 1 # act + eggs = 1 # act - assert chickens + eggs == 2 + assert chickens + eggs == 2 ''', ] ) diff --git a/tests/helpers/test_find_test_functions.py b/tests/helpers/test_find_test_functions.py index 8067a86..b1b1245 100644 --- a/tests/helpers/test_find_test_functions.py +++ b/tests/helpers/test_find_test_functions.py @@ -1,10 +1,10 @@ -import astroid +import ast from flake8_aaa.helpers import find_test_functions def test_empty(): - tree = astroid.parse("print('hi')") + tree = ast.parse("print('hi')") result = find_test_functions(tree) @@ -12,7 +12,7 @@ def test_empty(): def test_some(): - tree = astroid.parse( + tree = ast.parse( """ import pytest diff --git a/tests/helpers/test_function_is_noop.py b/tests/helpers/test_function_is_noop.py index 057038a..ae1b2cf 100644 --- a/tests/helpers/test_function_is_noop.py +++ b/tests/helpers/test_function_is_noop.py @@ -1,4 +1,5 @@ -import astroid +import ast + import pytest from flake8_aaa.helpers import function_is_noop @@ -11,7 +12,7 @@ from flake8_aaa.helpers import function_is_noop ] ) def test(code_str): - node = astroid.extract_node(code_str) + node = ast.parse(code_str).body[0] result = function_is_noop(node) @@ -22,7 +23,7 @@ def test(code_str): 'def test_tomorrow():\n # TODO write this test\n result = 1', ]) def test_not_noop(code_str): - node = astroid.extract_node(code_str) + node = ast.parse(code_str).body[0] result = function_is_noop(node) diff --git a/tests/helpers/test_node_is_pytest_raises.py b/tests/helpers/test_node_is_pytest_raises.py index 9a21de3..1e87e7b 100644 --- a/tests/helpers/test_node_is_pytest_raises.py +++ b/tests/helpers/test_node_is_pytest_raises.py @@ -1,4 +1,6 @@ -import astroid +import ast + +import asttokens import pytest from flake8_aaa.helpers import node_is_pytest_raises @@ -6,15 +8,22 @@ from flake8_aaa.helpers import node_is_pytest_raises @pytest.mark.parametrize( 'code_str', [ - '''with pytest.raises(Exception): - do_thing()''', '''with pytest.raises(Exception) as excinfo: - do_thing()''' + ''' +def test(): + with pytest.raises(Exception): + do_thing() +''', + ''' +def test_other(): + with pytest.raises(Exception) as excinfo: + do_thing() +''', ] ) -def test(code_str): - node = astroid.parse(code_str).body[0] +def test(first_node_with_tokens): + with_node = first_node_with_tokens.body[0] - result = node_is_pytest_raises(node) + result = node_is_pytest_raises(with_node) assert result is True @@ -24,7 +33,9 @@ def test(code_str): f.read()''', ]) def test_no(code_str): - node = astroid.parse(code_str).body[0] + tree = ast.parse(code_str) + asttokens.ASTTokens(code_str, tree=tree) + node = tree.body[0] result = node_is_pytest_raises(node) diff --git a/tests/helpers/test_node_is_result_assignment.py b/tests/helpers/test_node_is_result_assignment.py index ec85e03..ce87c34 100644 --- a/tests/helpers/test_node_is_result_assignment.py +++ b/tests/helpers/test_node_is_result_assignment.py @@ -1,33 +1,21 @@ -import astroid import pytest from flake8_aaa.helpers import node_is_result_assignment [email protected]('code_str', ( - 'result = 1', - 'result = lambda x: x + 1', -)) -def test(code_str): - node = astroid.extract_node(code_str) - - result = node_is_result_assignment(node) - - assert result is True - - @pytest.mark.parametrize( - 'code_str', ( - 'xresult = 1', - 'result, _ = 1, 2', - 'result[0] = 0', - 'result += 1', - 'result -= 1', - ) + ('code_str', 'expected_result'), + [ + ('result = 1', True), + ('result = lambda x: x + 1', True), + ('xresult = 1', False), + ('result, _ = 1, 2', False), + ('result[0] = 0', False), + ('result += 1', False), + ('result -= 1', False), + ], ) -def test_no(code_str): - node = astroid.parse(code_str).body[0] - - result = node_is_result_assignment(node) +def test_no(first_node_with_tokens, expected_result): + result = node_is_result_assignment(first_node_with_tokens) - assert result is False + assert result is expected_result diff --git a/tests/test_run.py b/tests/test_run.py index 0d05296..bb0b7a6 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -1,5 +1,9 @@ +# encoding: utf-8 + # Integration tests that flake8 runs and checks using this plugin +# Some unicode text: Réne has £10 - ensure that this file is loaded with Python 2 + from flake8_aaa.__about__ import __version__
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 9 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==1.6.3 asttokens==1.1.10 attrs==22.2.0 certifi==2021.5.30 flake8==3.5.0 -e git+https://github.com/jamescooke/flake8-aaa.git@15695f30ea8e2f80f92026468569ed00c6d031dc#egg=flake8_aaa importlib-metadata==4.8.3 iniconfig==1.1.1 lazy-object-proxy==1.3.1 mccabe==0.6.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pycodestyle==2.3.1 pyflakes==1.6.0 pyparsing==3.1.4 pytest==7.0.1 six==1.11.0 tomli==1.2.3 typing_extensions==4.1.1 wrapt==1.10.11 zipp==3.6.0
name: flake8-aaa channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==1.6.3 - asttokens==1.1.10 - attrs==22.2.0 - flake8==3.5.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - lazy-object-proxy==1.3.1 - mccabe==0.6.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.3.1 - pyflakes==1.6.0 - pyparsing==3.1.4 - pytest==7.0.1 - six==1.11.0 - tomli==1.2.3 - typing-extensions==4.1.1 - wrapt==1.10.11 - zipp==3.6.0 prefix: /opt/conda/envs/flake8-aaa
[ "tests/act_block/test_build.py::test_raises_block[\\ndef", "tests/act_block/test_build.py::test[result", "tests/act_block/test_build.py::test[with", "tests/act_block/test_build.py::test[data[new_key]", "tests/act_block/test_build.py::test_not_actions[act", "tests/act_block/test_build.py::test_not_actions[actions", "tests/act_block/test_build.py::test_not_actions[person", "tests/act_block/test_build.py::test_not_actions[result", "tests/act_block/test_build.py::test_not_actions[results", "tests/act_block/test_build.py::test_not_actions[with", "tests/checker/test_init.py::test", "tests/checker/test_load.py::test", "tests/function/test_init.py::test[\\ndef", "tests/function/test_parse.py::test_none[def", "tests/function/test_parse.py::test_one[def", "tests/function/test_parse.py::test_multi[\\ndef", "tests/helpers/test_find_test_functions.py::test_empty", "tests/helpers/test_find_test_functions.py::test_some", "tests/helpers/test_function_is_noop.py::test[def", "tests/helpers/test_node_is_pytest_raises.py::test[\\ndef", "tests/helpers/test_node_is_result_assignment.py::test_no[result" ]
[]
[ "tests/function/test_fixtures.py::test[\\ndef", "tests/helpers/test_function_is_noop.py::test_not_noop[def", "tests/helpers/test_node_is_pytest_raises.py::test_no[with", "tests/helpers/test_node_is_result_assignment.py::test_no[xresult", "tests/helpers/test_node_is_result_assignment.py::test_no[result,", "tests/helpers/test_node_is_result_assignment.py::test_no[result[0]" ]
[]
MIT License
2,589
[ "requirements/base.txt", "setup.py", "requirements/base.in", "flake8_aaa/function.py", "flake8_aaa/checker.py", "tox.ini", "flake8_aaa/helpers.py", "requirements/dev.txt", "flake8_aaa/act_block.py" ]
[ "requirements/base.txt", "setup.py", "requirements/base.in", "flake8_aaa/function.py", "flake8_aaa/checker.py", "tox.ini", "flake8_aaa/helpers.py", "requirements/dev.txt", "flake8_aaa/act_block.py" ]
theolind__pymysensors-154
f373e86e5423c8a92bb5adeb7b03ae7b64850e04
2018-05-26 12:59:31
f373e86e5423c8a92bb5adeb7b03ae7b64850e04
diff --git a/mysensors/__init__.py b/mysensors/__init__.py index f57486b..784f988 100644 --- a/mysensors/__init__.py +++ b/mysensors/__init__.py @@ -49,7 +49,7 @@ class Gateway(object): self.metric = True # if true - use metric, if false - use imperial if persistence: self.persistence = Persistence( - self.sensors, persistence_file, persistence_scheduler) + self.sensors, persistence_scheduler, persistence_file) else: self.persistence = None self.protocol_version = safe_is_version(protocol_version) @@ -351,7 +351,8 @@ class ThreadingGateway(Gateway): def __init__(self, *args, **kwargs): """Set up gateway instance.""" - super().__init__(*args, **kwargs) + super().__init__( + *args, persistence_scheduler=self._create_scheduler, **kwargs) self.lock = threading.Lock() self._stop_event = threading.Event() self._cancel_save = None @@ -373,12 +374,22 @@ class ThreadingGateway(Gateway): continue time.sleep(0.02) + def _create_scheduler(self, save_sensors): + """Return function to schedule saving sensors.""" + def schedule_save(): + """Save sensors and schedule a new save.""" + save_sensors() + scheduler = threading.Timer(10.0, schedule_save) + scheduler.start() + self._cancel_save = scheduler.cancel + return schedule_save + def start_persistence(self): """Load persistence file and schedule saving of persistence file.""" if not self.persistence: return self.persistence.safe_load_sensors() - self._cancel_save = self.persistence.schedule_save_sensors() + self.persistence.schedule_save_sensors() def stop(self): """Stop the background thread.""" @@ -494,7 +505,7 @@ class BaseAsyncGateway(BaseTransportGateway): """Return function to schedule saving sensors.""" @asyncio.coroutine def schedule_save(): - """Return a function to cancel the schedule.""" + """Save sensors and schedule a new save.""" yield from self.loop.run_in_executor(None, save_sensors) callback = partial( ensure_future, schedule_save(), loop=self.loop) diff --git a/mysensors/persistence.py b/mysensors/persistence.py index 5dd4b57..efb2e6c 100644 --- a/mysensors/persistence.py +++ b/mysensors/persistence.py @@ -3,35 +3,21 @@ import json import logging import os import pickle -import threading from .sensor import ChildSensor, Sensor _LOGGER = logging.getLogger(__name__) -def create_scheduler(save_sensors): - """Return function to schedule saving sensors.""" - def schedule_save(): - """Return a function to cancel the schedule.""" - save_sensors() - scheduler = threading.Timer(10.0, schedule_save) - scheduler.start() - return scheduler.cancel - return schedule_save - - class Persistence(object): """Organize persistence file saving and loading.""" def __init__( - self, sensors, persistence_file='mysensors.pickle', - schedule_factory=None): + self, sensors, schedule_factory, + persistence_file='mysensors.pickle'): """Set up Persistence instance.""" self.persistence_file = persistence_file self.persistence_bak = '{}.bak'.format(self.persistence_file) - if schedule_factory is None: - schedule_factory = create_scheduler self.schedule_save_sensors = schedule_factory(self.save_sensors) self._sensors = sensors self.need_save = True
Main program does not exit cleanly [branch master - version 0.14.0 - Using serial gateway - NO asyncio] After calling the SerialGateway.stop() method the program does not return to console but seems to be looping in a still alive thread ( probably the persistence thread). ************************************************************************************ ```py MYSGW_Serial_Port = '/dev/ttyMSGW' .... GATEWAY = mysensors.SerialGateway( MYSGW_Serial_Port, event_callback=event, persistence=True, persistence_file='./mysensors.json', protocol_version='2.0', baud=115200, timeout=1.0, reconnect_timeout=10.0) GATEWAY.start_persistence() GATEWAY.start() .... .... GATEWAY.stop() #-> main thread does not go past this point exit(0) ``` *************************************************************************************
theolind/pymysensors
diff --git a/tests/test_gateway_mqtt.py b/tests/test_gateway_mqtt.py index cba4270..60700fa 100644 --- a/tests/test_gateway_mqtt.py +++ b/tests/test_gateway_mqtt.py @@ -143,11 +143,10 @@ def test_subscribe_error(gateway, add_sensor, mock_sub, caplog): def test_start_stop_gateway( mock_save, mock_load, gateway, add_sensor, mock_pub, mock_sub): """Test start and stop of MQTT gateway.""" - gateway.persistence = Persistence(gateway.sensors) - mock_cancel_save = mock.MagicMock() + mock_schedule_factory = mock.MagicMock() mock_schedule_save = mock.MagicMock() - mock_schedule_save.return_value = mock_cancel_save - gateway.persistence.schedule_save_sensors = mock_schedule_save + mock_schedule_factory.return_value = mock_schedule_save + gateway.persistence = Persistence(gateway.sensors, mock_schedule_factory) sensor = add_sensor(1) sensor.add_child_sensor(1, gateway.const.Presentation.S_HUM) sensor.children[1].values[gateway.const.SetReq.V_HUM] = '20' @@ -173,7 +172,6 @@ def test_start_stop_gateway( assert mock_pub.call_count == 2 assert mock_pub.mock_calls == calls gateway.stop() - assert mock_cancel_save.call_count == 1 assert mock_save.call_count == 1 @@ -185,7 +183,7 @@ def test_mqtt_load_persistence(gateway, add_sensor, mock_sub, tmpdir): persistence_file = tmpdir.join('file.json') gateway.persistence = Persistence( - gateway.sensors, persistence_file.strpath) + gateway.sensors, mock.MagicMock(), persistence_file.strpath) gateway.persistence.save_sensors() del gateway.sensors[1] assert 1 not in gateway.sensors diff --git a/tests/test_mysensors.py b/tests/test_mysensors.py index 403ce9d..3a6c9c8 100644 --- a/tests/test_mysensors.py +++ b/tests/test_mysensors.py @@ -613,6 +613,28 @@ def test_gateway_low_protocol(): assert gateway.protocol_version == '1.4' [email protected]('mysensors.persistence.Persistence.save_sensors') [email protected]('mysensors.threading.Timer') +def test_threading_persistence(mock_timer_class, mock_save_sensors): + """Test schedule persistence on threading gateway.""" + mock_timer_1 = mock.MagicMock() + mock_timer_2 = mock.MagicMock() + mock_timer_class.side_effect = [mock_timer_1, mock_timer_2] + gateway = ThreadingGateway(persistence=True) + gateway.persistence.schedule_save_sensors() + assert mock_save_sensors.call_count == 1 + assert mock_timer_class.call_count == 1 + assert mock_timer_1.start.call_count == 1 + gateway.persistence.schedule_save_sensors() + assert mock_save_sensors.call_count == 2 + assert mock_timer_class.call_count == 2 + assert mock_timer_1.start.call_count == 1 + assert mock_timer_2.start.call_count == 1 + gateway.stop() + assert mock_timer_2.cancel.call_count == 1 + assert mock_save_sensors.call_count == 3 + + def test_update_fw(): """Test calling fw_update with bad path.""" gateway = ThreadingGateway() diff --git a/tests/test_persistence.py b/tests/test_persistence.py index fdf5464..c5d8896 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -45,7 +45,7 @@ def test_persistence(gateway, add_sensor, filename, tmpdir): persistence_file = tmpdir.join(filename) gateway.persistence = Persistence( - gateway.sensors, persistence_file.strpath) + gateway.sensors, mock.MagicMock(), persistence_file.strpath) gateway.persistence.save_sensors() del gateway.sensors[1] assert 1 not in gateway.sensors @@ -75,7 +75,7 @@ def test_bad_file_name(gateway, add_sensor, tmpdir): add_sensor(1) persistence_file = tmpdir.join('file.bad') gateway.persistence = Persistence( - gateway.sensors, persistence_file.strpath) + gateway.sensors, mock.MagicMock(), persistence_file.strpath) with pytest.raises(Exception): gateway.persistence.save_sensors() @@ -85,7 +85,7 @@ def test_json_no_files(gateway, tmpdir): assert not gateway.sensors persistence_file = tmpdir.join('file.json') gateway.persistence = Persistence( - gateway.sensors, persistence_file.strpath) + gateway.sensors, mock.MagicMock(), persistence_file.strpath) gateway.persistence.safe_load_sensors() assert not gateway.sensors @@ -97,7 +97,7 @@ def test_empty_files(gateway, filename, tmpdir): assert not gateway.sensors persistence_file = tmpdir.join(filename) gateway.persistence = Persistence( - gateway.sensors, persistence_file.strpath) + gateway.sensors, mock.MagicMock(), persistence_file.strpath) persistence = gateway.persistence persistence_file.write('') with open(persistence.persistence_bak, 'w') as file_handle: @@ -112,7 +112,8 @@ def test_json_empty_file_good_bak(gateway, add_sensor, tmpdir): assert 1 in gateway.sensors persistence_file = tmpdir.join('file.json') orig_file_name = persistence_file.strpath - gateway.persistence = Persistence(gateway.sensors, orig_file_name) + gateway.persistence = Persistence( + gateway.sensors, mock.MagicMock(), orig_file_name) gateway.persistence.save_sensors() del gateway.sensors[1] assert 1 not in gateway.sensors @@ -160,7 +161,7 @@ def test_persistence_upgrade( assert 'description' not in sensor.children[0].__dict__ persistence_file = tmpdir.join(filename) gateway.persistence = Persistence( - gateway.sensors, persistence_file.strpath) + gateway.sensors, mock.MagicMock(), persistence_file.strpath) gateway.persistence.save_sensors() del gateway.sensors[1] assert 1 not in gateway.sensors @@ -175,16 +176,21 @@ def test_persistence_upgrade( assert gateway.sensors[1].children[0].type == sensor.children[0].type [email protected]('mysensors.persistence.threading.Timer') @mock.patch('mysensors.persistence.Persistence.save_sensors') -def test_schedule_save_sensors(mock_save, mock_timer_class, gateway): +def test_schedule_save_sensors(mock_save, gateway): """Test schedule save sensors.""" - mock_timer = mock.MagicMock() - mock_timer_class.return_value = mock_timer - gateway.persistence = Persistence(gateway.sensors) + mock_schedule_save = mock.MagicMock() + mock_schedule_factory = mock.MagicMock() + mock_schedule_factory.return_value = mock_schedule_save + + gateway.persistence = Persistence(gateway.sensors, mock_schedule_factory) + + assert mock_schedule_factory.call_count == 1 + assert mock_schedule_factory.call_args == mock.call(mock_save) + gateway.persistence.schedule_save_sensors() - assert mock_save.call_count == 1 - assert mock_timer.start.call_count == 1 + + assert mock_schedule_save.call_count == 1 class MySensorsJSONEncoderTestUpgrade(MySensorsJSONEncoder):
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
0.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "flake8", "pylint", "pydocstyle" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==2.11.7 attrs==22.2.0 certifi==2021.5.30 crcmod==1.7 dill==0.3.4 flake8==5.0.4 get-mac==0.9.2 importlib-metadata==4.2.0 iniconfig==1.1.1 intelhex==2.3.0 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pycodestyle==2.9.1 pydocstyle==6.3.0 pyflakes==2.5.0 pylint==2.13.9 -e git+https://github.com/theolind/pymysensors.git@f373e86e5423c8a92bb5adeb7b03ae7b64850e04#egg=pymysensors pyparsing==3.1.4 pyserial==3.5 pyserial-asyncio==0.6 pytest==7.0.1 snowballstemmer==2.2.0 tomli==1.2.3 typed-ast==1.5.5 typing_extensions==4.1.1 voluptuous==0.11.1 wrapt==1.16.0 zipp==3.6.0
name: pymysensors channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==2.11.7 - attrs==22.2.0 - crcmod==1.7 - dill==0.3.4 - flake8==5.0.4 - get-mac==0.9.2 - importlib-metadata==4.2.0 - iniconfig==1.1.1 - intelhex==2.3.0 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pydocstyle==6.3.0 - pyflakes==2.5.0 - pylint==2.13.9 - pyparsing==3.1.4 - pyserial==3.5 - pyserial-asyncio==0.6 - pytest==7.0.1 - snowballstemmer==2.2.0 - tomli==1.2.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - voluptuous==0.11.1 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/pymysensors
[ "tests/test_gateway_mqtt.py::test_start_stop_gateway", "tests/test_gateway_mqtt.py::test_mqtt_load_persistence", "tests/test_mysensors.py::test_threading_persistence", "tests/test_persistence.py::test_persistence[file.pickle]", "tests/test_persistence.py::test_persistence[file.json]", "tests/test_persistence.py::test_bad_file_name", "tests/test_persistence.py::test_json_no_files", "tests/test_persistence.py::test_empty_files[file.pickle]", "tests/test_persistence.py::test_empty_files[file.json]", "tests/test_persistence.py::test_json_empty_file_good_bak", "tests/test_persistence.py::test_persistence_upgrade[file.pickle]", "tests/test_persistence.py::test_persistence_upgrade[file.json]", "tests/test_persistence.py::test_schedule_save_sensors" ]
[]
[ "tests/test_gateway_mqtt.py::test_send", "tests/test_gateway_mqtt.py::test_send_empty_string", "tests/test_gateway_mqtt.py::test_send_error", "tests/test_gateway_mqtt.py::test_recv", "tests/test_gateway_mqtt.py::test_recv_wrong_prefix", "tests/test_gateway_mqtt.py::test_presentation", "tests/test_gateway_mqtt.py::test_presentation_no_sensor", "tests/test_gateway_mqtt.py::test_subscribe_error", "tests/test_gateway_mqtt.py::test_nested_prefix", "tests/test_gateway_mqtt.py::test_get_gateway_id", "tests/test_mysensors.py::test_logic_bad_message[1.4]", "tests/test_mysensors.py::test_logic_bad_message[1.5]", "tests/test_mysensors.py::test_logic_bad_message[2.0]", "tests/test_mysensors.py::test_logic_bad_message[2.1]", "tests/test_mysensors.py::test_logic_bad_message[2.2]", "tests/test_mysensors.py::test_non_presented_sensor[1.4-None]", "tests/test_mysensors.py::test_non_presented_sensor[1.5-None]", "tests/test_mysensors.py::test_non_presented_sensor[2.0-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_non_presented_sensor[2.1-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_non_presented_sensor[2.2-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_present_to_non_sensor[1.4-None]", "tests/test_mysensors.py::test_present_to_non_sensor[1.5-None]", "tests/test_mysensors.py::test_present_to_non_sensor[2.0-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_present_to_non_sensor[2.1-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_present_to_non_sensor[2.2-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_internal_id_request[1.4]", "tests/test_mysensors.py::test_internal_id_request[1.5]", "tests/test_mysensors.py::test_internal_id_request[2.0]", "tests/test_mysensors.py::test_internal_id_request[2.1]", "tests/test_mysensors.py::test_internal_id_request[2.2]", "tests/test_mysensors.py::test_id_request_with_node_zero[1.4]", "tests/test_mysensors.py::test_id_request_with_node_zero[1.5]", "tests/test_mysensors.py::test_id_request_with_node_zero[2.0]", "tests/test_mysensors.py::test_id_request_with_node_zero[2.1]", "tests/test_mysensors.py::test_id_request_with_node_zero[2.2]", "tests/test_mysensors.py::test_presentation_arduino_node[1.4]", "tests/test_mysensors.py::test_presentation_arduino_node[1.5]", "tests/test_mysensors.py::test_presentation_arduino_node[2.0]", "tests/test_mysensors.py::test_presentation_arduino_node[2.1]", "tests/test_mysensors.py::test_presentation_arduino_node[2.2]", "tests/test_mysensors.py::test_id_request_presentation[1.4]", "tests/test_mysensors.py::test_id_request_presentation[1.5]", "tests/test_mysensors.py::test_id_request_presentation[2.0]", "tests/test_mysensors.py::test_id_request_presentation[2.1]", "tests/test_mysensors.py::test_id_request_presentation[2.2]", "tests/test_mysensors.py::test_internal_config[1.4]", "tests/test_mysensors.py::test_internal_config[1.5]", "tests/test_mysensors.py::test_internal_config[2.0]", "tests/test_mysensors.py::test_internal_config[2.1]", "tests/test_mysensors.py::test_internal_config[2.2]", "tests/test_mysensors.py::test_internal_time[1.4]", "tests/test_mysensors.py::test_internal_time[1.5]", "tests/test_mysensors.py::test_internal_time[2.0]", "tests/test_mysensors.py::test_internal_time[2.1]", "tests/test_mysensors.py::test_internal_time[2.2]", "tests/test_mysensors.py::test_internal_sketch_name[1.4]", "tests/test_mysensors.py::test_internal_sketch_name[1.5]", "tests/test_mysensors.py::test_internal_sketch_name[2.0]", "tests/test_mysensors.py::test_internal_sketch_name[2.1]", "tests/test_mysensors.py::test_internal_sketch_name[2.2]", "tests/test_mysensors.py::test_internal_sketch_version[1.4]", "tests/test_mysensors.py::test_internal_sketch_version[1.5]", "tests/test_mysensors.py::test_internal_sketch_version[2.0]", "tests/test_mysensors.py::test_internal_sketch_version[2.1]", "tests/test_mysensors.py::test_internal_sketch_version[2.2]", "tests/test_mysensors.py::test_internal_log_message[1.4]", "tests/test_mysensors.py::test_internal_log_message[1.5]", "tests/test_mysensors.py::test_internal_log_message[2.0]", "tests/test_mysensors.py::test_internal_log_message[2.1]", "tests/test_mysensors.py::test_internal_log_message[2.2]", "tests/test_mysensors.py::test_internal_gateway_ready[1.4-None]", "tests/test_mysensors.py::test_internal_gateway_ready[1.5-None]", "tests/test_mysensors.py::test_internal_gateway_ready[2.0-255;255;3;0;20;\\n]", "tests/test_mysensors.py::test_internal_gateway_ready[2.1-255;255;3;0;20;\\n]", "tests/test_mysensors.py::test_internal_gateway_ready[2.2-255;255;3;0;20;\\n]", "tests/test_mysensors.py::test_present_light_level_sensor[1.4]", "tests/test_mysensors.py::test_present_light_level_sensor[1.5]", "tests/test_mysensors.py::test_present_light_level_sensor[2.0]", "tests/test_mysensors.py::test_present_light_level_sensor[2.1]", "tests/test_mysensors.py::test_present_light_level_sensor[2.2]", "tests/test_mysensors.py::test_present_humidity_sensor[1.4]", "tests/test_mysensors.py::test_present_humidity_sensor[1.5]", "tests/test_mysensors.py::test_present_humidity_sensor[2.0]", "tests/test_mysensors.py::test_present_humidity_sensor[2.1]", "tests/test_mysensors.py::test_present_humidity_sensor[2.2]", "tests/test_mysensors.py::test_present_same_child[1.4]", "tests/test_mysensors.py::test_present_same_child[1.5]", "tests/test_mysensors.py::test_present_same_child[2.0]", "tests/test_mysensors.py::test_present_same_child[2.1]", "tests/test_mysensors.py::test_present_same_child[2.2]", "tests/test_mysensors.py::test_set_light_level[1.4]", "tests/test_mysensors.py::test_set_light_level[1.5]", "tests/test_mysensors.py::test_set_light_level[2.0]", "tests/test_mysensors.py::test_set_light_level[2.1]", "tests/test_mysensors.py::test_set_light_level[2.2]", "tests/test_mysensors.py::test_set_humidity_level[1.4]", "tests/test_mysensors.py::test_set_humidity_level[1.5]", "tests/test_mysensors.py::test_set_humidity_level[2.0]", "tests/test_mysensors.py::test_set_humidity_level[2.1]", "tests/test_mysensors.py::test_set_humidity_level[2.2]", "tests/test_mysensors.py::test_battery_level[1.4]", "tests/test_mysensors.py::test_battery_level[1.5]", "tests/test_mysensors.py::test_battery_level[2.0]", "tests/test_mysensors.py::test_battery_level[2.1]", "tests/test_mysensors.py::test_battery_level[2.2]", "tests/test_mysensors.py::test_bad_battery_level[1.4]", "tests/test_mysensors.py::test_bad_battery_level[1.5]", "tests/test_mysensors.py::test_bad_battery_level[2.0]", "tests/test_mysensors.py::test_bad_battery_level[2.1]", "tests/test_mysensors.py::test_bad_battery_level[2.2]", "tests/test_mysensors.py::test_req[1.4]", "tests/test_mysensors.py::test_req[1.5]", "tests/test_mysensors.py::test_req[2.0]", "tests/test_mysensors.py::test_req[2.1]", "tests/test_mysensors.py::test_req[2.2]", "tests/test_mysensors.py::test_req_zerovalue[1.4]", "tests/test_mysensors.py::test_req_zerovalue[1.5]", "tests/test_mysensors.py::test_req_zerovalue[2.0]", "tests/test_mysensors.py::test_req_zerovalue[2.1]", "tests/test_mysensors.py::test_req_zerovalue[2.2]", "tests/test_mysensors.py::test_req_novalue[1.4]", "tests/test_mysensors.py::test_req_novalue[1.5]", "tests/test_mysensors.py::test_req_novalue[2.0]", "tests/test_mysensors.py::test_req_novalue[2.1]", "tests/test_mysensors.py::test_req_novalue[2.2]", "tests/test_mysensors.py::test_req_notasensor[1.4]", "tests/test_mysensors.py::test_req_notasensor[1.5]", "tests/test_mysensors.py::test_req_notasensor[2.0]", "tests/test_mysensors.py::test_req_notasensor[2.1]", "tests/test_mysensors.py::test_req_notasensor[2.2]", "tests/test_mysensors.py::test_callback[1.4]", "tests/test_mysensors.py::test_callback[1.5]", "tests/test_mysensors.py::test_callback[2.0]", "tests/test_mysensors.py::test_callback[2.1]", "tests/test_mysensors.py::test_callback[2.2]", "tests/test_mysensors.py::test_callback_exception[1.4]", "tests/test_mysensors.py::test_callback_exception[1.5]", "tests/test_mysensors.py::test_callback_exception[2.0]", "tests/test_mysensors.py::test_callback_exception[2.1]", "tests/test_mysensors.py::test_callback_exception[2.2]", "tests/test_mysensors.py::test_set_and_reboot[1.4]", "tests/test_mysensors.py::test_set_and_reboot[1.5]", "tests/test_mysensors.py::test_set_and_reboot[2.0]", "tests/test_mysensors.py::test_set_and_reboot[2.1]", "tests/test_mysensors.py::test_set_and_reboot[2.2]", "tests/test_mysensors.py::test_set_child_value[1.4]", "tests/test_mysensors.py::test_set_child_value[1.5]", "tests/test_mysensors.py::test_set_child_value[2.0]", "tests/test_mysensors.py::test_set_child_value[2.1]", "tests/test_mysensors.py::test_set_child_value[2.2]", "tests/test_mysensors.py::test_set_child_value_no_sensor[1.4-None]", "tests/test_mysensors.py::test_set_child_value_no_sensor[1.5-None]", "tests/test_mysensors.py::test_set_child_value_no_sensor[2.0-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_set_child_value_no_sensor[2.1-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_set_child_value_no_sensor[2.2-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_non_presented_child[1.4-None]", "tests/test_mysensors.py::test_non_presented_child[1.5-None]", "tests/test_mysensors.py::test_non_presented_child[2.0-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_non_presented_child[2.1-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_non_presented_child[2.2-1;255;3;0;19;\\n]", "tests/test_mysensors.py::test_set_child_no_children[1.4]", "tests/test_mysensors.py::test_set_child_no_children[1.5]", "tests/test_mysensors.py::test_set_child_no_children[2.0]", "tests/test_mysensors.py::test_set_child_no_children[2.1]", "tests/test_mysensors.py::test_set_child_no_children[2.2]", "tests/test_mysensors.py::test_set_child_value_bad_type[1.4]", "tests/test_mysensors.py::test_set_child_value_bad_type[1.5]", "tests/test_mysensors.py::test_set_child_value_bad_type[2.0]", "tests/test_mysensors.py::test_set_child_value_bad_type[2.1]", "tests/test_mysensors.py::test_set_child_value_bad_type[2.2]", "tests/test_mysensors.py::test_set_child_value_bad_ack[1.4]", "tests/test_mysensors.py::test_set_child_value_bad_ack[1.5]", "tests/test_mysensors.py::test_set_child_value_bad_ack[2.0]", "tests/test_mysensors.py::test_set_child_value_bad_ack[2.1]", "tests/test_mysensors.py::test_set_child_value_bad_ack[2.2]", "tests/test_mysensors.py::test_set_child_value_value_type[1.4]", "tests/test_mysensors.py::test_set_child_value_value_type[1.5]", "tests/test_mysensors.py::test_set_child_value_value_type[2.0]", "tests/test_mysensors.py::test_set_child_value_value_type[2.1]", "tests/test_mysensors.py::test_set_child_value_value_type[2.2]", "tests/test_mysensors.py::test_child_validate[1.4]", "tests/test_mysensors.py::test_child_validate[1.5]", "tests/test_mysensors.py::test_child_validate[2.0]", "tests/test_mysensors.py::test_child_validate[2.1]", "tests/test_mysensors.py::test_child_validate[2.2]", "tests/test_mysensors.py::test_set_forecast[1.4]", "tests/test_mysensors.py::test_set_forecast[1.5]", "tests/test_mysensors.py::test_set_forecast[2.0]", "tests/test_mysensors.py::test_set_forecast[2.1]", "tests/test_mysensors.py::test_set_forecast[2.2]", "tests/test_mysensors.py::test_set_bad_battery_attribute[1.4]", "tests/test_mysensors.py::test_set_bad_battery_attribute[1.5]", "tests/test_mysensors.py::test_set_bad_battery_attribute[2.0]", "tests/test_mysensors.py::test_set_bad_battery_attribute[2.1]", "tests/test_mysensors.py::test_set_bad_battery_attribute[2.2]", "tests/test_mysensors.py::test_set_rgb[1.5]", "tests/test_mysensors.py::test_set_rgb[2.0]", "tests/test_mysensors.py::test_set_rgb[2.1]", "tests/test_mysensors.py::test_set_rgb[2.2]", "tests/test_mysensors.py::test_set_rgbw[1.5]", "tests/test_mysensors.py::test_set_rgbw[2.0]", "tests/test_mysensors.py::test_set_rgbw[2.1]", "tests/test_mysensors.py::test_set_rgbw[2.2]", "tests/test_mysensors.py::test_smartsleep[2.0-1;255;3;0;22;\\n]", "tests/test_mysensors.py::test_smartsleep[2.1-1;255;3;0;22;\\n]", "tests/test_mysensors.py::test_smartsleep[2.2-1;255;3;0;32;500\\n]", "tests/test_mysensors.py::test_smartsleep_from_unknown[2.0-1;255;3;0;22;\\n]", "tests/test_mysensors.py::test_smartsleep_from_unknown[2.1-1;255;3;0;22;\\n]", "tests/test_mysensors.py::test_smartsleep_from_unknown[2.2-1;255;3;0;32;500\\n]", "tests/test_mysensors.py::test_set_with_new_state[2.0-1;255;3;0;22;\\n]", "tests/test_mysensors.py::test_set_with_new_state[2.1-1;255;3;0;22;\\n]", "tests/test_mysensors.py::test_set_with_new_state[2.2-1;255;3;0;32;500\\n]", "tests/test_mysensors.py::test_discover_response_unknown[2.0]", "tests/test_mysensors.py::test_discover_response_unknown[2.1]", "tests/test_mysensors.py::test_discover_response_unknown[2.2]", "tests/test_mysensors.py::test_discover_response_known[2.0]", "tests/test_mysensors.py::test_discover_response_known[2.1]", "tests/test_mysensors.py::test_discover_response_known[2.2]", "tests/test_mysensors.py::test_set_position[2.0]", "tests/test_mysensors.py::test_set_position[2.1]", "tests/test_mysensors.py::test_set_position[2.2]", "tests/test_mysensors.py::test_gateway_bad_protocol", "tests/test_mysensors.py::test_gateway_low_protocol", "tests/test_mysensors.py::test_update_fw", "tests/test_mysensors.py::test_update_fw_bad_path" ]
[]
MIT License
2,590
[ "mysensors/persistence.py", "mysensors/__init__.py" ]
[ "mysensors/persistence.py", "mysensors/__init__.py" ]
jamescooke__flake8-aaa-14
88221857e1f5beab0d3e024131adef95b31f24c9
2018-05-27 13:05:09
47893db2a642dc33d937e71f661de792a6ce4021
diff --git a/flake8_aaa/function.py b/flake8_aaa/function.py index e353135..2944886 100644 --- a/flake8_aaa/function.py +++ b/flake8_aaa/function.py @@ -46,6 +46,12 @@ class Function: except NotActionBlock: continue + # Allow `pytest.raises` in assert blocks + if len(self.act_blocks) > 1: + self.act_blocks = [self.act_blocks[0]] + list( + filter(lambda ab: ab.block_type != ActBlock.PYTEST_RAISES, self.act_blocks[1:]) + ) + self.parsed = True return len(self.act_blocks) diff --git a/setup.cfg b/setup.cfg index dbb65e4..9211379 100644 --- a/setup.cfg +++ b/setup.cfg @@ -9,5 +9,6 @@ not_skip=__init__.py max-line-length = 120 [yapf] +# coalesce_brackets = true dedent_closing_brackets = true column_limit = 120 diff --git a/tox.ini b/tox.ini index aa37fc8..ef19d36 100644 --- a/tox.ini +++ b/tox.ini @@ -13,4 +13,5 @@ commands = install: flake8 --version test: pytest lint: make lint +setenv = IN_TOX = 1 whitelist_externals = make
Allow `pytest.raises` in assert blocks In this test from here: https://github.com/constructpm/pysyncgateway/blob/master/tests/user/test_delete.py#L8-L14 ``` def test(existing_user): result = existing_user.delete() assert result is True assert result.retrieved is False with pytest.raises(DoesNotExist): result.retrieve() ``` `flake8-aaa` raises `AAA02` multiple Act blocks found in test. Instead, `flake8-aaa` should allow this because checking that results raise exceptions is part of a normal testing process.
jamescooke/flake8-aaa
diff --git a/tests/function/test_check.py b/tests/function/test_check.py index a95d8e1..8f13981 100644 --- a/tests/function/test_check.py +++ b/tests/function/test_check.py @@ -17,12 +17,25 @@ def test_noop(function): assert result == [] [email protected]('code_str', [''' [email protected]( + 'code_str', [ + ''' def test(): result = 1 assert result == 1 -''']) +''', + ''' +def test(existing_user): + result = existing_user.delete() + + assert result is True + assert result.retrieved is False + with pytest.raises(DoesNotExist): + result.retrieve() +''', + ] +) def test_result_assigned(function): function.parse() @@ -51,7 +64,7 @@ def test(): x = 1 + 1 # act assert x == 2 ''']) -def test_no_qa(function): +def test_act(function): function.parse() result = function.check() diff --git a/tests/function/test_parse.py b/tests/function/test_parse.py index 910d0cd..ecbf225 100644 --- a/tests/function/test_parse.py +++ b/tests/function/test_parse.py @@ -1,5 +1,7 @@ import pytest +from flake8_aaa.act_block import ActBlock + @pytest.mark.parametrize('code_str', ['def test():\n pass']) def test_none(function): @@ -45,3 +47,25 @@ def test_multi(function): assert result == 2 assert function.parsed is True assert function.is_noop is False + + [email protected]( + 'code_str', [ + ''' +def test(existing_user): + result = existing_user.delete() + + assert result is True + assert result.retrieved is False + with pytest.raises(DoesNotExist): + result.retrieve() +''' + ] +) +def test(function): + result = function.parse() + + assert result == 1 + assert function.parsed is True + assert function.is_noop is False + assert function.act_blocks[0].block_type == ActBlock.RESULT_ASSIGNMENT diff --git a/tests/test_run.py b/tests/test_run.py index bb0b7a6..0550997 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -4,15 +4,23 @@ # Some unicode text: Réne has £10 - ensure that this file is loaded with Python 2 +import os + +import pytest + from flake8_aaa.__about__ import __version__ +skip_not_tox = pytest.mark.skipif(not os.getenv('IN_TOX', False), reason='Not running inside Tox') + +@skip_not_tox def test_installed(flake8dir): result = flake8dir.run_flake8(extra_args=['--version']) assert 'aaa: {}'.format(__version__) in result.out +@skip_not_tox def test(flake8dir): flake8dir.make_py_files( test_plus='''
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 3 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asttokens==1.1.10 attrs==22.2.0 certifi==2021.5.30 flake8==3.5.0 -e git+https://github.com/jamescooke/flake8-aaa.git@88221857e1f5beab0d3e024131adef95b31f24c9#egg=flake8_aaa importlib-metadata==4.8.3 iniconfig==1.1.1 mccabe==0.6.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pycodestyle==2.3.1 pyflakes==1.6.0 pyparsing==3.1.4 pytest==7.0.1 six==1.11.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: flake8-aaa channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asttokens==1.1.10 - attrs==22.2.0 - flake8==3.5.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mccabe==0.6.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.3.1 - pyflakes==1.6.0 - pyparsing==3.1.4 - pytest==7.0.1 - six==1.11.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/flake8-aaa
[ "tests/function/test_check.py::test_result_assigned[\\ndef", "tests/function/test_parse.py::test[\\ndef" ]
[]
[ "tests/function/test_check.py::test_noop[def", "tests/function/test_check.py::test_no_result[\\ndef", "tests/function/test_check.py::test_act[\\ndef", "tests/function/test_check.py::test_multi_act[\\ndef", "tests/function/test_check.py::test_not_parsed[x", "tests/function/test_parse.py::test_none[def", "tests/function/test_parse.py::test_one[def", "tests/function/test_parse.py::test_multi[\\ndef" ]
[]
MIT License
2,591
[ "tox.ini", "flake8_aaa/function.py", "setup.cfg" ]
[ "tox.ini", "flake8_aaa/function.py", "setup.cfg" ]
acorg__dark-matter-576
66f246ba9417430e3f00e94ca0abc88de59a92d4
2018-05-27 14:07:28
66f246ba9417430e3f00e94ca0abc88de59a92d4
diff --git a/dark/__init__.py b/dark/__init__.py index 0246a07..6a59296 100644 --- a/dark/__init__.py +++ b/dark/__init__.py @@ -7,4 +7,4 @@ if sys.version_info < (2, 7): # will not be found by the version() function in ../setup.py # # Remember to update ../CHANGELOG.md describing what's new in each version. -__version__ = '3.0.5' +__version__ = '3.0.6' diff --git a/dark/filter.py b/dark/filter.py index 0665ffc..b0daa76 100644 --- a/dark/filter.py +++ b/dark/filter.py @@ -279,6 +279,23 @@ def addFASTAFilteringCommandLineOptions(parser): help=('A file of (1-based) sequence numbers to retain. Numbers must ' 'be one per line.')) + parser.add_argument( + '--idLambda', metavar='LAMBDA-FUNCTION', + help=('A one-argument function taking and returning a read id. ' + 'E.g., --idLambda "lambda id: id.split(\'_\')[0]" or ' + '--idLambda "lambda id: id[:10]". If the function returns None, ' + 'the read will be filtered out.')) + + parser.add_argument( + '--readLambda', metavar='LAMBDA-FUNCTION', + help=('A one-argument function taking and returning a read. ' + 'E.g., --readLambda "lambda r: Read(r.id.split(\'_\')[0], ' + 'r.sequence.strip(\'-\')". Make sure to also modify the quality ' + 'string if you change the length of a FASTQ sequence. If the ' + 'function returns None, the read will be filtered out. The ' + 'function will be passed to eval with the dark.reads classes ' + 'Read, DNARead, AARead, etc. all in scope.')) + # A mutually exclusive group for --keepSites, --keepSitesFile, # --removeSites, and --removeSitesFile. group = parser.add_mutually_exclusive_group() @@ -381,4 +398,5 @@ def parseFASTAFilteringCommandLineOptions(args, reads): randomSubset=args.randomSubset, trueLength=args.trueLength, sampleFraction=args.sampleFraction, sequenceNumbersFile=args.sequenceNumbersFile, + idLambda=args.idLambda, readLambda=args.readLambda, keepSites=keepSites, removeSites=removeSites) diff --git a/dark/reads.py b/dark/reads.py index 42390e4..1074f78 100644 --- a/dark/reads.py +++ b/dark/reads.py @@ -740,8 +740,9 @@ class ReadFilter(object): sequence identity. @param removeDuplicatesById: If C{True} remove duplicated reads based only on read id. - @param removeDescriptions: If C{True} remove the description part of read - ids (i.e., the part following the first whitespace). + @param removeDescriptions: If C{True} remove the description (the part + following the first whitespace) from read ids. The description is + removed after applying the function specified by --idLambda (if any). @param modifier: If not C{None}, a function that is passed a read and which either returns a read or C{None}. If it returns a read, that read is passed through the filter. If it returns C{None}, @@ -791,6 +792,14 @@ class ReadFilter(object): file containing (1-based) sequence numbers, in ascending order, one per line. Only those sequences matching the given numbers will be kept. + @param idLambda: If not C{None}, a C{str} Python lambda function + specification to use to modify read ids. The function is applied + before removing the description (if --removeDescriptions is also + specified). + @param readLambda: If not C{None}, a C{str} Python lambda function + specification to use to modify reads. The function will be passed, + and must return, a single Read (or one of its subclasses). This + function is called after the --idLambda function, if any. @param keepSites: A set of C{int} 0-based sites (i.e., indices) in sequences that should be kept. If C{None} (the default), all sites are kept. @@ -819,7 +828,8 @@ class ReadFilter(object): removeDuplicates=False, removeDuplicatesById=False, removeDescriptions=False, modifier=None, randomSubset=None, trueLength=None, sampleFraction=None, - sequenceNumbersFile=None, keepSites=None, removeSites=None): + sequenceNumbersFile=None, idLambda=None, readLambda=None, + keepSites=None, removeSites=None): if randomSubset is not None: if sampleFraction is not None: @@ -929,6 +939,9 @@ class ReadFilter(object): sampleFraction = None self.sampleFraction = sampleFraction + self.idLambda = eval(idLambda) if idLambda else None + self.readLambda = eval(readLambda) if readLambda else None + def filter(self, read): """ Check if a read passes the filter. @@ -1038,6 +1051,20 @@ class ReadFilter(object): elif self.removeSites is not None: read = read.newFromSites(self.removeSites, exclude=True) + if self.idLambda: + newId = self.idLambda(read.id) + if newId is None: + return False + else: + read.id = newId + + if self.readLambda: + newRead = self.readLambda(read) + if newRead is None: + return False + else: + read = newRead + if self.removeDescriptions: read.id = read.id.split()[0]
Add ability to give an anonymous Python function for read id conversion when filtering FASTA
acorg/dark-matter
diff --git a/test/test_reads.py b/test/test_reads.py index 4e51442..5d9cd3e 100644 --- a/test/test_reads.py +++ b/test/test_reads.py @@ -3126,6 +3126,52 @@ class TestReadsFiltering(TestCase): six.assertRaisesRegex(self, ValueError, error, Reads().filter, keepSites={4}, removeSites={5}) + def testIdLambda(self): + """ + A passed idLambda function should produce the expected read ids. + """ + read = Read('id1', 'ATCGCC') + reads = Reads(initialReads=[read]) + result = reads.filter(idLambda='lambda id: "x-" + id.upper()') + self.assertEqual('x-ID1', list(result)[0].id) + + def testIdLambdaReturningNone(self): + """ + A passed idLambda function should produce the expected read ids, + including when it returns None. + """ + read1 = Read('id1', 'ATCGCC') + read2 = Read('id2', 'GGATCG') + reads = Reads(initialReads=[read1, read2]) + result = reads.filter( + idLambda='lambda id: "aa" if id.find("1") > -1 else None') + (result,) = list(result) + self.assertEqual('aa', result.id) + + def testReadLambda(self): + """ + A passed readLambda function should produce the expected reads. + """ + read = Read('id1', 'ATCGCC') + reads = Reads(initialReads=[read]) + result = reads.filter(readLambda='lambda r: Read("hey", "AAA")') + (result,) = list(result) + self.assertEqual(Read('hey', 'AAA'), result) + + def testReadLambdaReturningNone(self): + """ + A passed readLambda function should produce the expected reads, + including when it returns None. + """ + read1 = Read('xid1', 'ATCGCC') + read2 = Read('yid2', 'GGATCG') + reads = Reads(initialReads=[read1, read2]) + result = reads.filter( + readLambda=('lambda r: Read(r.id + "-x", r.sequence[:2]) ' + 'if r.id.startswith("x") else None')) + (result,) = list(result) + self.assertEqual(Read('xid1-x', 'AT'), result) + class TestReadsInRAM(TestCase): """
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backcall==0.2.0 biopython==1.79 bz2file==0.98 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 coverage==6.2 cycler==0.11.0 -e git+https://github.com/acorg/dark-matter.git@66f246ba9417430e3f00e94ca0abc88de59a92d4#egg=dark_matter decorator==5.1.1 execnet==1.9.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 kiwisolver==1.3.1 matplotlib==3.3.4 numpy==1.19.5 packaging==21.3 parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 Pillow==8.4.0 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pycparser==2.21 pyfaidx==0.7.1 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pyzmq==25.1.2 requests==2.27.1 simplejson==3.20.1 six==1.17.0 tomli==1.2.3 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 wcwidth==0.2.13 zipp==3.6.0
name: dark-matter channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backcall==0.2.0 - biopython==1.79 - bz2file==0.98 - cffi==1.15.1 - charset-normalizer==2.0.12 - coverage==6.2 - cycler==0.11.0 - decorator==5.1.1 - execnet==1.9.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - kiwisolver==1.3.1 - matplotlib==3.3.4 - numpy==1.19.5 - packaging==21.3 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==8.4.0 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pycparser==2.21 - pyfaidx==0.7.1 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pyzmq==25.1.2 - requests==2.27.1 - simplejson==3.20.1 - six==1.17.0 - tomli==1.2.3 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/dark-matter
[ "test/test_reads.py::TestReadsFiltering::testIdLambda", "test/test_reads.py::TestReadsFiltering::testIdLambdaReturningNone", "test/test_reads.py::TestReadsFiltering::testReadLambda", "test/test_reads.py::TestReadsFiltering::testReadLambdaReturningNone" ]
[ "test/test_reads.py::TestReadsInRAM::testFastaFile" ]
[ "test/test_reads.py::TestRead::testCasePreservation", "test/test_reads.py::TestRead::testCheckAlphabetAAReadMatchingReturnTrue", "test/test_reads.py::TestRead::testCheckAlphabetAAReadNotMatchingRaise", "test/test_reads.py::TestRead::testCheckAlphabetDNAReadMatchingReturnTrue", "test/test_reads.py::TestRead::testCheckAlphabetDNAReadNotMatchingRaise", "test/test_reads.py::TestRead::testCheckAlphabetwithReadMustBePermissive", "test/test_reads.py::TestRead::testEquality", "test/test_reads.py::TestRead::testEqualityWithDifferingIds", "test/test_reads.py::TestRead::testEqualityWithDifferingQuality", "test/test_reads.py::TestRead::testEqualityWithDifferingSequences", "test/test_reads.py::TestRead::testEqualityWithNoQuality", "test/test_reads.py::TestRead::testEqualityWithOneOmittedQuality", "test/test_reads.py::TestRead::testExpectedAttributes", "test/test_reads.py::TestRead::testFromDict", "test/test_reads.py::TestRead::testFromDictNoQuality", "test/test_reads.py::TestRead::testGetitemFullCopy", "test/test_reads.py::TestRead::testGetitemId", "test/test_reads.py::TestRead::testGetitemLength", "test/test_reads.py::TestRead::testGetitemQuality", "test/test_reads.py::TestRead::testGetitemReturnsNewRead", "test/test_reads.py::TestRead::testGetitemReversed", "test/test_reads.py::TestRead::testGetitemSequence", "test/test_reads.py::TestRead::testGetitemSingleIndex", "test/test_reads.py::TestRead::testGetitemWithStep", "test/test_reads.py::TestRead::testHashDiffersIfIdDiffers", "test/test_reads.py::TestRead::testHashDiffersIfQualityDiffers", "test/test_reads.py::TestRead::testHashDiffersIfSequenceDiffers", "test/test_reads.py::TestRead::testHashIdenticalNoQuality", "test/test_reads.py::TestRead::testHashIdenticalWithQuality", "test/test_reads.py::TestRead::testHashViaDict", "test/test_reads.py::TestRead::testHashViaSet", "test/test_reads.py::TestRead::testKeepSites", "test/test_reads.py::TestRead::testKeepSitesAllSites", "test/test_reads.py::TestRead::testKeepSitesNoSites", "test/test_reads.py::TestRead::testKeepSitesOutOfRange", "test/test_reads.py::TestRead::testKeepSitesWithQuality", "test/test_reads.py::TestRead::testLength", "test/test_reads.py::TestRead::testLowComplexityFraction", "test/test_reads.py::TestRead::testLowComplexityFractionEmptySequence", "test/test_reads.py::TestRead::testLowComplexityFractionOne", "test/test_reads.py::TestRead::testLowComplexityFractionZero", "test/test_reads.py::TestRead::testNoQuality", "test/test_reads.py::TestRead::testRemoveSites", "test/test_reads.py::TestRead::testRemoveSitesAllSites", "test/test_reads.py::TestRead::testRemoveSitesNoSites", "test/test_reads.py::TestRead::testRemoveSitesOutOfRange", "test/test_reads.py::TestRead::testRemoveSitesWithQuality", "test/test_reads.py::TestRead::testToDict", "test/test_reads.py::TestRead::testToDictNoQuality", "test/test_reads.py::TestRead::testToFASTA", "test/test_reads.py::TestRead::testToFASTAWithQuality", "test/test_reads.py::TestRead::testToFASTQ", "test/test_reads.py::TestRead::testToFASTQWithNoQuality", "test/test_reads.py::TestRead::testToUnknownFormat", "test/test_reads.py::TestRead::testUnequalLengths", "test/test_reads.py::TestRead::testWalkHSPExactMatch", "test/test_reads.py::TestRead::testWalkHSPExactMatchWithGap", "test/test_reads.py::TestRead::testWalkHSPLeftAndRightOverhangingMatch", "test/test_reads.py::TestRead::testWalkHSPLeftAndRightOverhangingMatchNoWhiskers", "test/test_reads.py::TestRead::testWalkHSPLeftOverhangingMatch", "test/test_reads.py::TestRead::testWalkHSPLeftOverhangingMatchNoWhiskers", "test/test_reads.py::TestRead::testWalkHSPRightOverhangingMatch", "test/test_reads.py::TestRead::testWalkHSPRightOverhangingMatchNoWhiskers", "test/test_reads.py::TestDNARead::testGetitemReturnsNewDNARead", "test/test_reads.py::TestDNARead::testReverseComplement", "test/test_reads.py::TestDNARead::testReverseComplementAmbiguous", "test/test_reads.py::TestDNARead::testReverseComplementReversesQuality", "test/test_reads.py::TestDNARead::testTranslationOfMultipleStopCodons", "test/test_reads.py::TestDNARead::testTranslationOfStartCodonATG", "test/test_reads.py::TestDNARead::testTranslationOfStopCodonTAG", "test/test_reads.py::TestDNARead::testTranslationOfStopCodonTGA", "test/test_reads.py::TestDNARead::testTranslations", "test/test_reads.py::TestDNARead::testTranslationsOfEmptySequence", "test/test_reads.py::TestDNARead::testTranslationsOfOneBaseSequence", "test/test_reads.py::TestDNARead::testTranslationsOfTwoBaseSequence", "test/test_reads.py::TestRNARead::testGetitemReturnsNewRNARead", "test/test_reads.py::TestRNARead::testReverseComplement", "test/test_reads.py::TestRNARead::testReverseComplementAmbiguous", "test/test_reads.py::TestRNARead::testTranslationOfStopCodonUAA", "test/test_reads.py::TestAARead::testCloseCloseORF", "test/test_reads.py::TestAARead::testCloseCloseThenCloseCloseORF", "test/test_reads.py::TestAARead::testCloseCloseThenCloseCloseThenCloseCloseORF", "test/test_reads.py::TestAARead::testCloseCloseThenCloseCloseThenCloseCloseORFWithJunk", "test/test_reads.py::TestAARead::testCloseCloseThenCloseCloseThenCloseOpenORF", "test/test_reads.py::TestAARead::testCloseCloseThenCloseCloseThenCloseOpenORFWithJunk", "test/test_reads.py::TestAARead::testCloseCloseThenCloseOpenORF", "test/test_reads.py::TestAARead::testCloseOpenORF", "test/test_reads.py::TestAARead::testCloseOpenORFWithMultipleStarts", "test/test_reads.py::TestAARead::testGetitemReturnsNewAARead", "test/test_reads.py::TestAARead::testNoStartCodon_GithubIssue239", "test/test_reads.py::TestAARead::testORFsEmptySequence", "test/test_reads.py::TestAARead::testORFsEmptySequenceWithStart", "test/test_reads.py::TestAARead::testORFsEmptySequenceWithStartStop", "test/test_reads.py::TestAARead::testORFsWithJustStartsAndStops", "test/test_reads.py::TestAARead::testORFsWithOneStopCodon", "test/test_reads.py::TestAARead::testORFsWithTwoStopCodons", "test/test_reads.py::TestAARead::testOpenCloseORF", "test/test_reads.py::TestAARead::testOpenCloseORFWithMultipleStops", "test/test_reads.py::TestAARead::testOpenCloseThenCloseCloseThenCloseOpenORF", "test/test_reads.py::TestAARead::testOpenCloseThenCloseCloseThenCloseOpenORFWithJunk", "test/test_reads.py::TestAARead::testOpenCloseThenCloseOpenORF", "test/test_reads.py::TestAARead::testOpenOpenORF", "test/test_reads.py::TestAARead::testPropertiesCorrectTranslation", "test/test_reads.py::TestAARead::testPropertyDetailsCorrectTranslation", "test/test_reads.py::TestAAReadWithX::testAlphabet", "test/test_reads.py::TestAAReadWithX::testAlphabetChecking", "test/test_reads.py::TestAAReadWithX::testGetitemReturnsNewAAReadWithX", "test/test_reads.py::TestAAReadORF::testClosedClosedId", "test/test_reads.py::TestAAReadORF::testClosedOpenId", "test/test_reads.py::TestAAReadORF::testFromDict", "test/test_reads.py::TestAAReadORF::testOpenClosedId", "test/test_reads.py::TestAAReadORF::testOpenLeft", "test/test_reads.py::TestAAReadORF::testOpenOpenId", "test/test_reads.py::TestAAReadORF::testOpenRight", "test/test_reads.py::TestAAReadORF::testSequence", "test/test_reads.py::TestAAReadORF::testStart", "test/test_reads.py::TestAAReadORF::testStartGreaterThanStop", "test/test_reads.py::TestAAReadORF::testStartNegative", "test/test_reads.py::TestAAReadORF::testStop", "test/test_reads.py::TestAAReadORF::testStopGreaterThanOriginalSequenceLength", "test/test_reads.py::TestAAReadORF::testToDict", "test/test_reads.py::TestSSAARead::testCorrectAttributes", "test/test_reads.py::TestSSAARead::testFromDict", "test/test_reads.py::TestSSAARead::testGetitemFullCopy", "test/test_reads.py::TestSSAARead::testGetitemId", "test/test_reads.py::TestSSAARead::testGetitemLength", "test/test_reads.py::TestSSAARead::testGetitemReturnsNewRead", "test/test_reads.py::TestSSAARead::testGetitemReversed", "test/test_reads.py::TestSSAARead::testGetitemSequence", "test/test_reads.py::TestSSAARead::testGetitemSingleIndex", "test/test_reads.py::TestSSAARead::testGetitemStructure", "test/test_reads.py::TestSSAARead::testGetitemWithStep", "test/test_reads.py::TestSSAARead::testHashDiffersIfIdDiffers", "test/test_reads.py::TestSSAARead::testHashDiffersIfSequenceDiffers", "test/test_reads.py::TestSSAARead::testHashDiffersIfStructureDiffers", "test/test_reads.py::TestSSAARead::testHashViaDict", "test/test_reads.py::TestSSAARead::testHashViaSet", "test/test_reads.py::TestSSAARead::testKeepSites", "test/test_reads.py::TestSSAARead::testKeepSitesAllSites", "test/test_reads.py::TestSSAARead::testKeepSitesNoSites", "test/test_reads.py::TestSSAARead::testKeepSitesOutOfRange", "test/test_reads.py::TestSSAARead::testReads", "test/test_reads.py::TestSSAARead::testRemoveSites", "test/test_reads.py::TestSSAARead::testRemoveSitesAllSites", "test/test_reads.py::TestSSAARead::testRemoveSitesNoSites", "test/test_reads.py::TestSSAARead::testRemoveSitesOutOfRange", "test/test_reads.py::TestSSAARead::testSequenceLengthMatchesStructureLength", "test/test_reads.py::TestSSAARead::testToDict", "test/test_reads.py::TestSSAARead::testToString", "test/test_reads.py::TestSSAARead::testToStringWithExplicitFastaFormat", "test/test_reads.py::TestSSAARead::testToStringWithExplicitFastaSSFormat", "test/test_reads.py::TestSSAARead::testToStringWithStructureSuffix", "test/test_reads.py::TestSSAARead::testToStringWithUnknownFormat", "test/test_reads.py::TestSSAAReadWithX::testCorrectAttributes", "test/test_reads.py::TestSSAAReadWithX::testFromDict", "test/test_reads.py::TestSSAAReadWithX::testGetitemFullCopy", "test/test_reads.py::TestSSAAReadWithX::testGetitemId", "test/test_reads.py::TestSSAAReadWithX::testGetitemLength", "test/test_reads.py::TestSSAAReadWithX::testGetitemReturnsNewRead", "test/test_reads.py::TestSSAAReadWithX::testGetitemReversed", "test/test_reads.py::TestSSAAReadWithX::testGetitemSequence", "test/test_reads.py::TestSSAAReadWithX::testGetitemSingleIndex", "test/test_reads.py::TestSSAAReadWithX::testGetitemStructure", "test/test_reads.py::TestSSAAReadWithX::testGetitemWithStep", "test/test_reads.py::TestSSAAReadWithX::testHashDiffersIfIdDiffers", "test/test_reads.py::TestSSAAReadWithX::testHashDiffersIfSequenceDiffers", "test/test_reads.py::TestSSAAReadWithX::testHashDiffersIfStructureDiffers", "test/test_reads.py::TestSSAAReadWithX::testHashViaDict", "test/test_reads.py::TestSSAAReadWithX::testHashViaSet", "test/test_reads.py::TestSSAAReadWithX::testKeepSites", "test/test_reads.py::TestSSAAReadWithX::testKeepSitesAllSites", "test/test_reads.py::TestSSAAReadWithX::testKeepSitesNoSites", "test/test_reads.py::TestSSAAReadWithX::testKeepSitesOutOfRange", "test/test_reads.py::TestSSAAReadWithX::testReads", "test/test_reads.py::TestSSAAReadWithX::testRemoveSites", "test/test_reads.py::TestSSAAReadWithX::testRemoveSitesAllSites", "test/test_reads.py::TestSSAAReadWithX::testRemoveSitesNoSites", "test/test_reads.py::TestSSAAReadWithX::testRemoveSitesOutOfRange", "test/test_reads.py::TestSSAAReadWithX::testSequenceContainingX", "test/test_reads.py::TestSSAAReadWithX::testSequenceLengthMatchesStructureLength", "test/test_reads.py::TestSSAAReadWithX::testToDict", "test/test_reads.py::TestSSAAReadWithX::testToString", "test/test_reads.py::TestSSAAReadWithX::testToStringWithExplicitFastaFormat", "test/test_reads.py::TestSSAAReadWithX::testToStringWithExplicitFastaSSFormat", "test/test_reads.py::TestSSAAReadWithX::testToStringWithStructureSuffix", "test/test_reads.py::TestSSAAReadWithX::testToStringWithUnknownFormat", "test/test_reads.py::TestTranslatedRead::testExpectedAttributes", "test/test_reads.py::TestTranslatedRead::testExpectedFrame", "test/test_reads.py::TestTranslatedRead::testFromDict", "test/test_reads.py::TestTranslatedRead::testId", "test/test_reads.py::TestTranslatedRead::testIdReverseComplemented", "test/test_reads.py::TestTranslatedRead::testMaximumORFLength", "test/test_reads.py::TestTranslatedRead::testMaximumORFLengthNoStops", "test/test_reads.py::TestTranslatedRead::testOutOfRangeFrame", "test/test_reads.py::TestTranslatedRead::testReverseComplemented", "test/test_reads.py::TestTranslatedRead::testSequence", "test/test_reads.py::TestTranslatedRead::testToDict", "test/test_reads.py::TestReadClassNameToClass::testNames", "test/test_reads.py::TestReads::testEmptyInitialReads", "test/test_reads.py::TestReads::testInitialReads", "test/test_reads.py::TestReads::testManuallyAddedReads", "test/test_reads.py::TestReads::testManuallyAddedReadsLength", "test/test_reads.py::TestReads::testNoReads", "test/test_reads.py::TestReads::testNoReadsLength", "test/test_reads.py::TestReads::testRepeatedIter", "test/test_reads.py::TestReads::testSaveAsFASTA", "test/test_reads.py::TestReads::testSaveAsFASTQ", "test/test_reads.py::TestReads::testSaveAsFASTQFailsOnReadWithNoQuality", "test/test_reads.py::TestReads::testSaveFASTAIsDefault", "test/test_reads.py::TestReads::testSaveReturnsReadCount", "test/test_reads.py::TestReads::testSaveToFileDescriptor", "test/test_reads.py::TestReads::testSaveWithUnknownFormat", "test/test_reads.py::TestReads::testSaveWithUppercaseFormat", "test/test_reads.py::TestReads::testSubclass", "test/test_reads.py::TestReads::testSubclassLength", "test/test_reads.py::TestReads::testSubclassWithAdditionalReads", "test/test_reads.py::TestReads::testUnfilteredLengthAdditionalReads", "test/test_reads.py::TestReads::testUnfilteredLengthAdditionalReadsAfterFiltering", "test/test_reads.py::TestReads::testUnfilteredLengthBeforeIterating", "test/test_reads.py::TestReads::testUnfilteredLengthInitialReads", "test/test_reads.py::TestReads::testUnfilteredLengthInitialReadsAfterFiltering", "test/test_reads.py::TestReads::testUnfilteredLengthInitialReadsIsReads", "test/test_reads.py::TestReads::testUnfilteredLengthInitialReadsIsReadsWithAdditional", "test/test_reads.py::TestReads::testUnfilteredLengthInitialSubclassThenFiltered", "test/test_reads.py::TestReads::testUnfilteredLengthInitialSubclassWithAdditionalThenFiltered", "test/test_reads.py::TestReads::testUnfilteredLengthInitialSubclassWithNoLen", "test/test_reads.py::TestReads::testUnfilteredLengthNoReads", "test/test_reads.py::TestReadsFiltering::testAddFiltersThenClearFilters", "test/test_reads.py::TestReadsFiltering::testFilterBlacklist", "test/test_reads.py::TestReadsFiltering::testFilterDoNotRemoveDescriptions", "test/test_reads.py::TestReadsFiltering::testFilterDuplicates", "test/test_reads.py::TestReadsFiltering::testFilterDuplicatesById", "test/test_reads.py::TestReadsFiltering::testFilterHead", "test/test_reads.py::TestReadsFiltering::testFilterHeadZero", "test/test_reads.py::TestReadsFiltering::testFilterKeepSequences", "test/test_reads.py::TestReadsFiltering::testFilterKeepSequencesNoSequences", "test/test_reads.py::TestReadsFiltering::testFilterNegativeRegex", "test/test_reads.py::TestReadsFiltering::testFilterNoArgs", "test/test_reads.py::TestReadsFiltering::testFilterOnLengthEverythingMatches", "test/test_reads.py::TestReadsFiltering::testFilterOnLengthNothingMatches", "test/test_reads.py::TestReadsFiltering::testFilterOnMaxLength", "test/test_reads.py::TestReadsFiltering::testFilterOnMinLength", "test/test_reads.py::TestReadsFiltering::testFilterPositiveRegex", "test/test_reads.py::TestReadsFiltering::testFilterRandomSubsetOfFiveFromFiveReads", "test/test_reads.py::TestReadsFiltering::testFilterRandomSubsetOfFiveFromOneRead", "test/test_reads.py::TestReadsFiltering::testFilterRandomSubsetOfOneFromOneRead", "test/test_reads.py::TestReadsFiltering::testFilterRandomSubsetOfTwoFromFiveReads", "test/test_reads.py::TestReadsFiltering::testFilterRandomSubsetOfZeroReads", "test/test_reads.py::TestReadsFiltering::testFilterRandomSubsetSizeZeroNoReads", "test/test_reads.py::TestReadsFiltering::testFilterRandomSubsetSizeZeroTwoReads", "test/test_reads.py::TestReadsFiltering::testFilterRemoveDescriptions", "test/test_reads.py::TestReadsFiltering::testFilterRemoveGaps", "test/test_reads.py::TestReadsFiltering::testFilterRemoveGapsWithQuality", "test/test_reads.py::TestReadsFiltering::testFilterRemoveSequences", "test/test_reads.py::TestReadsFiltering::testFilterRemoveSequencesNoSequences", "test/test_reads.py::TestReadsFiltering::testFilterReturnsReadInstance", "test/test_reads.py::TestReadsFiltering::testFilterTruncateTitles", "test/test_reads.py::TestReadsFiltering::testFilterWhitelist", "test/test_reads.py::TestReadsFiltering::testFilterWithMinLengthEqualToMaxLength", "test/test_reads.py::TestReadsFiltering::testFilterWithModifierThatChangesIds", "test/test_reads.py::TestReadsFiltering::testFilterWithModifierThatOmits", "test/test_reads.py::TestReadsFiltering::testFilterWithModifierThatOmitsAndChangesIds", "test/test_reads.py::TestReadsFiltering::testFilteredReadsInstanceHasExpectedLength", "test/test_reads.py::TestReadsFiltering::testKeepSites", "test/test_reads.py::TestReadsFiltering::testKeepSitesAllSites", "test/test_reads.py::TestReadsFiltering::testKeepSitesNoSites", "test/test_reads.py::TestReadsFiltering::testKeepSitesOutOfRange", "test/test_reads.py::TestReadsFiltering::testKeepSitesWithQuality", "test/test_reads.py::TestReadsFiltering::testLineNumberFile", "test/test_reads.py::TestReadsFiltering::testLineNumberFileEmpty", "test/test_reads.py::TestReadsFiltering::testLineNumberFileFirstLineTooSmall", "test/test_reads.py::TestReadsFiltering::testLineNumberFileNonAscending", "test/test_reads.py::TestReadsFiltering::testLineNumberFileRunOutOfSequences", "test/test_reads.py::TestReadsFiltering::testRemoveAndKeepSites", "test/test_reads.py::TestReadsFiltering::testRemoveSites", "test/test_reads.py::TestReadsFiltering::testRemoveSitesAllSites", "test/test_reads.py::TestReadsFiltering::testRemoveSitesNoSites", "test/test_reads.py::TestReadsFiltering::testRemoveSitesOutOfRange", "test/test_reads.py::TestReadsFiltering::testRemoveSitesWithQuality", "test/test_reads.py::TestReadsFiltering::testSampleFractionAndNoTrueLengthRaisesValueError", "test/test_reads.py::TestReadsFiltering::testSampleFractionAndRandomSubsetRaisesValueError", "test/test_reads.py::TestReadsFiltering::testSampleFractionOne", "test/test_reads.py::TestReadsFiltering::testSampleFractionPointOne", "test/test_reads.py::TestReadsFiltering::testSampleFractionZero", "test/test_reads.py::TestReadsInRAM::testAdd", "test/test_reads.py::TestReadsInRAM::testFromReads", "test/test_reads.py::TestReadsInRAM::testNoReads", "test/test_reads.py::TestReadsInRAM::testOneReadIndex", "test/test_reads.py::TestReadsInRAM::testOneReadLength", "test/test_reads.py::TestReadsInRAM::testOneReadList", "test/test_reads.py::TestReadsInRAM::testSetItem", "test/test_reads.py::TestReadsInRAM::testTwoReadsIndex", "test/test_reads.py::TestReadsInRAM::testTwoReadsLength", "test/test_reads.py::TestReadsInRAM::testTwoReadsList", "test/test_reads.py::TestSummarizePosition::testCorrectFrequencies", "test/test_reads.py::TestSummarizePosition::testExcludeShortSequences", "test/test_reads.py::TestSummarizePosition::testFrequenciesNoReads", "test/test_reads.py::TestSummarizePosition::testIndexLargerThanSequenceLength", "test/test_reads.py::TestSummarizePosition::testNumberOfExclusionsNoReads", "test/test_reads.py::TestSitesMatching::testAllMatches", "test/test_reads.py::TestSitesMatching::testIgnoreCase", "test/test_reads.py::TestSitesMatching::testMatchCase", "test/test_reads.py::TestSitesMatching::testMultipleReadsAll", "test/test_reads.py::TestSitesMatching::testMultipleReadsAllWithDifferingLengths", "test/test_reads.py::TestSitesMatching::testMultipleReadsAny", "test/test_reads.py::TestSitesMatching::testMultipleReadsAnyWithDifferingLengths", "test/test_reads.py::TestSitesMatching::testNoMatches", "test/test_reads.py::TestSitesMatching::testPartialMatch" ]
[]
MIT License
2,592
[ "dark/__init__.py", "dark/filter.py", "dark/reads.py" ]
[ "dark/__init__.py", "dark/filter.py", "dark/reads.py" ]
Stewori__pytypes-47
f8e2f14786872f0e2e17507139a4e72be58a1102
2018-05-28 02:26:16
f8e2f14786872f0e2e17507139a4e72be58a1102
diff --git a/pytypes/typelogger.py b/pytypes/typelogger.py index 078b521..3b3c774 100644 --- a/pytypes/typelogger.py +++ b/pytypes/typelogger.py @@ -146,7 +146,7 @@ def combine_argtype(observations): additional unification effort (e.g. can apply PEP 484 style numeric tower). """ assert len(observations) > 0 - assert isinstance(is_Tuple(observations[0])) + assert is_Tuple(observations[0]) if len(observations) > 1: prms = [get_Tuple_params(observations[0])] ln = len(prms[0])
TypeError: isinstance expected 2 arguments, got 1 Running [Usage example with decorator](https://github.com/Stewori/pytypes#usage-example-with-decorator) in readme gave following error for me. ``` Traceback (most recent call last): File "/tmp/tmp.py", line 31, in <module> pytypes.dump_cache() NameError: name 'pytypes' is not defined Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/Users/qria/.venvs/jupyter2/lib/python3.6/site-packages/pytypes/typelogger.py", line 316, in _dump_module assumed_glbls, implicit_globals, assumed_typevars) File "/Users/qria/.venvs/jupyter2/lib/python3.6/site-packages/pytypes/typelogger.py", line 755, in dump assumed_globals, implicit_globals, assumed_typevars) File "/Users/qria/.venvs/jupyter2/lib/python3.6/site-packages/pytypes/typelogger.py", line 680, in dump assumed_globals, implicit_globals)) File "/Users/qria/.venvs/jupyter2/lib/python3.6/site-packages/pytypes/typelogger.py", line 653, in _stub_src_annotations assumed_globals, implicit_globals), ' ...'] File "/Users/qria/.venvs/jupyter2/lib/python3.6/site-packages/pytypes/typelogger.py", line 625, in _declaration if annotated else self._signature(), ':')) File "/Users/qria/.venvs/jupyter2/lib/python3.6/site-packages/pytypes/typelogger.py", line 597, in _annotated_signature tp_lst = _prepare_arg_types_list(combine_argtype(self.arg_type_observations), File "/Users/qria/.venvs/jupyter2/lib/python3.6/site-packages/pytypes/typelogger.py", line 149, in combine_argtype assert isinstance(is_Tuple(observations[0])) TypeError: isinstance expected 2 arguments, got 1 ``` I don't know much about this codebase but maybe you've intended `assert is_Tuple(observations[0])`? versions: pytypes==1.0b4
Stewori/pytypes
diff --git a/tests/test_typechecker.py b/tests/test_typechecker.py index 7fb1565..7051409 100644 --- a/tests/test_typechecker.py +++ b/tests/test_typechecker.py @@ -4734,5 +4734,38 @@ class Test_utils(unittest.TestCase): self.assertFalse(pytypes.is_subtype(list, Wrapper)) +class Test_combine_argtype(unittest.TestCase): + def test_exceptions(self): + # Empty observations not allowed + with self.assertRaises(AssertionError): + pytypes.typelogger.combine_argtype([]) + + # Non tuple types not allowed + with self.assertRaises(AssertionError): + notTuple = typing.List[int] + pytypes.typelogger.combine_argtype([notTuple]) + + with self.assertRaises(AssertionError): + notTuple = typing.List[int] + pytypes.typelogger.combine_argtype([typing.Tuple[int], notTuple]) + + def test_function(self): + # If single observation is supplied it should return itself + self.assertEqual( + pytypes.typelogger.combine_argtype([typing.Tuple[int]]), + typing.Tuple[int], + ) + # Observations should be unioned + self.assertEqual( + pytypes.typelogger.combine_argtype([typing.Tuple[int], typing.Tuple[str]]), + typing.Tuple[typing.Union[int, str]], + ) + # Number classes should be combined as PEP 484 style numeric tower + self.assertEqual( + pytypes.typelogger.combine_argtype([typing.Tuple[int], typing.Tuple[float]]), + typing.Tuple[float], + ) + + if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.04
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "flake8" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 flake8==5.0.4 importlib-metadata==4.2.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pycodestyle==2.9.1 pyflakes==2.5.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 -e git+https://github.com/Stewori/pytypes.git@f8e2f14786872f0e2e17507139a4e72be58a1102#egg=pytypes toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: pytypes channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - flake8==5.0.4 - importlib-metadata==4.2.0 - mccabe==0.7.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 prefix: /opt/conda/envs/pytypes
[ "tests/test_typechecker.py::Test_combine_argtype::test_exceptions", "tests/test_typechecker.py::Test_combine_argtype::test_function" ]
[ "tests/test_typechecker.py::testfunc", "tests/test_typechecker.py::testfunc_err", "tests/test_typechecker.py::testfunc2", "tests/test_typechecker.py::testfunc4", "tests/test_typechecker.py::testfunc_None_ret", "tests/test_typechecker.py::testfunc_None_ret_err", "tests/test_typechecker.py::testfunc_None_arg", "tests/test_typechecker.py::testfunc_Dict_arg", "tests/test_typechecker.py::testfunc_Mapping_arg", "tests/test_typechecker.py::testfunc_Dict_ret", "tests/test_typechecker.py::testfunc_Dict_ret_err", "tests/test_typechecker.py::testfunc_Seq_arg", "tests/test_typechecker.py::testfunc_Seq_ret_List", "tests/test_typechecker.py::testfunc_Seq_ret_Tuple", "tests/test_typechecker.py::testfunc_Seq_ret_err", "tests/test_typechecker.py::testfunc_Iter_arg", "tests/test_typechecker.py::testfunc_Iter_str_arg", "tests/test_typechecker.py::testfunc_Iter_ret_err", "tests/test_typechecker.py::testfunc_Callable_arg", "tests/test_typechecker.py::testfunc_Callable_call_err", "tests/test_typechecker.py::testfunc_Callable_ret", "tests/test_typechecker.py::testfunc_Callable_ret_err", "tests/test_typechecker.py::testfunc_Generator_arg", "tests/test_typechecker.py::testfunc_Generator_ret", "tests/test_typechecker.py::testfunc_Generic_arg", "tests/test_typechecker.py::testfunc_Generic_ret", "tests/test_typechecker.py::testfunc_Generic_ret_err", "tests/test_typechecker.py::testfunc_numeric_tower_float", "tests/test_typechecker.py::testfunc_numeric_tower_complex", "tests/test_typechecker.py::testfunc_numeric_tower_tuple", "tests/test_typechecker.py::testfunc_numeric_tower_return", "tests/test_typechecker.py::testfunc_numeric_tower_return_err", "tests/test_typechecker.py::testfunc_custom_annotations_typechecked", "tests/test_typechecker.py::testfunc_custom_annotations_typechecked_err", "tests/test_typechecker.py::testfunc_varargs2", "tests/test_typechecker.py::testfunc_varargs3", "tests/test_typechecker.py::testfunc_varargs5", "tests/test_typechecker.py::testfunc_varargs_err", "tests/test_typechecker.py::testfunc_varargs_ca3" ]
[ "tests/test_typechecker.py::testfunc_Iter_ret", "tests/test_typechecker.py::testfunc_Generator", "tests/test_typechecker.py::testfunc_varargs1", "tests/test_typechecker.py::testfunc_varargs4", "tests/test_typechecker.py::testClass2_defTimeCheck", "tests/test_typechecker.py::testClass2_defTimeCheck2", "tests/test_typechecker.py::testClass2_defTimeCheck3", "tests/test_typechecker.py::testClass2_defTimeCheck4", "tests/test_typechecker.py::testClass3_defTimeCheck", "tests/test_typechecker.py::testClass2_defTimeCheck_init_ov", "tests/test_typechecker.py::testfunc_check_argument_types_empty", "tests/test_typechecker.py::testfunc_varargs_ca1", "tests/test_typechecker.py::testfunc_varargs_ca4", "tests/test_typechecker.py::TestTypecheck::test_abstract_override", "tests/test_typechecker.py::TestTypecheck::test_annotations_from_typestring", "tests/test_typechecker.py::TestTypecheck::test_callable", "tests/test_typechecker.py::TestTypecheck::test_classmethod", "tests/test_typechecker.py::TestTypecheck::test_custom_annotations", "tests/test_typechecker.py::TestTypecheck::test_custom_generic", "tests/test_typechecker.py::TestTypecheck::test_defaults_inferred_types", "tests/test_typechecker.py::TestTypecheck::test_dict", "tests/test_typechecker.py::TestTypecheck::test_empty", "tests/test_typechecker.py::TestTypecheck::test_function", "tests/test_typechecker.py::TestTypecheck::test_generator", "tests/test_typechecker.py::TestTypecheck::test_get_generic_parameters", "tests/test_typechecker.py::TestTypecheck::test_get_types", "tests/test_typechecker.py::TestTypecheck::test_iterable", "tests/test_typechecker.py::TestTypecheck::test_method", "tests/test_typechecker.py::TestTypecheck::test_method_forward", "tests/test_typechecker.py::TestTypecheck::test_numeric_tower", "tests/test_typechecker.py::TestTypecheck::test_parent_typecheck_no_override", "tests/test_typechecker.py::TestTypecheck::test_parent_typecheck_other_signature", "tests/test_typechecker.py::TestTypecheck::test_property", "tests/test_typechecker.py::TestTypecheck::test_sequence", "tests/test_typechecker.py::TestTypecheck::test_staticmethod", "tests/test_typechecker.py::TestTypecheck::test_subtype_class_extends_generic", "tests/test_typechecker.py::TestTypecheck::test_typecheck_parent_type", "tests/test_typechecker.py::TestTypecheck::test_typestring_varargs_syntax", "tests/test_typechecker.py::TestTypecheck::test_typevar_class", "tests/test_typechecker.py::TestTypecheck::test_typevar_func", "tests/test_typechecker.py::TestTypecheck::test_unparameterized", "tests/test_typechecker.py::TestTypecheck::test_varargs", "tests/test_typechecker.py::TestTypecheck::test_varargs_check_argument_types", "tests/test_typechecker.py::TestTypecheck::test_various", "tests/test_typechecker.py::TestTypecheck_class::test_classmethod", "tests/test_typechecker.py::TestTypecheck_class::test_method", "tests/test_typechecker.py::TestTypecheck_class::test_staticmethod", "tests/test_typechecker.py::TestTypecheck_module::test_function_py2", "tests/test_typechecker.py::TestTypecheck_module::test_function_py3", "tests/test_typechecker.py::Test_check_argument_types::test_function", "tests/test_typechecker.py::Test_check_argument_types::test_inner_class", "tests/test_typechecker.py::Test_check_argument_types::test_inner_method", "tests/test_typechecker.py::Test_check_argument_types::test_methods", "tests/test_typechecker.py::TestOverride::test_auto_override", "tests/test_typechecker.py::TestOverride::test_override", "tests/test_typechecker.py::TestOverride::test_override_at_definition_time", "tests/test_typechecker.py::TestOverride::test_override_at_definition_time_with_forward_decl", "tests/test_typechecker.py::TestOverride::test_override_diamond", "tests/test_typechecker.py::TestOverride::test_override_typecheck", "tests/test_typechecker.py::TestOverride::test_override_typecheck_class", "tests/test_typechecker.py::TestOverride::test_override_vararg", "tests/test_typechecker.py::TestStubfile::test_annotations_from_stubfile_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_annotations_from_stubfile_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_callable_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_custom_generic_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_defaults_inferred_types_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_defaults_inferred_types_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_dict_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_generator_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_iterable_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_override_diamond_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_override_diamond_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_property_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_property_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_sequence_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_typecheck_parent_type_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_typecheck_parent_type_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_varargs_check_argument_types_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_varargs_check_argument_types_plain_3_5_stub", "tests/test_typechecker.py::TestStubfile::test_varargs_plain_2_7_stub", "tests/test_typechecker.py::TestStubfile::test_varargs_plain_3_5_stub", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_abstract_override_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_callable_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_classmethod_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_custom_generic_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_defaults_inferred_types", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_dict_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_function_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_generator_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_get_types_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_iterable_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_method_forward_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_method_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_parent_typecheck_no_override_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_parent_typecheck_other_signature_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_property", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_sequence_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_staticmethod_py3", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_typecheck_parent_type", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_typevar_func", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_varargs", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_varargs_check_argument_types", "tests/test_typechecker.py::TestTypecheck_Python3_5::test_various_py3", "tests/test_typechecker.py::TestOverride_Python3_5::test_auto_override", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_at_definition_time", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_at_definition_time_with_forward_decl", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_diamond", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_py3", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_typecheck", "tests/test_typechecker.py::TestOverride_Python3_5::test_override_vararg", "tests/test_typechecker.py::Test_check_argument_types_Python3_5::test_function", "tests/test_typechecker.py::Test_check_argument_types_Python3_5::test_inner_class", "tests/test_typechecker.py::Test_check_argument_types_Python3_5::test_inner_method", "tests/test_typechecker.py::Test_check_argument_types_Python3_5::test_methods", "tests/test_typechecker.py::Test_utils::test_bound_typevars_readonly", "tests/test_typechecker.py::Test_utils::test_empty_values", "tests/test_typechecker.py::Test_utils::test_forward_declaration", "tests/test_typechecker.py::Test_utils::test_forward_declaration_infinite_recursion", "tests/test_typechecker.py::Test_utils::test_frozenset", "tests/test_typechecker.py::Test_utils::test_resolve_fw_decl", "tests/test_typechecker.py::Test_utils::test_tuple_ellipsis" ]
[]
Apache License 2.0
2,593
[ "pytypes/typelogger.py" ]
[ "pytypes/typelogger.py" ]
conan-io__conan-2952
c3a6ed5dc7b5e27ac69191e36aa7592e47ce7759
2018-05-29 10:29:36
c3a6ed5dc7b5e27ac69191e36aa7592e47ce7759
diff --git a/conans/client/build/autotools_environment.py b/conans/client/build/autotools_environment.py index 924161e9c..9bf4bd3e8 100644 --- a/conans/client/build/autotools_environment.py +++ b/conans/client/build/autotools_environment.py @@ -14,6 +14,7 @@ from conans.client.tools.win import unix_path from conans.tools import (environment_append, args_to_string, cpu_count, cross_building, detected_architecture, get_gnu_triplet) from conans.errors import ConanException +from conans.util.files import get_abs_path class AutoToolsBuildEnvironment(object): @@ -131,7 +132,9 @@ class AutoToolsBuildEnvironment(object): triplet_args.append("--target=%s" % (target or self.target)) if pkg_config_paths: - pkg_env = {"PKG_CONFIG_PATH": os.pathsep.join(pkg_config_paths)} + pkg_env = {"PKG_CONFIG_PATH": + os.pathsep.join(get_abs_path(f, self._conanfile.install_folder) + for f in pkg_config_paths)} else: # If we are using pkg_config generator automate the pcs location, otherwise it could # read wrong files diff --git a/conans/client/build/cmake.py b/conans/client/build/cmake.py index 9964d0836..b5f8cb843 100644 --- a/conans/client/build/cmake.py +++ b/conans/client/build/cmake.py @@ -12,7 +12,7 @@ from conans.errors import ConanException from conans.model.conan_file import ConanFile from conans.model.version import Version from conans.util.env_reader import get_env -from conans.util.files import mkdir +from conans.util.files import mkdir, get_abs_path from conans.tools import cpu_count, args_to_string from conans import tools from conans.util.log import logger @@ -28,7 +28,8 @@ def _get_env_cmake_system_name(): class CMake(object): def __init__(self, conanfile, generator=None, cmake_system_name=True, - parallel=True, build_type=None, toolset=None, make_program=None, set_cmake_flags=False): + parallel=True, build_type=None, toolset=None, make_program=None, + set_cmake_flags=False): """ :param settings_or_conanfile: Conanfile instance (or settings for retro compatibility) :param generator: Generator name to use or none to autodetect @@ -370,7 +371,8 @@ class CMake(object): self._conanfile.run(command) def configure(self, args=None, defs=None, source_dir=None, build_dir=None, - source_folder=None, build_folder=None, cache_build_folder=None): + source_folder=None, build_folder=None, cache_build_folder=None, + pkg_config_paths=None): # TODO: Deprecate source_dir and build_dir in favor of xxx_folder if not self._conanfile.should_configure: @@ -387,12 +389,26 @@ class CMake(object): defs_to_string(defs), args_to_string([source_dir]) ]) - command = "cd %s && cmake %s" % (args_to_string([self.build_dir]), arg_list) - if platform.system() == "Windows" and self.generator == "MinGW Makefiles": - with tools.remove_from_path("sh"): - self._run(command) + + + if pkg_config_paths: + pkg_env = {"PKG_CONFIG_PATH": + os.pathsep.join(get_abs_path(f, self._conanfile.install_folder) + for f in pkg_config_paths)} else: - self._run(command) + # If we are using pkg_config generator automate the pcs location, otherwise it could + # read wrong files + set_env = "pkg_config" in self._conanfile.generators \ + and "PKG_CONFIG_PATH" not in os.environ + pkg_env = {"PKG_CONFIG_PATH": self._conanfile.install_folder} if set_env else {} + + with tools.environment_append(pkg_env): + command = "cd %s && cmake %s" % (args_to_string([self.build_dir]), arg_list) + if platform.system() == "Windows" and self.generator == "MinGW Makefiles": + with tools.remove_from_path("sh"): + self._conanfile.run(command) + else: + self._conanfile.run(command) def build(self, args=None, build_dir=None, target=None): if not self._conanfile.should_build: diff --git a/conans/client/build/meson.py b/conans/client/build/meson.py index 1545a59d7..b8a7ff4b3 100644 --- a/conans/client/build/meson.py +++ b/conans/client/build/meson.py @@ -4,7 +4,7 @@ from conans import tools from conans.client import join_arguments, defs_to_string from conans.errors import ConanException from conans.tools import args_to_string -from conans.util.files import mkdir +from conans.util.files import mkdir, get_abs_path class Meson(object): @@ -53,14 +53,6 @@ class Meson(object): def build_folder(self, value): self.build_dir = value - @staticmethod - def _get_dir(folder, origin): - if folder: - if os.path.isabs(folder): - return folder - return os.path.join(origin, folder) - return origin - def _get_dirs(self, source_folder, build_folder, source_dir, build_dir, cache_build_folder): if (source_folder or build_folder) and (source_dir or build_dir): raise ConanException("Use 'build_folder'/'source_folder'") @@ -69,11 +61,11 @@ class Meson(object): build_ret = build_dir or self.build_dir or self._conanfile.build_folder source_ret = source_dir or self._conanfile.source_folder else: - build_ret = self._get_dir(build_folder, self._conanfile.build_folder) - source_ret = self._get_dir(source_folder, self._conanfile.source_folder) + build_ret = get_abs_path(build_folder, self._conanfile.build_folder) + source_ret = get_abs_path(source_folder, self._conanfile.source_folder) if self._conanfile.in_local_cache and cache_build_folder: - build_ret = self._get_dir(cache_build_folder, self._conanfile.build_folder) + build_ret = get_abs_path(cache_build_folder, self._conanfile.build_folder) return source_ret, build_ret @@ -90,7 +82,7 @@ class Meson(object): cache_build_folder) if pkg_config_paths: - pc_paths = os.pathsep.join(self._get_dir(f, self._conanfile.install_folder) + pc_paths = os.pathsep.join(get_abs_path(f, self._conanfile.install_folder) for f in pkg_config_paths) else: pc_paths = self._conanfile.install_folder diff --git a/conans/util/files.py b/conans/util/files.py index d8492cd72..8c6a859a1 100644 --- a/conans/util/files.py +++ b/conans/util/files.py @@ -181,6 +181,14 @@ def relative_dirs(path): return ret +def get_abs_path(folder, origin): + if folder: + if os.path.isabs(folder): + return folder + return os.path.join(origin, folder) + return origin + + def _change_permissions(func, path, exc_info): if not os.access(path, os.W_OK): os.chmod(path, stat.S_IWUSR)
CMake build wrapper should set PKG_CONFIG_PATH - [x] I've read the [CONTRIBUTING guide](https://raw.githubusercontent.com/conan-io/conan/develop/.github/CONTRIBUTING.md). - [x] I've specified the Conan version, operating system version and any tool that can be relevant. - [x] I've explained the steps to reproduce the error or the motivation/use case of the question/suggestion. conan version 1.0.4 or master A lot of cmake scripts use both `find_package` (`FindFoo.cmake`-based) and `pkg_check_modules` (`pkg-config`-based). CMake build wrapper should automatically provide `PKG_CONFIG_PATH` env var set to build directory or to recipe-provided paths. Exact same behavior is seen in `AutoToolsBuildEnviroment` or `Meson`. `CMake` should not be an exception.
conan-io/conan
diff --git a/conans/test/build_helpers/autotools_configure_test.py b/conans/test/build_helpers/autotools_configure_test.py index fed69a0a3..9f0fcd983 100644 --- a/conans/test/build_helpers/autotools_configure_test.py +++ b/conans/test/build_helpers/autotools_configure_test.py @@ -1,16 +1,18 @@ +import os import platform import unittest +from collections import namedtuple -from conans.client.build.autotools_environment import AutoToolsBuildEnvironment from conans import tools +from conans.client.build.autotools_environment import AutoToolsBuildEnvironment from conans.client.tools.oss import cpu_count +from conans.model.ref import ConanFileReference +from conans.model.settings import Settings from conans.paths import CONANFILE -from conans.test.utils.conanfile import MockConanfile, MockSettings, MockOptions +from conans.test.build_helpers.cmake_test import ConanFileMock from conans.test.util.tools_test import RunnerMock +from conans.test.utils.conanfile import MockConanfile, MockSettings, MockOptions from conans.test.utils.tools import TestClient -from conans.test.build_helpers.cmake_test import ConanFileMock -from conans.model.settings import Settings -from collections import namedtuple class AutoToolsConfigureTest(unittest.TestCase): @@ -416,9 +418,12 @@ class HelloConan(ConanFile): self.assertIn("PKG_CONFIG_PATH=%s" % client.client_cache.conan_folder, client.out) client.save({CONANFILE: conanfile % ("'pkg_config'", - "pkg_config_paths=['/tmp/hello', '/tmp/foo']")}) + "pkg_config_paths=['/tmp/hello', 'foo']")}) client.run("create . conan/testing") - self.assertIn("PKG_CONFIG_PATH=/tmp/hello:/tmp/foo", client.out) + ref = ConanFileReference.loads("Hello/1.2.1@conan/testing") + builds_folder = client.client_cache.builds(ref) + bf = os.path.join(builds_folder, os.listdir(builds_folder)[0]) + self.assertIn("PKG_CONFIG_PATH=/tmp/hello:%s/foo" % bf, client.out) def cross_build_command_test(self): runner = RunnerMock() diff --git a/conans/test/build_helpers/cmake_test.py b/conans/test/build_helpers/cmake_test.py index 812c53444..09aab1631 100644 --- a/conans/test/build_helpers/cmake_test.py +++ b/conans/test/build_helpers/cmake_test.py @@ -688,6 +688,38 @@ build_type: [ Release] cmake.configure() self.assertNotIn(self.tempdir, conanfile.path) + def test_pkg_config_path(self): + conanfile = ConanFileMock() + conanfile.generators = ["pkg_config"] + conanfile.install_folder = "/my_install/folder/" + settings = Settings.loads(default_settings_yml) + settings.os = "Windows" + settings.compiler = "Visual Studio" + settings.compiler.version = "12" + settings.arch = "x86" + conanfile.settings = settings + cmake = CMake(conanfile) + cmake.configure() + self.assertEquals(conanfile.captured_env["PKG_CONFIG_PATH"], "/my_install/folder/") + + conanfile.generators = [] + cmake = CMake(conanfile) + cmake.configure() + self.assertNotIn("PKG_CONFIG_PATH", conanfile.captured_env) + + cmake = CMake(conanfile) + cmake.configure(pkg_config_paths=["reldir1", "/abspath2/to/other"]) + self.assertEquals(conanfile.captured_env["PKG_CONFIG_PATH"], + os.path.pathsep.join(["/my_install/folder/reldir1", + "/abspath2/to/other"])) + + # If there is already a PKG_CONFIG_PATH do not set it + conanfile.generators = ["pkg_config"] + cmake = CMake(conanfile) + with tools.environment_append({"PKG_CONFIG_PATH": "do_not_mess_with_this"}): + cmake.configure() + self.assertEquals(conanfile.captured_env["PKG_CONFIG_PATH"], "do_not_mess_with_this") + def test_shared(self): settings = Settings.loads(default_settings_yml) settings.os = "Windows" @@ -843,7 +875,10 @@ class ConanFileMock(ConanFile): self.should_configure = True self.should_build = True self.should_install = True + self.generators = [] + self.captured_env = {} def run(self, command): self.command = command self.path = os.environ["PATH"] + self.captured_env = {key: value for key, value in os.environ.items()}
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 4 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "conans/requirements.txt", "conans/requirements_osx.txt", "conans/requirements_server.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asn1crypto==1.5.1 astroid==1.6.6 attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.12.25 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 codecov==2.1.13 colorama==0.3.9 -e git+https://github.com/conan-io/conan.git@c3a6ed5dc7b5e27ac69191e36aa7592e47ce7759#egg=conan coverage==4.2 cryptography==2.1.4 deprecation==2.0.7 distro==1.1.0 fasteners==0.19 future==0.16.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==1.3.0 ndg-httpsclient==0.4.4 node-semver==0.2.0 nose==1.3.7 packaging==21.3 parameterized==0.8.1 patch==1.16 pbr==6.1.1 pluggy==1.0.0 pluginbase==0.7 py==1.11.0 pyasn==1.5.0b7 pyasn1==0.5.1 pycparser==2.21 Pygments==2.14.0 PyJWT==1.7.1 pylint==1.8.4 pyOpenSSL==17.5.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==3.12 requests==2.27.1 six==1.17.0 soupsieve==2.3.2.post1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 waitress==2.0.0 WebOb==1.8.9 WebTest==2.0.35 wrapt==1.16.0 zipp==3.6.0
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asn1crypto==1.5.1 - astroid==1.6.6 - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.12.25 - cffi==1.15.1 - charset-normalizer==2.0.12 - codecov==2.1.13 - colorama==0.3.9 - coverage==4.2 - cryptography==2.1.4 - deprecation==2.0.7 - distro==1.1.0 - fasteners==0.19 - future==0.16.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==1.3.0 - ndg-httpsclient==0.4.4 - node-semver==0.2.0 - nose==1.3.7 - packaging==21.3 - parameterized==0.8.1 - patch==1.16 - pbr==6.1.1 - pluggy==1.0.0 - pluginbase==0.7 - py==1.11.0 - pyasn==1.5.0b7 - pyasn1==0.5.1 - pycparser==2.21 - pygments==2.14.0 - pyjwt==1.7.1 - pylint==1.8.4 - pyopenssl==17.5.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==3.12 - requests==2.27.1 - six==1.17.0 - soupsieve==2.3.2.post1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - waitress==2.0.0 - webob==1.8.9 - webtest==2.0.35 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/conan
[ "conans/test/build_helpers/cmake_test.py::CMakeTest::test_pkg_config_path" ]
[ "conans/test/build_helpers/autotools_configure_test.py::AutoToolsConfigureTest::test_pkg_config_paths" ]
[ "conans/test/build_helpers/autotools_configure_test.py::AutoToolsConfigureTest::test_cppstd", "conans/test/build_helpers/autotools_configure_test.py::AutoToolsConfigureTest::test_make_targets_install", "conans/test/build_helpers/autotools_configure_test.py::AutoToolsConfigureTest::test_mocked_methods", "conans/test/build_helpers/autotools_configure_test.py::AutoToolsConfigureTest::test_previous_env", "conans/test/build_helpers/autotools_configure_test.py::AutoToolsConfigureTest::test_variables", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_clean_sh_path", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_cmake_system_version_android", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_cores_ancient_visual", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_deprecated_behaviour", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_missing_settings", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_run_tests", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_shared", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_sysroot", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_verbose" ]
[]
MIT License
2,594
[ "conans/client/build/meson.py", "conans/client/build/cmake.py", "conans/util/files.py", "conans/client/build/autotools_environment.py" ]
[ "conans/client/build/meson.py", "conans/client/build/cmake.py", "conans/util/files.py", "conans/client/build/autotools_environment.py" ]
ucfopen__canvasapi-184
6030f6bcb9de01c536617f4832caf51473195260
2018-05-29 14:44:36
6030f6bcb9de01c536617f4832caf51473195260
diff --git a/canvasapi/assignment.py b/canvasapi/assignment.py index bbc4bda..03d1b56 100644 --- a/canvasapi/assignment.py +++ b/canvasapi/assignment.py @@ -5,6 +5,7 @@ from six import python_2_unicode_compatible from canvasapi.canvas_object import CanvasObject from canvasapi.exceptions import RequiredFieldMissing from canvasapi.paginated_list import PaginatedList +from canvasapi.progress import Progress from canvasapi.submission import Submission from canvasapi.user import UserDisplay from canvasapi.util import combine_kwargs, obj_or_id @@ -144,6 +145,27 @@ class Assignment(CanvasObject): return Submission(self._requester, response_json) + def submissions_bulk_update(self, **kwargs): + """ + Update the grading and comments on multiple student's assignment + submissions in an asynchronous job. + + :calls: `POST /api/v1/courses/:course_id/assignments/:assignment_id/ \ + submissions/update_grades \ + <https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.bulk_update>`_ + + :rtype: :class:`canvasapi.progress.Progress` + """ + response = self._requester.request( + 'POST', + 'courses/{}/assignments/{}/submissions/update_grades'.format( + self.course_id, + self.id + ), + _kwargs=combine_kwargs(**kwargs) + ) + return Progress(self._requester, response.json()) + @python_2_unicode_compatible class AssignmentGroup(CanvasObject): diff --git a/canvasapi/course.py b/canvasapi/course.py index 725506c..5a6e6aa 100644 --- a/canvasapi/course.py +++ b/canvasapi/course.py @@ -11,6 +11,7 @@ from canvasapi.exceptions import RequiredFieldMissing from canvasapi.folder import Folder from canvasapi.page import Page from canvasapi.paginated_list import PaginatedList +from canvasapi.progress import Progress from canvasapi.tab import Tab from canvasapi.submission import Submission from canvasapi.upload import Uploader @@ -2143,6 +2144,25 @@ class Course(CanvasObject): _kwargs=combine_kwargs(**kwargs) ) + def submissions_bulk_update(self, **kwargs): + """ + Update the grading and comments on multiple student's assignment + submissions in an asynchronous job. + + :calls: `POST /api/v1/courses/:course_id/submissions/update_grades \ + <https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.bulk_update>`_ + + :rtype: :class:`canvasapi.progress.Progress` + """ + response = self._requester.request( + 'POST', + 'courses/{}/submissions/update_grades'.format( + self.id + ), + _kwargs=combine_kwargs(**kwargs) + ) + return Progress(self._requester, response.json()) + @python_2_unicode_compatible class CourseNickname(CanvasObject): diff --git a/canvasapi/section.py b/canvasapi/section.py index 7a9a95f..0d22736 100644 --- a/canvasapi/section.py +++ b/canvasapi/section.py @@ -5,6 +5,7 @@ from six import python_2_unicode_compatible from canvasapi.canvas_object import CanvasObject from canvasapi.paginated_list import PaginatedList +from canvasapi.progress import Progress from canvasapi.submission import Submission from canvasapi.util import combine_kwargs, obj_or_id @@ -373,3 +374,22 @@ class Section(CanvasObject): 'user_id': user_id }) return submission.mark_unread(**kwargs) + + def submissions_bulk_update(self, **kwargs): + """ + Update the grading and comments on multiple student's assignment + submissions in an asynchronous job. + + :calls: `POST /api/v1/sections/:section_id/submissions/update_grades \ + <https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.bulk_update>`_ + + :rtype: :class:`canvasapi.progress.Progress` + """ + response = self._requester.request( + 'POST', + 'sections/{}/submissions/update_grades'.format( + self.id + ), + _kwargs=combine_kwargs(**kwargs) + ) + return Progress(self._requester, response.json())
Wrap “Grade or comment on multiple submissions” methods The Canvas REST API offers [a suite of "Grade or comment on multiple submissions" methods](https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.bulk_update) that `canvasapi` 0.9.0 does not yet wrap. I recently had cause to use one of these methods, so proper `canvasapi` versions would be appreciated. In my particular case I need to update grades for multiple assignments by multiple students. That presumably makes the `POST /api/v1/courses/:course_id/submissions/update_grades` entry point the right thing to use, although it is not clear to me whether one can indeed update multiple assignments for multiple students all in a single call.
ucfopen/canvasapi
diff --git a/tests/fixtures/assignment.json b/tests/fixtures/assignment.json index 47f38b6..aec1393 100644 --- a/tests/fixtures/assignment.json +++ b/tests/fixtures/assignment.json @@ -84,5 +84,22 @@ "submission_type": "online_upload" }, "status_code": 200 + }, + "update_submissions": { + "method": "POST", + "endpoint": "courses/1/assignments/1/submissions/update_grades", + "data": { + "id": 3, + "context_id": 1, + "context_type": "Course", + "user_id": null, + "tag": "submissions_update", + "completion": null, + "workflow_state": "queued", + "updated_at": "2013-01-15T15:04:00Z", + "message": null, + "url": "https://canvas.example.edu/api/v1/progress/3" + }, + "status_code": 200 } } diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index 2f30d67..9f1f08e 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -1458,5 +1458,22 @@ } ], "status_code": 200 + }, + "update_submissions": { + "method": "POST", + "endpoint": "courses/1/submissions/update_grades", + "data": { + "id": 3, + "context_id": 1, + "context_type": "Course", + "user_id": null, + "tag": "submissions_update", + "completion": null, + "workflow_state": "queued", + "updated_at": "2013-01-15T15:04:00Z", + "message": null, + "url": "https://canvas.example.edu/api/v1/progress/3" + }, + "status_code": 200 } } diff --git a/tests/fixtures/progress.json b/tests/fixtures/progress.json index 8642747..3be42a0 100644 --- a/tests/fixtures/progress.json +++ b/tests/fixtures/progress.json @@ -16,5 +16,21 @@ "url": "https://canvas.example.edu/api/v1/progress/1" }, "status_code": 200 + }, + "course_progress": { + "method": "GET", + "endpoint": "progress/3", + "data":{ + "id": 3, + "context_id": 1, + "context_type": "Course", + "user_id": null, + "tag": "submissions_update", + "completion": 100, + "workflow_state": "completed", + "updated_at": "2013-01-15T15:04:00Z", + "message": null, + "url": "https://canvas.example.edu/api/v1/progress/3" + } } -} \ No newline at end of file +} diff --git a/tests/fixtures/section.json b/tests/fixtures/section.json index 19c860b..c4caecb 100644 --- a/tests/fixtures/section.json +++ b/tests/fixtures/section.json @@ -182,5 +182,22 @@ "method": "DELETE", "endpoint": "sections/1/assignments/1/submissions/1/read", "status_code": 204 + }, + "update_submissions": { + "method": "POST", + "endpoint": "sections/1/submissions/update_grades", + "data": { + "id": 3, + "context_id": 1, + "context_type": "Course", + "user_id": null, + "tag": "submissions_update", + "completion": null, + "workflow_state": "queued", + "updated_at": "2013-01-15T15:04:00Z", + "message": null, + "url": "https://canvas.example.edu/api/v1/progress/3" + }, + "status_code": 200 } } diff --git a/tests/test_assignment.py b/tests/test_assignment.py index e0adc34..e5fec7c 100644 --- a/tests/test_assignment.py +++ b/tests/test_assignment.py @@ -6,6 +6,7 @@ import requests_mock from canvasapi import Canvas from canvasapi.assignment import Assignment, AssignmentGroup from canvasapi.exceptions import RequiredFieldMissing +from canvasapi.progress import Progress from canvasapi.submission import Submission from canvasapi.user import UserDisplay from tests import settings @@ -101,6 +102,23 @@ class TestAssignment(unittest.TestCase): string = str(self.assignment) self.assertIsInstance(string, str) + # submissions_bulk_update() + def test_submissions_bulk_update(self, m): + register_uris({'assignment': ['update_submissions']}, m) + register_uris({'progress': ['course_progress']}, m) + progress = self.assignment.submissions_bulk_update(grade_data={ + '1': { + 'posted_grade': 97 + }, + '2': { + 'posted_grade': 98 + } + }) + self.assertIsInstance(progress, Progress) + self.assertTrue(progress.context_type == "Course") + progress = progress.query() + self.assertTrue(progress.context_type == "Course") + @requests_mock.Mocker() class TestAssignmentGroup(unittest.TestCase): diff --git a/tests/test_course.py b/tests/test_course.py index e6e728d..48053dc 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -22,6 +22,7 @@ from canvasapi.folder import Folder from canvasapi.group import Group, GroupCategory from canvasapi.module import Module from canvasapi.outcome import OutcomeGroup, OutcomeLink +from canvasapi.progress import Progress from canvasapi.quiz import Quiz from canvasapi.rubric import Rubric from canvasapi.section import Section @@ -1387,6 +1388,25 @@ class TestCourse(unittest.TestCase): self.assertEqual(migration_systems[1].requires_file_upload, False) self.assertEqual(migration_systems[1].name, "Dummy Importer 02") + # submissions_bulk_update() + def test_submissions_bulk_update(self, m): + register_uris({'course': ['update_submissions']}, m) + register_uris({'progress': ['course_progress']}, m) + progress = self.course.submissions_bulk_update(grade_data={ + '1': { + '1': { + 'posted_grade': 97 + }, + '2': { + 'posted_grade': 98 + } + } + }) + self.assertIsInstance(progress, Progress) + self.assertTrue(progress.context_type == "Course") + progress = progress.query() + self.assertTrue(progress.context_type == "Course") + @requests_mock.Mocker() class TestCourseNickname(unittest.TestCase): diff --git a/tests/test_section.py b/tests/test_section.py index 92b500c..eef7694 100644 --- a/tests/test_section.py +++ b/tests/test_section.py @@ -8,6 +8,7 @@ from six import text_type from canvasapi import Canvas from canvasapi.enrollment import Enrollment from canvasapi.exceptions import RequiredFieldMissing +from canvasapi.progress import Progress from canvasapi.section import Section from canvasapi.submission import Submission from tests import settings @@ -319,3 +320,21 @@ class TestSection(unittest.TestCase): self.assertEqual(len(warning_list), 1) self.assertEqual(warning_list[-1].category, DeprecationWarning) + + def test_submissions_bulk_update(self, m): + register_uris({'section': ['update_submissions']}, m) + register_uris({'progress': ['course_progress']}, m) + progress = self.section.submissions_bulk_update(grade_data={ + '1': { + '1': { + 'posted_grade': 97 + }, + '2': { + 'posted_grade': 98 + } + } + }) + self.assertIsInstance(progress, Progress) + self.assertTrue(progress.context_type == "Course") + progress = progress.query() + self.assertTrue(progress.context_type == "Course")
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 3 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio", "requests_mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/ucfopen/canvasapi.git@6030f6bcb9de01c536617f4832caf51473195260#egg=canvasapi certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup==1.2.2 execnet==2.1.1 idna==3.10 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 pytz==2025.2 requests==2.32.3 requests-mock==1.12.1 six==1.17.0 tomli==2.2.1 typing_extensions==4.13.0 urllib3==2.3.0
name: canvasapi channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - pytz==2025.2 - requests==2.32.3 - requests-mock==1.12.1 - six==1.17.0 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 prefix: /opt/conda/envs/canvasapi
[ "tests/test_assignment.py::TestAssignment::test_submissions_bulk_update", "tests/test_course.py::TestCourse::test_submissions_bulk_update", "tests/test_section.py::TestSection::test_submissions_bulk_update" ]
[ "tests/test_course.py::TestCourse::test_get_submission", "tests/test_course.py::TestCourse::test_list_assignment_groups", "tests/test_course.py::TestCourse::test_list_external_feeds", "tests/test_course.py::TestCourse::test_list_files", "tests/test_course.py::TestCourse::test_list_folders", "tests/test_course.py::TestCourse::test_list_gradeable_students", "tests/test_course.py::TestCourse::test_list_group_categories", "tests/test_course.py::TestCourse::test_list_groups", "tests/test_course.py::TestCourse::test_list_multiple_submissions", "tests/test_course.py::TestCourse::test_list_rubrics", "tests/test_course.py::TestCourse::test_list_sections", "tests/test_course.py::TestCourse::test_list_submissions", "tests/test_course.py::TestCourse::test_list_tabs", "tests/test_course.py::TestCourse::test_mark_submission_as_read", "tests/test_course.py::TestCourse::test_mark_submission_as_unread", "tests/test_course.py::TestCourse::test_submit_assignment", "tests/test_course.py::TestCourse::test_submit_assignment_fail", "tests/test_course.py::TestCourse::test_update_submission", "tests/test_course.py::TestCourse::test_update_tab", "tests/test_section.py::TestSection::test_get_submission", "tests/test_section.py::TestSection::test_list_multiple_submissions", "tests/test_section.py::TestSection::test_list_submissions", "tests/test_section.py::TestSection::test_mark_submission_as_read", "tests/test_section.py::TestSection::test_mark_submission_as_unread", "tests/test_section.py::TestSection::test_subit_assignment_fail", "tests/test_section.py::TestSection::test_submit_assignment", "tests/test_section.py::TestSection::test_update_submission" ]
[ "tests/test_assignment.py::TestAssignment::test__str__", "tests/test_assignment.py::TestAssignment::test_delete_assignments", "tests/test_assignment.py::TestAssignment::test_edit_assignment", "tests/test_assignment.py::TestAssignment::test_get_gradeable_students", "tests/test_assignment.py::TestAssignment::test_get_submission", "tests/test_assignment.py::TestAssignment::test_get_submissions", "tests/test_assignment.py::TestAssignment::test_submit", "tests/test_assignment.py::TestAssignment::test_submit_fail", "tests/test_assignment.py::TestAssignmentGroup::test__str__", "tests/test_assignment.py::TestAssignmentGroup::test_delete_assignment_group", "tests/test_assignment.py::TestAssignmentGroup::test_edit_assignment_group", "tests/test_course.py::TestCourse::test__str__", "tests/test_course.py::TestCourse::test_add_grading_standards", "tests/test_course.py::TestCourse::test_add_grading_standards_empty_list", "tests/test_course.py::TestCourse::test_add_grading_standards_missing_name_key", "tests/test_course.py::TestCourse::test_add_grading_standards_missing_value_key", "tests/test_course.py::TestCourse::test_add_grading_standards_non_dict_list", "tests/test_course.py::TestCourse::test_conclude", "tests/test_course.py::TestCourse::test_create_assignment", "tests/test_course.py::TestCourse::test_create_assignment_fail", "tests/test_course.py::TestCourse::test_create_assignment_group", "tests/test_course.py::TestCourse::test_create_content_migration", "tests/test_course.py::TestCourse::test_create_content_migration_bad_migration_type", "tests/test_course.py::TestCourse::test_create_content_migration_migrator", "tests/test_course.py::TestCourse::test_create_course_section", "tests/test_course.py::TestCourse::test_create_discussion_topic", "tests/test_course.py::TestCourse::test_create_external_feed", "tests/test_course.py::TestCourse::test_create_external_tool", "tests/test_course.py::TestCourse::test_create_folder", "tests/test_course.py::TestCourse::test_create_group_category", "tests/test_course.py::TestCourse::test_create_module", "tests/test_course.py::TestCourse::test_create_module_fail", "tests/test_course.py::TestCourse::test_create_page", "tests/test_course.py::TestCourse::test_create_page_fail", "tests/test_course.py::TestCourse::test_create_quiz", "tests/test_course.py::TestCourse::test_create_quiz_fail", "tests/test_course.py::TestCourse::test_delete", "tests/test_course.py::TestCourse::test_delete_external_feed", "tests/test_course.py::TestCourse::test_edit_front_page", "tests/test_course.py::TestCourse::test_enroll_user", "tests/test_course.py::TestCourse::test_get_assignment", "tests/test_course.py::TestCourse::test_get_assignment_group", "tests/test_course.py::TestCourse::test_get_assignment_groups", "tests/test_course.py::TestCourse::test_get_assignments", "tests/test_course.py::TestCourse::test_get_content_migration", "tests/test_course.py::TestCourse::test_get_content_migrations", "tests/test_course.py::TestCourse::test_get_course_level_assignment_data", "tests/test_course.py::TestCourse::test_get_course_level_participation_data", "tests/test_course.py::TestCourse::test_get_course_level_student_summary_data", "tests/test_course.py::TestCourse::test_get_discussion_topic", "tests/test_course.py::TestCourse::test_get_discussion_topics", "tests/test_course.py::TestCourse::test_get_enrollments", "tests/test_course.py::TestCourse::test_get_external_feeds", "tests/test_course.py::TestCourse::test_get_external_tool", "tests/test_course.py::TestCourse::test_get_external_tools", "tests/test_course.py::TestCourse::test_get_file", "tests/test_course.py::TestCourse::test_get_files", "tests/test_course.py::TestCourse::test_get_folder", "tests/test_course.py::TestCourse::test_get_folders", "tests/test_course.py::TestCourse::test_get_full_discussion_topic", "tests/test_course.py::TestCourse::test_get_grading_standards", "tests/test_course.py::TestCourse::test_get_group_categories", "tests/test_course.py::TestCourse::test_get_groups", "tests/test_course.py::TestCourse::test_get_migration_systems", "tests/test_course.py::TestCourse::test_get_module", "tests/test_course.py::TestCourse::test_get_modules", "tests/test_course.py::TestCourse::test_get_multiple_submissions", "tests/test_course.py::TestCourse::test_get_multiple_submissions_grouped_param", "tests/test_course.py::TestCourse::test_get_outcome_group", "tests/test_course.py::TestCourse::test_get_outcome_groups_in_context", "tests/test_course.py::TestCourse::test_get_outcome_links_in_context", "tests/test_course.py::TestCourse::test_get_outcome_result_rollups", "tests/test_course.py::TestCourse::test_get_outcome_results", "tests/test_course.py::TestCourse::test_get_page", "tests/test_course.py::TestCourse::test_get_pages", "tests/test_course.py::TestCourse::test_get_quiz", "tests/test_course.py::TestCourse::test_get_quiz_fail", "tests/test_course.py::TestCourse::test_get_quizzes", "tests/test_course.py::TestCourse::test_get_recent_students", "tests/test_course.py::TestCourse::test_get_root_outcome_group", "tests/test_course.py::TestCourse::test_get_rubric", "tests/test_course.py::TestCourse::test_get_rubrics", "tests/test_course.py::TestCourse::test_get_section", "tests/test_course.py::TestCourse::test_get_sections", "tests/test_course.py::TestCourse::test_get_settings", "tests/test_course.py::TestCourse::test_get_single_grading_standard", "tests/test_course.py::TestCourse::test_get_tabs", "tests/test_course.py::TestCourse::test_get_user", "tests/test_course.py::TestCourse::test_get_user_id_type", "tests/test_course.py::TestCourse::test_get_user_in_a_course_level_assignment_data", "tests/test_course.py::TestCourse::test_get_user_in_a_course_level_messaging_data", "tests/test_course.py::TestCourse::test_get_user_in_a_course_level_participation_data", "tests/test_course.py::TestCourse::test_get_users", "tests/test_course.py::TestCourse::test_preview_html", "tests/test_course.py::TestCourse::test_reorder_pinned_topics", "tests/test_course.py::TestCourse::test_reorder_pinned_topics_comma_separated_string", "tests/test_course.py::TestCourse::test_reorder_pinned_topics_invalid_input", "tests/test_course.py::TestCourse::test_reorder_pinned_topics_tuple", "tests/test_course.py::TestCourse::test_reset", "tests/test_course.py::TestCourse::test_show_front_page", "tests/test_course.py::TestCourse::test_update", "tests/test_course.py::TestCourse::test_update_settings", "tests/test_course.py::TestCourse::test_upload", "tests/test_course.py::TestCourseNickname::test__str__", "tests/test_course.py::TestCourseNickname::test_remove", "tests/test_section.py::TestSection::test__str__", "tests/test_section.py::TestSection::test_cross_list_section", "tests/test_section.py::TestSection::test_decross_list_section", "tests/test_section.py::TestSection::test_delete", "tests/test_section.py::TestSection::test_edit", "tests/test_section.py::TestSection::test_get_enrollments", "tests/test_section.py::TestSection::test_get_multiple_submissions", "tests/test_section.py::TestSection::test_get_multiple_submissions_grouped_param" ]
[]
MIT License
2,595
[ "canvasapi/course.py", "canvasapi/section.py", "canvasapi/assignment.py" ]
[ "canvasapi/course.py", "canvasapi/section.py", "canvasapi/assignment.py" ]
sernst__cauldron-28
6dbaa6713036625744ace2852056e839d8d4ae4f
2018-05-29 17:32:39
3ebb9fece61219af16f73fd67a1c0e7fc584f770
diff --git a/cauldron/cli/server/routes/synchronize/__init__.py b/cauldron/cli/server/routes/synchronize/__init__.py index 81f5aff..1b1ea08 100644 --- a/cauldron/cli/server/routes/synchronize/__init__.py +++ b/cauldron/cli/server/routes/synchronize/__init__.py @@ -3,8 +3,9 @@ import mimetypes import os import tempfile -import cauldron as cd import flask + +import cauldron as cd from cauldron import cli from cauldron import writer from cauldron.cli import sync @@ -115,6 +116,7 @@ def sync_open_project(): sync_status.update({}, time=-1, project=None) open_response = project_opener.open_project(project_folder, forget=True) + open_response.join() project = cd.project.internal_project project.remote_source_directory = source_directory @@ -142,6 +144,7 @@ def sync_source_file(): index = args.get('index', 0) sync_time = args.get('sync_time', -1) location = args.get('location', 'project') + offset = args.get('offset', 0) if None in [relative_path, chunk]: return r.fail( @@ -173,11 +176,16 @@ def sync_source_file(): if not os.path.exists(parent_directory): os.makedirs(parent_directory) - sync.io.write_file_chunk(file_path, chunk, append=index > 0) + sync.io.write_file_chunk( + file_path=file_path, + packed_chunk=chunk, + append=index > 0, + offset=offset + ) sync_status.update({}, time=sync_time) - print('SAVED CHUNK:', file_path) + print('SAVED CHUNK:', offset, file_path) return r.notify( kind='SUCCESS', code='SAVED_CHUNK', diff --git a/cauldron/cli/sync/comm.py b/cauldron/cli/sync/comm.py index c66d111..f60cc7f 100644 --- a/cauldron/cli/sync/comm.py +++ b/cauldron/cli/sync/comm.py @@ -20,7 +20,6 @@ def assemble_url( :return: The fully-resolved URL for the given endpoint """ - url_root = ( remote_connection.url if remote_connection else @@ -51,7 +50,6 @@ def parse_http_response(http_response: HttpResponse) -> 'environ.Response': :return: The Cauldron response object for the given http response """ - try: response = environ.Response.deserialize(http_response.json()) except Exception as error: @@ -67,35 +65,65 @@ def parse_http_response(http_response: HttpResponse) -> 'environ.Response': return response -def get_request_function(data: dict = None, method: str = None): - """ """ - - default_method = 'post' if data else 'get' - return getattr(requests, method.lower() if method else default_method) - - def send_request( endpoint: str, data: dict = None, remote_connection: 'environ.RemoteConnection' = None, method: str = None, + timeout: int = 10, + max_retries: int = 10, **kwargs ) -> 'environ.Response': - """ """ + """ + Sends a request to the remote kernel specified by the RemoteConnection + object and processes the result. If the request fails or times out it + will be retried until the max retries is reached. After that a failed + response will be returned instead. + + :param endpoint: + Remote endpoint where the request will be directed. + :param data: + An optional JSON-serializable dictionary containing the request + body data. + :param remote_connection: + Defines the connection to the remote server where the request will + be sent. + :param method: + The HTTP method type for the request, e.g. GET, POST. + :param timeout: + Number of seconds before the request aborts when trying to either + connect to the target endpoint or receive data from the server. + :param max_retries: + Number of retry attempts to make before giving up if a non-HTTP + error is encountered during communication. + """ + if max_retries < 0: + return environ.Response().fail( + code='COMMUNICATION_ERROR', + error=None, + message='Unable to communicate with the remote kernel.' + ).console(whitespace=1).response url = assemble_url(endpoint, remote_connection) - func = get_request_function(data, method) try: - http_response = func(url, json=data, **kwargs) - except Exception as error: - return environ.Response().fail( - code='CONNECTION_ERROR', - error=error, - message='Unable to communicate with the remote connection' - ).console( - whitespace=1 - ).response + http_response = requests.request( + method=method, + url=url, + json=data, + timeout=10, + **kwargs + ) + except (requests.ConnectionError, requests.HTTPError, requests.Timeout): + return send_request( + endpoint=endpoint, + data=data, + remote_connection=remote_connection, + method=method, + timeout=timeout, + max_retries=max_retries - 1, + **kwargs + ) return parse_http_response(http_response) diff --git a/cauldron/cli/sync/files.py b/cauldron/cli/sync/files.py index 047d0c9..9d130b7 100644 --- a/cauldron/cli/sync/files.py +++ b/cauldron/cli/sync/files.py @@ -11,25 +11,24 @@ from cauldron.environ.response import Response def send_chunk( chunk: str, index: int, + offset: int, relative_path: str, file_kind: str = '', remote_connection: 'environ.RemoteConnection' = None, sync_time: float = -1 ): """ """ - - args = dict( - relative_path=relative_path, - chunk=chunk, - type=file_kind, - index=index, - sync_time=time.time() if sync_time < 0 else sync_time - ) - return sync.comm.send_request( endpoint='/sync-file', remote_connection=remote_connection, - data=args + data=dict( + relative_path=relative_path, + chunk=chunk, + offset=offset, + type=file_kind, + index=index, + sync_time=time.time() if sync_time < 0 else sync_time + ) ) @@ -44,7 +43,6 @@ def send( sync_time: float = -1 ) -> Response: """ """ - response = Response() sync_time = time.time() if sync_time < 0 else sync_time callback = ( @@ -91,15 +89,18 @@ def send( ) )) + offset = 0 for index, chunk in enumerate(chunks): response = send_chunk( chunk=chunk, index=index, + offset=offset, relative_path=relative_path, file_kind=file_kind, remote_connection=remote_connection, sync_time=sync_time ) + offset += len(chunk) if response.failed: return response @@ -146,7 +147,6 @@ def send_all_in( sync_time: float = -1 ) -> Response: """ """ - sync_time = time.time() if sync_time < 0 else sync_time glob_end = ('**', '*') if recursive else ('*',) @@ -156,10 +156,10 @@ def send_all_in( relative_root_path if relative_root_path else directory - ).rstrip(os.sep) + ).rstrip(os.path.sep) for file_path in glob.iglob(glob_path, recursive=True): - relative_path = file_path[len(root_path):].lstrip(os.sep) + relative_path = file_path[len(root_path):].lstrip(os.path.sep) response = send( file_path=file_path, diff --git a/cauldron/cli/sync/sync_io.py b/cauldron/cli/sync/sync_io.py index 9836a25..4cb3b07 100644 --- a/cauldron/cli/sync/sync_io.py +++ b/cauldron/cli/sync/sync_io.py @@ -3,10 +3,8 @@ import math import os import zlib - from cauldron import writer - # Default Chunks are 1MB in size DEFAULT_CHUNK_SIZE = 1048576 # type: int @@ -20,7 +18,6 @@ def pack_chunk(source_data: bytes) -> str: :param source_data: The data to be converted to a compressed, base64 string """ - if not source_data: return '' @@ -61,18 +58,17 @@ def get_file_chunk_count( The number of chunks necessary to send the entire contents of the specified file for the given chunk size """ - if not os.path.exists(file_path): return 0 file_size = os.path.getsize(file_path) - return max(1, math.ceil(file_size / chunk_size)) + return max(1, int(math.ceil(file_size / chunk_size))) def read_file_chunks( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE -) -> str: +) -> bytes: """ Reads the specified file in chunks and returns a generator where each returned chunk is a compressed base64 encoded string for sync @@ -84,7 +80,6 @@ def read_file_chunks( The size, in bytes, of each chunk. The final chunk will be less than or equal to this size as the remainder. """ - chunk_count = get_file_chunk_count(file_path, chunk_size) if chunk_count < 1: @@ -97,7 +92,12 @@ def read_file_chunks( yield chunk -def write_file_chunk(file_path: str, chunk_data: str, append: bool = True): +def write_file_chunk( + file_path: str, + packed_chunk: str, + append: bool = True, + offset: int = -1 +): """ Write or append the specified chunk data to the given file path, unpacking the chunk before writing. If the file does not yet exist, it will be @@ -106,13 +106,19 @@ def write_file_chunk(file_path: str, chunk_data: str, append: bool = True): :param file_path: The file where the chunk will be written or appended - :param chunk_data: - The packed chunk data to write to the file + :param packed_chunk: + The packed chunk data to write to the file. It will be unpacked before + the file is written. :param append: Whether or not the chunk should be appended to the existing file. If False the chunk data will overwrite the existing file. + :param offset: + The byte offset in the file where the chunk should be written. + If the value is less than zero, the chunk will be written or appended + based on the `append` argument. Note that if you indicate an append + write mode and an offset, the mode will be forced to write instead of + append. """ - mode = 'ab' if append else 'wb' - contents = unpack_chunk(chunk_data) - writer.write_file(file_path, contents, mode=mode) + contents = unpack_chunk(packed_chunk) + writer.write_file(file_path, contents, mode=mode, offset=offset) diff --git a/cauldron/environ/response.py b/cauldron/environ/response.py index eabf446..aea5182 100644 --- a/cauldron/environ/response.py +++ b/cauldron/environ/response.py @@ -191,6 +191,25 @@ class Response(object): print(self.echo()) return self + def join(self, timeout: float = None) -> bool: + """ + Joins on the thread associated with the response if it exists, or + just returns after a no-op if no thread exists to join. + + :param timeout: + Maximum number of seconds to block on the join before given up + and continuing operation. The default `None` value will wait + forever. + :return: + A boolean indicating whether or not a thread existed to join + upon. + """ + try: + self.thread.join(timeout) + return True + except AttributeError: + return False + def echo(self) -> str: """ """ diff --git a/cauldron/environ/systems.py b/cauldron/environ/systems.py index d2f8abc..c0a408a 100644 --- a/cauldron/environ/systems.py +++ b/cauldron/environ/systems.py @@ -3,6 +3,7 @@ import os import shutil import site import sys +import time import typing from cauldron.environ import paths @@ -119,13 +120,19 @@ def get_package_data() -> dict: return json.load(f) -def remove(path: str) -> bool: +def remove(path: str, max_retries: int = 3) -> bool: """ + Removes the specified path from the local filesystem if it exists. + Directories will be removed along with all files and folders within + them as well as files. :param path: + The location of the file or folder to remove. + :param max_retries: + The number of times to retry before giving up. :return: + A boolean indicating whether or not the removal was successful. """ - if not path: return False @@ -134,12 +141,14 @@ def remove(path: str) -> bool: remover = os.remove if os.path.isfile(path) else shutil.rmtree - for attempt in range(3): + for attempt in range(max_retries): try: remover(path) return True except Exception: - pass + # Pause briefly in case there's a race condition on lock + # for the target. + time.sleep(0.02) return False diff --git a/cauldron/settings.json b/cauldron/settings.json index a2fb2f3..b042ac5 100644 --- a/cauldron/settings.json +++ b/cauldron/settings.json @@ -1,4 +1,4 @@ { - "version": "0.3.4", + "version": "0.3.5", "notebookVersion": "v1" } diff --git a/cauldron/writer.py b/cauldron/writer.py index 3ff8551..ca30c69 100644 --- a/cauldron/writer.py +++ b/cauldron/writer.py @@ -6,7 +6,8 @@ import typing def attempt_file_write( path: str, contents: typing.Union[str, bytes], - mode: str = 'w' + mode: str = 'w', + offset: int = 0 ) -> typing.Union[None, Exception]: """ Attempts to write the specified contents to a file and returns None if @@ -18,14 +19,34 @@ def attempt_file_write( The contents of the file to write :param mode: The mode in which the file will be opened when written + :param offset: + The byte offset in the file where the contents should be written. + If the value is zero, the offset information will be ignored and + the operation will write entirely based on mode. Note that if you + indicate an append write mode and an offset, the mode will be forced + to write instead of append. :return: None if the write operation succeeded. Otherwise, the exception that was raised by the failed write action. """ + try: + data = contents.encode() + except Exception: + data = contents + if offset > 0: + with open(path, 'rb') as f: + existing = f.read(offset) + else: + existing = None + + append = 'a' in mode + write_mode = 'wb' if offset > 0 or not append else 'ab' try: - with open(path, mode) as f: - f.write(contents) + with open(path, write_mode) as f: + if existing is not None: + f.write(existing) + f.write(data) return None except Exception as error: return error @@ -35,7 +56,8 @@ def write_file( path: str, contents, mode: str = 'w', - retry_count: int = 3 + retry_count: int = 3, + offset: int = 0 ) -> typing.Tuple[bool, typing.Union[None, Exception]]: """ Writes the specified contents to a file, with retry attempts if the write @@ -51,16 +73,21 @@ def write_file( :param retry_count: The number of attempts to make before giving up and returning a failed write. + :param offset: + The byte offset in the file where the contents should be written. + If the value is zero, the offset information will be ignored and the + operation will write entirely based on mode. Note that if you indicate + an append write mode and an offset, the mode will be forced to write + instead of append. :return: Returns two arguments. The first is a boolean specifying whether or not the write operation succeeded. The second is the error result, which is None if the write operation succeeded. Otherwise, it will be the exception that was raised by the last failed write attempt. """ - error = None for i in range(retry_count): - error = attempt_file_write(path, contents, mode) + error = attempt_file_write(path, contents, mode, offset) if error is None: return True, None time.sleep(0.2) @@ -86,7 +113,6 @@ def attempt_json_write( None if the write operation succeeded. Otherwise, the exception that was raised by the failed write operation. """ - try: with open(path, mode) as f: json.dump(contents, f) @@ -122,7 +148,6 @@ def write_json_file( is None if the write operation succeeded. Otherwise, it will be the exception that was raised by the last failed write attempt. """ - error = None for i in range(retry_count): error = attempt_json_write(path, contents, mode) diff --git a/docker-compose.yml b/docker-compose.yml index 5bc6481..4ae3145 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,12 +1,40 @@ - version: '3' - services: - app: - build: . - container_name: cauldron_app - volumes: - - .:/cauldron - ports: - - "5010:5010" - stdin_open: true - tty: true - entrypoint: /bin/bash +version: '3' +services: + app: + build: + context: . + dockerfile: Dockerfile + volumes: + - .:/cauldron + ports: + - "5010:5010" + stdin_open: true + tty: true + entrypoint: /bin/bash + + kernel-conda: + build: + context: . + dockerfile: docker-conda.dockerfile + volumes: + - .:/cauldron_local + ports: + - "5010:5010" + + kernel-miniconda: + build: + context: . + dockerfile: docker-miniconda.dockerfile + volumes: + - .:/cauldron_local + ports: + - "5010:5010" + + kernel-standard: + build: + context: . + dockerfile: docker-standard.dockerfile + volumes: + - .:/cauldron_local + ports: + - "5010:5010" diff --git a/docker-run.sh b/docker-run.sh index 90b704d..8cd1d7b 100644 --- a/docker-run.sh +++ b/docker-run.sh @@ -2,5 +2,3 @@ echo "Starting Cauldron Kernel" cauldron kernel --port=5010 --name=0.0.0.0 - -
Enhanced Syncing Improve the file sync handling in the `cauldron.cli.sync` subpackage.
sernst/cauldron
diff --git a/cauldron/steptest/functional.py b/cauldron/steptest/functional.py index 16ac45c..dbb16c8 100644 --- a/cauldron/steptest/functional.py +++ b/cauldron/steptest/functional.py @@ -1,4 +1,3 @@ -import inspect import os import sys import tempfile @@ -12,32 +11,37 @@ from cauldron.steptest.results import StepTestRunResult class CauldronTest: - """A Decorator class for use with the Pytest testing framework.""" + """ + A Dependency injection class for use with the Pytest or similar testing + framework. + """ - def __init__(self, *args, **kwargs): + def __init__(self, project_path: str, *args, **kwargs): """ Initializes the decorator with default values that will be populated during the lifecycle of the decorator and test. """ + self.project_path = os.path.realpath(project_path) self._call_args = args self._call_kwargs = kwargs self._test_function = None self.results_directory = None self.temp_directories = dict() + self._library_paths = [] - def __call__(self, test_function): + def setup(self) -> 'CauldronTest': """ - Executed during decoration, this function wraps the supplied test - function and returns a wrapped function that should be called to - executed the step test. + Handles initializing the environment and opening the project for + testing. """ - self._test_function = test_function - - def cauldron_test_wrapper(*args, **kwargs): - return self.run_test(*args, **kwargs) + environ.modes.add(environ.modes.TESTING) project_path = self.make_project_path('cauldron.json') - self._library_paths = support.get_library_paths(project_path) + self._library_paths = [ + path + for path in support.get_library_paths(project_path) + if path not in sys.path + ] sys.path.extend(self._library_paths) # Load libraries before calling test functions so that patching works @@ -45,15 +49,6 @@ class CauldronTest: # patching isn't reverted. runner.reload_libraries(self._library_paths) - cauldron_test_wrapper.__name__ = test_function.__name__ - return cauldron_test_wrapper - - def setup(self): - """ - Handles initializing the environment and opening the project for - testing. - """ - environ.modes.add(environ.modes.TESTING) results_directory = tempfile.mkdtemp( prefix='cd-step-test-results-{}--'.format(self.__class__.__name__) ) @@ -62,6 +57,8 @@ class CauldronTest: self.temp_directories = dict() self.open_project() + return self + def make_project_path(self, *args) -> str: """ Returns an absolute path to the specified location within the Cauldron @@ -74,8 +71,7 @@ class CauldronTest: components are specified, the location returned will be the project directory itself. """ - filename = inspect.getfile(self._test_function) - project_directory = support.find_project_directory(filename) + project_directory = support.find_project_directory(self.project_path) return os.path.join(project_directory, *args) def open_project(self) -> 'exposed.ExposedProject': @@ -129,22 +125,6 @@ class CauldronTest: """ return support.make_temp_path(self.temp_directories, identifier, *args) - def run_test(self, *args, **kwargs): - """ - The function called to actually carry out the execution of the test, - which is wrapped within a function and closure in the `__call__` - method for decoration purposes. - - :param args: - Positional arguments passed to the test function at execution time. - :param kwargs: - Keyword arguments passed to the test function at execution time. - """ - self.setup() - result = self._test_function(self, *args, **kwargs) - self.tear_down() - return result - def tear_down(self): """ After a test is run this function is used to undo any side effects that diff --git a/cauldron/test/cli/sync/test_sync_comm.py b/cauldron/test/cli/sync/test_sync_comm.py index 9f208d4..bdcbe3a 100644 --- a/cauldron/test/cli/sync/test_sync_comm.py +++ b/cauldron/test/cli/sync/test_sync_comm.py @@ -2,6 +2,7 @@ import os from unittest.mock import MagicMock from unittest.mock import patch +import requests from requests import Response as HttpResponse from cauldron import environ @@ -11,11 +12,10 @@ from cauldron.test.support import scaffolds class TestSyncComm(scaffolds.ResultsTest): - """ Tests for the cauldron.cli.sync.sync_comm module """ + """Test suite for the cauldron.cli.sync.sync_comm module""" def test_assemble_url_without_connection(self): - """ should assemble url """ - + """Should assemble url""" endpoint = '/some-endpoint' url_assembled = comm.assemble_url(endpoint) self.assertEqual( @@ -24,8 +24,7 @@ class TestSyncComm(scaffolds.ResultsTest): ) def test_assemble_url_specified_connection(self): - """ should assemble url using the specified remote connection data """ - + """Should assemble url using the specified remote connection data""" url = 'some.url:5451' endpoint = '/some-endpoint' remote_connection = environ.RemoteConnection(url=url, active=True) @@ -34,8 +33,7 @@ class TestSyncComm(scaffolds.ResultsTest): self.assertEqual(url_assembled, 'http://{}{}'.format(url, endpoint)) def test_assemble_url_global_connection(self): - """ should assemble url using the specified remote connection data """ - + """Should assemble url using the specified remote connection data""" url = 'some.url:5451' endpoint = '/some-endpoint' @@ -46,25 +44,22 @@ class TestSyncComm(scaffolds.ResultsTest): support.run_command('disconnect') - @patch('requests.get') - def test_send_request_invalid(self, request_get: MagicMock): - """ should fail to send request """ - - request_get.side_effect = ValueError('Fake Error') - - response = comm.send_request('/fake', method='get') - self.assert_has_error_code(response, 'CONNECTION_ERROR') + @patch('requests.request') + def test_send_request_invalid(self, request: MagicMock): + """Should fail to send request""" + request.side_effect = requests.ConnectionError('Fake Error') + response = comm.send_request('/fake', method='GET') + self.assert_has_error_code(response, 'COMMUNICATION_ERROR') @patch('cauldron.cli.sync.comm.parse_http_response') - @patch('requests.post') + @patch('requests.request') def test_send_request_valid( self, - request_post: MagicMock, + request: MagicMock, parse_http_response: MagicMock ): - """ should fail to send request """ - - request_post.return_value = HttpResponse() + """Should successfully send request""" + request.return_value = HttpResponse() parse_http_response.return_value = environ.Response('test') response = comm.send_request( @@ -75,8 +70,7 @@ class TestSyncComm(scaffolds.ResultsTest): self.assertEqual(response.identifier, 'test') def test_parse_valid_http_response(self): - """ should fail to send request """ - + """Should fail to send request""" source_response = environ.Response().update(test='hello_world') def json_mock(*args, **kwargs): @@ -93,8 +87,7 @@ class TestSyncComm(scaffolds.ResultsTest): ) def test_parse_invalid_http_response(self): - """ should fail to parse invalid http response """ - + """Should fail to parse invalid http response""" http_response = HttpResponse() response = comm.parse_http_response(http_response) self.assert_has_error_code(response, 'INVALID_REMOTE_RESPONSE') @@ -102,10 +95,8 @@ class TestSyncComm(scaffolds.ResultsTest): @patch('requests.get') def test_failed_download(self, requests_get: MagicMock): - """ should fail to download if the GET request raises an exception """ - + """Should fail to download if the GET request raises an exception""" requests_get.side_effect = IOError('FAKE ERROR') - path = self.get_temp_path('failed_download', 'fake.filename') response = comm.download_file('fake.filename', path) @@ -114,8 +105,7 @@ class TestSyncComm(scaffolds.ResultsTest): @patch('requests.get') def test_failed_download_write(self, requests_get: MagicMock): - """ should fail to download if the GET request raises an exception """ - + """Should fail to download if the GET request raises an exception""" requests_get.return_value = dict() path = self.get_temp_path('failed_download', 'fake.filename') @@ -128,8 +118,7 @@ class TestSyncComm(scaffolds.ResultsTest): @patch('requests.get') def test_download(self, requests_get: MagicMock): - """ should successfully download saved cauldron file """ - + """Should successfully download saved cauldron file""" def mock_iter_content(*args, **kwargs): yield from [b'a', b'b', b'', None, b'c'] @@ -146,4 +135,3 @@ class TestSyncComm(scaffolds.ResultsTest): with open(path, 'rb') as f: contents = f.read() self.assertEqual(contents, b'abc') - diff --git a/cauldron/test/environ/test_response.py b/cauldron/test/environ/test_response.py index b25ee9d..92d2ef8 100644 --- a/cauldron/test/environ/test_response.py +++ b/cauldron/test/environ/test_response.py @@ -1,22 +1,21 @@ from unittest import mock from unittest.mock import patch +from unittest.mock import MagicMock from cauldron.environ.response import Response from cauldron.test.support import scaffolds class TestResponse(scaffolds.ResultsTest): - """ """ + """Test suite for the Response class""" def test_get_response(self): - """ should get the response back from the response message """ - + """Should get the response back from the response message""" r = Response() self.assertEqual(r, r.fail().get_response()) def test_warn(self): - """ should notify if warned is called """ - + """Should notify if warned is called""" r = Response() r.warn('FAKE_WARN', key='VALUE') @@ -25,14 +24,12 @@ class TestResponse(scaffolds.ResultsTest): self.assertEqual(r.warnings[0].data['key'], 'VALUE') def test_debug_echo(self): - """ should echo debug information """ - + """Should echo debug information""" r = Response() r.debug_echo() def test_echo(self): - """ should echo information """ - + """Should echo information""" r = Response() r.warn('WARNING', something=[1, 2, 3], value=False) r.fail('ERROR') @@ -41,8 +38,7 @@ class TestResponse(scaffolds.ResultsTest): self.assertGreater(result.find('ERROR'), 0) def test_echo_parented(self): - """ should call parent echo """ - + """Should call parent echo""" r = Response() parent = Response().consume(r) @@ -52,14 +48,12 @@ class TestResponse(scaffolds.ResultsTest): func.assert_any_call() def test_consume_nothing(self): - """ should abort consuming if there is nothing to consume """ - + """Should abort consuming if there is nothing to consume""" r = Response() r.consume(None) def test_grandparent(self): - """ should parent correctly if parented """ - + """Should parent correctly if parented""" child = Response() parent = Response() grandparent = Response() @@ -70,8 +64,7 @@ class TestResponse(scaffolds.ResultsTest): self.assertEqual(child.parent, grandparent) def test_update_parented(self): - """ should update through parent """ - + """Should update through parent""" child = Response() parent = Response() parent.consume(child) @@ -80,8 +73,7 @@ class TestResponse(scaffolds.ResultsTest): self.assertEqual(parent.data['banana'], 'orange') def test_notify_parented(self): - """ should notify through parent """ - + """Should notify through parent""" child = Response() parent = Response() parent.consume(child) @@ -95,8 +87,7 @@ class TestResponse(scaffolds.ResultsTest): self.assertEqual(m.message, 'Good Stuff') def test_end_parented(self): - """ should end the parent """ - + """Should end the parent""" child = Response() parent = Response() parent.consume(child) @@ -105,8 +96,7 @@ class TestResponse(scaffolds.ResultsTest): self.assertTrue(parent.ended) def test_logging(self): - """ should log messages to the log """ - + """Should log messages to the log""" r = Response() r.notify( kind='TEST', @@ -130,7 +120,18 @@ class TestResponse(scaffolds.ResultsTest): self.assertEqual(out, compare) def test_self_consumption(self): - """ should not consume itself and cause regression error """ - + """Should not consume itself and cause regression error""" r = Response() r.consume(r) + + def test_join_nothing(self): + """Should do nothing and return if no thread exists""" + r = Response() + self.assertFalse(r.join()) + + def test_join_thread(self): + """Should join the associated thread and return True""" + r = Response() + r.thread = MagicMock() + self.assertTrue(r.join()) + self.assertEqual(1, r.thread.join.call_count) diff --git a/cauldron/test/steptesting/test_functional.py b/cauldron/test/steptesting/test_functional.py index 76ce75d..c65438f 100644 --- a/cauldron/test/steptesting/test_functional.py +++ b/cauldron/test/steptesting/test_functional.py @@ -9,7 +9,15 @@ from cauldron import steptest from cauldron.steptest import CauldronTest -@CauldronTest() [email protected](name='tester') +def tester_fixture() -> CauldronTest: + """Create the Cauldron project test environment""" + tester = CauldronTest(project_path=os.path.dirname(__file__)) + tester.setup() + yield tester + tester.tear_down() + + def test_first_step(tester: CauldronTest): """Should not be any null/NaN values in df""" assert cd.shared.fetch('df') is None @@ -21,7 +29,6 @@ def test_first_step(tester: CauldronTest): assert error_echo == '' -@CauldronTest() def test_second_step(tester: CauldronTest): """ Should fail without exception because of an exception raised in the @@ -34,7 +41,6 @@ def test_second_step(tester: CauldronTest): assert 0 < len(error_echo) -@CauldronTest() def test_second_step_strict(tester: CauldronTest): """ Should fail because of an exception raised in the source when strict @@ -45,10 +51,9 @@ def test_second_step_strict(tester: CauldronTest): @patch('_testlib.patching_test') -@CauldronTest() def test_second_step_with_patching( - tester: CauldronTest, - patching_test: MagicMock + patching_test: MagicMock, + tester: CauldronTest ): """Should override the return value with the patch""" patching_test.return_value = 12 @@ -58,7 +63,6 @@ def test_second_step_with_patching( assert 12 == cd.shared.result -@CauldronTest() def test_second_step_without_patching(tester: CauldronTest): """Should succeed running the step without patching""" cd.shared.value = 42 @@ -66,7 +70,6 @@ def test_second_step_without_patching(tester: CauldronTest): assert 42 == cd.shared.result -@CauldronTest() def test_to_strings(tester: CauldronTest): """Should convert list of integers to a list of strings""" before = [1, 2, 3] @@ -76,7 +79,6 @@ def test_to_strings(tester: CauldronTest): assert ['1', '2', '3'] == after -@CauldronTest() def test_modes(tester: CauldronTest): """Should be testing and not interactive or single run""" step = tester.run_step('S01-first.py') @@ -86,16 +88,14 @@ def test_modes(tester: CauldronTest): assert not step.local.is_single_run -@CauldronTest() -def test_find_in_current_path(tester: CauldronTest): +def test_find_in_current_path(): """Should find a project in this file's directory""" directory = os.path.dirname(os.path.realpath(__file__)) result = steptest.find_project_directory(directory) assert directory == result -@CauldronTest() -def test_find_in_parent_path(tester: CauldronTest): +def test_find_in_parent_path(): """Should find a project in the parent directory""" directory = os.path.dirname(os.path.realpath(__file__)) subdirectory = os.path.join(directory, 'fake') @@ -103,8 +103,7 @@ def test_find_in_parent_path(tester: CauldronTest): assert directory == result -@CauldronTest() -def test_find_in_grandparent_path(tester: CauldronTest): +def test_find_in_grandparent_path(): """Should find a project in the grandparent directory""" directory = os.path.dirname(os.path.realpath(__file__)) subdirectory = os.path.join(directory, 'fake', 'fake') @@ -112,8 +111,7 @@ def test_find_in_grandparent_path(tester: CauldronTest): assert directory == result -@CauldronTest() -def test_find_failed_at_root(tester: CauldronTest): +def test_find_failed_at_root(): """Should raise FileNotFoundError if top-level directory has no project""" directory = os.path.dirname(os.path.realpath(__file__)) subdirectory = os.path.join(directory, 'fake') @@ -124,21 +122,18 @@ def test_find_failed_at_root(tester: CauldronTest): func.assert_called_once_with(subdirectory) -@CauldronTest() def test_make_temp_path(tester: CauldronTest): """Should make a temp path for testing""" temp_path = tester.make_temp_path('some-id', 'a', 'b.test') assert temp_path.endswith('b.test') -@CauldronTest() def test_no_such_step(tester: CauldronTest): """Should fail if no such step exists""" with pytest.raises(Exception): tester.run_step('FAKE-STEP.no-exists') -@CauldronTest() def test_no_such_project(tester: CauldronTest): """Should fail if no project exists""" project = cd.project.internal_project @@ -150,7 +145,6 @@ def test_no_such_project(tester: CauldronTest): cd.project.load(project) -@CauldronTest() def test_open_project_fails(tester: CauldronTest): """Should raise Assertion error after failing to open the project""" with patch('cauldron.steptest.support.open_project') as open_project: diff --git a/cauldron/test/test_writer.py b/cauldron/test/test_writer.py index 2788bb5..3d4ca8e 100644 --- a/cauldron/test/test_writer.py +++ b/cauldron/test/test_writer.py @@ -1,99 +1,130 @@ -import unittest -from unittest.mock import patch +import tempfile from unittest.mock import MagicMock +from unittest.mock import patch +from cauldron import environ from cauldron import writer -class TestWriter(unittest.TestCase): - """Test suite for the cauldron.writer module""" - - @patch('time.sleep') - @patch('cauldron.writer.attempt_file_write') - def test_write_file(self, attempt_file_write: MagicMock, sleep: MagicMock): - """Should successfully write without retries""" - - attempt_file_write.return_value = None - - success, error = writer.write_file('fake', 'fake') - self.assertTrue(success) - self.assertIsNone(error) - self.assertEqual(1, attempt_file_write.call_count) - self.assertEqual(0, sleep.call_count) - - @patch('time.sleep') - @patch('cauldron.writer.attempt_file_write') - def test_write_file_fail( - self, - attempt_file_write: MagicMock, - sleep: MagicMock - ): - """Should fail to write with retries""" - - attempt_file_write.return_value = IOError('FAKE') - - success, error = writer.write_file('fake', 'fake', retry_count=5) - self.assertFalse(success) - self.assertIsNotNone(error) - self.assertEqual(5, attempt_file_write.call_count) - self.assertEqual(5, sleep.call_count) - - @patch('time.sleep') - @patch('cauldron.writer.attempt_json_write') - def test_write_json(self, attempt_json_write: MagicMock, sleep: MagicMock): - """Should successfully write JSON without retries""" - - attempt_json_write.return_value = None - - success, error = writer.write_json_file('fake', {}) - self.assertTrue(success) - self.assertIsNone(error) - self.assertEqual(1, attempt_json_write.call_count) - self.assertEqual(0, sleep.call_count) - - @patch('time.sleep') - @patch('cauldron.writer.attempt_json_write') - def test_write_json_fail( - self, - attempt_json_write: MagicMock, - sleep: MagicMock - ): - """Should fail to write JSON data to file with retries""" - - attempt_json_write.return_value = IOError('FAKE') - - success, error = writer.write_json_file('fake', {}, retry_count=5) - self.assertFalse(success) - self.assertIsNotNone(error) - self.assertEqual(5, attempt_json_write.call_count) - self.assertEqual(5, sleep.call_count) - - def test_attempt_file_write(self): - """Should write to file without error""" - - with patch('builtins.open'): - result = writer.attempt_file_write('fake', 'fake') - self.assertIsNone(result) - - def test_attempt_file_write_failed(self): - """Should fail to write to file""" - - with patch('builtins.open') as open_func: - open_func.side_effect = IOError('Fake') - result = writer.attempt_file_write('fake', 'fake') - self.assertIsNotNone(result) - - def test_attempt_json_write(self): - """Should write to JSON file without error""" - - with patch('builtins.open'): - result = writer.attempt_json_write('fake', {}) - self.assertIsNone(result) - - def test_attempt_json_write_failed(self): - """Should fail to write JSON data to file""" - - with patch('builtins.open') as open_func: - open_func.side_effect = IOError('Fake') - result = writer.attempt_json_write('fake', {}) - self.assertIsNotNone(result) +@patch('time.sleep') +@patch('cauldron.writer.attempt_file_write') +def test_write_file(attempt_file_write: MagicMock, sleep: MagicMock): + """Should successfully write without retries""" + attempt_file_write.return_value = None + + success, error = writer.write_file('fake', 'fake') + assert success + assert error is None + assert 1 == attempt_file_write.call_count + assert 0 == sleep.call_count + + +@patch('time.sleep') +@patch('cauldron.writer.attempt_file_write') +def test_write_file_fail(attempt_file_write: MagicMock, sleep: MagicMock): + """Should fail to write with retries""" + attempt_file_write.return_value = IOError('FAKE') + + success, error = writer.write_file('fake', 'fake', retry_count=5) + assert not success + assert error is not None + assert 5 == attempt_file_write.call_count + assert 5 == sleep.call_count + + +@patch('time.sleep') +@patch('cauldron.writer.attempt_json_write') +def test_write_json(attempt_json_write: MagicMock, sleep: MagicMock): + """Should successfully write JSON without retries""" + attempt_json_write.return_value = None + success, error = writer.write_json_file('fake', {}) + assert success + assert error is None + assert 1 == attempt_json_write.call_count + assert 0 == sleep.call_count + + +@patch('time.sleep') +@patch('cauldron.writer.attempt_json_write') +def test_write_json_fail(attempt_json_write: MagicMock, sleep: MagicMock): + """Should fail to write JSON data to file with retries""" + attempt_json_write.return_value = IOError('FAKE') + success, error = writer.write_json_file('fake', {}, retry_count=5) + assert not success + assert error is not None + assert 5 == attempt_json_write.call_count + assert 5 == sleep.call_count + + +def test_attempt_file_write(): + """Should write to file without error""" + with patch('builtins.open'): + result = writer.attempt_file_write('fake', 'fake') + assert result is None + + +def test_attempt_file_write_failed(): + """Should fail to write to file""" + with patch('builtins.open') as open_func: + open_func.side_effect = IOError('Fake') + result = writer.attempt_file_write('fake', 'fake') + assert result is not None + + +def test_attempt_json_write(): + """Should write to JSON file without error""" + with patch('builtins.open'): + result = writer.attempt_json_write('fake', {}) + assert result is None + + +def test_attempt_json_write_failed(): + """Should fail to write JSON data to file""" + with patch('builtins.open') as open_func: + open_func.side_effect = IOError('Fake') + result = writer.attempt_json_write('fake', {}) + assert result is not None + + +def test_write_offset_binary(): + """Should write binary data correctly to the given offset""" + path = tempfile.mkstemp()[-1] + try: + writer.write_file(path, b'abc', 'wb') + writer.write_file(path, b'def', 'ab', offset=1) + writer.write_file(path, b'ghi', 'w+b', offset=2) + writer.write_file(path, b'jkl', 'a+b', offset=3) + + with open(path, 'rb') as f: + contents = f.read() + except Exception: # pragma: no cover + raise + finally: + environ.systems.remove(path, 10) + + assert b'adgjkl' == contents, """ + Expected the offset argument to adjust how data is written + to the file to produce an overlapped result. + """ + + +def test_write_offset_ascii(): + """Should write string data correctly to the given offset""" + path = tempfile.mkstemp()[-1] + try: + writer.write_file(path, 'abc', 'w') + writer.write_file(path, 'def', 'a', offset=1) + writer.write_file(path, '\u00A9hi', 'w', offset=2) + writer.write_file(path, '\u0113kl', 'a', offset=4) + + with open(path, 'rb') as f: + contents = f.read().decode() + except Exception: # pragma: no cover + raise + finally: + environ.systems.remove(path, 10) + + assert 'ad\u00A9\u0113kl' == contents, """ + Expected the offset argument to adjust how data is written + to the file to produce an overlapped result. + """
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 10 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 beautifulsoup4==4.12.3 bokeh==2.3.3 -e git+https://github.com/sernst/cauldron.git@6dbaa6713036625744ace2852056e839d8d4ae4f#egg=cauldron_notebook certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 cycler==0.11.0 dataclasses==0.8 Flask==2.0.3 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 kiwisolver==1.3.1 Markdown==3.3.7 MarkupSafe==2.0.1 matplotlib==3.3.4 numpy==1.19.5 packaging==21.3 pandas==1.1.5 Pillow==8.4.0 plotly==5.18.0 pluggy==1.0.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-runner==5.3.2 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 scipy==1.5.4 seaborn==0.11.2 six==1.17.0 soupsieve==2.3.2.post1 tenacity==8.2.2 tomli==1.2.3 tornado==6.1 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0
name: cauldron channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - beautifulsoup4==4.12.3 - bokeh==2.3.3 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - cycler==0.11.0 - dataclasses==0.8 - flask==2.0.3 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - kiwisolver==1.3.1 - markdown==3.3.7 - markupsafe==2.0.1 - matplotlib==3.3.4 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pillow==8.4.0 - plotly==5.18.0 - pluggy==1.0.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-runner==5.3.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - scipy==1.5.4 - seaborn==0.11.2 - six==1.17.0 - soupsieve==2.3.2.post1 - tenacity==8.2.2 - tomli==1.2.3 - tornado==6.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/cauldron
[ "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_send_request_invalid", "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_send_request_valid", "cauldron/test/environ/test_response.py::TestResponse::test_join_nothing", "cauldron/test/environ/test_response.py::TestResponse::test_join_thread", "cauldron/test/test_writer.py::test_write_offset_binary", "cauldron/test/test_writer.py::test_write_offset_ascii" ]
[]
[ "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_assemble_url_global_connection", "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_assemble_url_specified_connection", "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_assemble_url_without_connection", "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_download", "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_failed_download", "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_failed_download_write", "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_parse_invalid_http_response", "cauldron/test/cli/sync/test_sync_comm.py::TestSyncComm::test_parse_valid_http_response", "cauldron/test/environ/test_response.py::TestResponse::test_consume_nothing", "cauldron/test/environ/test_response.py::TestResponse::test_debug_echo", "cauldron/test/environ/test_response.py::TestResponse::test_echo", "cauldron/test/environ/test_response.py::TestResponse::test_echo_parented", "cauldron/test/environ/test_response.py::TestResponse::test_end_parented", "cauldron/test/environ/test_response.py::TestResponse::test_get_response", "cauldron/test/environ/test_response.py::TestResponse::test_grandparent", "cauldron/test/environ/test_response.py::TestResponse::test_logging", "cauldron/test/environ/test_response.py::TestResponse::test_notify_parented", "cauldron/test/environ/test_response.py::TestResponse::test_self_consumption", "cauldron/test/environ/test_response.py::TestResponse::test_update_parented", "cauldron/test/environ/test_response.py::TestResponse::test_warn", "cauldron/test/steptesting/test_functional.py::test_first_step", "cauldron/test/steptesting/test_functional.py::test_second_step", "cauldron/test/steptesting/test_functional.py::test_second_step_strict", "cauldron/test/steptesting/test_functional.py::test_second_step_with_patching", "cauldron/test/steptesting/test_functional.py::test_second_step_without_patching", "cauldron/test/steptesting/test_functional.py::test_to_strings", "cauldron/test/steptesting/test_functional.py::test_modes", "cauldron/test/steptesting/test_functional.py::test_find_in_current_path", "cauldron/test/steptesting/test_functional.py::test_find_in_parent_path", "cauldron/test/steptesting/test_functional.py::test_find_in_grandparent_path", "cauldron/test/steptesting/test_functional.py::test_find_failed_at_root", "cauldron/test/steptesting/test_functional.py::test_make_temp_path", "cauldron/test/steptesting/test_functional.py::test_no_such_step", "cauldron/test/steptesting/test_functional.py::test_no_such_project", "cauldron/test/steptesting/test_functional.py::test_open_project_fails", "cauldron/test/test_writer.py::test_write_file", "cauldron/test/test_writer.py::test_write_file_fail", "cauldron/test/test_writer.py::test_write_json", "cauldron/test/test_writer.py::test_write_json_fail", "cauldron/test/test_writer.py::test_attempt_file_write", "cauldron/test/test_writer.py::test_attempt_file_write_failed", "cauldron/test/test_writer.py::test_attempt_json_write", "cauldron/test/test_writer.py::test_attempt_json_write_failed" ]
[]
MIT License
2,596
[ "cauldron/environ/response.py", "cauldron/cli/sync/comm.py", "cauldron/environ/systems.py", "cauldron/writer.py", "cauldron/cli/sync/files.py", "cauldron/cli/sync/sync_io.py", "docker-compose.yml", "cauldron/settings.json", "cauldron/cli/server/routes/synchronize/__init__.py", "docker-run.sh" ]
[ "cauldron/environ/response.py", "cauldron/cli/sync/comm.py", "cauldron/environ/systems.py", "cauldron/writer.py", "cauldron/cli/sync/files.py", "cauldron/cli/sync/sync_io.py", "docker-compose.yml", "cauldron/settings.json", "cauldron/cli/server/routes/synchronize/__init__.py", "docker-run.sh" ]
ingresso-group__pyticketswitch-70
a22c4a3679174b1798acda89e59559930eb1f1a3
2018-05-29 18:32:26
a22c4a3679174b1798acda89e59559930eb1f1a3
codecov[bot]: # [Codecov](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70?src=pr&el=h1) Report > Merging [#70](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70?src=pr&el=desc) into [master](https://codecov.io/gh/ingresso-group/pyticketswitch/commit/a22c4a3679174b1798acda89e59559930eb1f1a3?src=pr&el=desc) will **increase** coverage by `0.02%`. > The diff coverage is `100%`. [![Impacted file tree graph](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70/graphs/tree.svg?height=150&width=650&token=LsKUTNdnRb&src=pr)](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #70 +/- ## ========================================== + Coverage 99.48% 99.51% +0.02% ========================================== Files 37 37 Lines 1764 2046 +282 ========================================== + Hits 1755 2036 +281 - Misses 9 10 +1 ``` | [Impacted Files](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [pyticketswitch/reservation.py](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70/diff?src=pr&el=tree#diff-cHl0aWNrZXRzd2l0Y2gvcmVzZXJ2YXRpb24ucHk=) | `100% <100%> (ø)` | :arrow_up: | | [pyticketswitch/exceptions.py](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70/diff?src=pr&el=tree#diff-cHl0aWNrZXRzd2l0Y2gvZXhjZXB0aW9ucy5weQ==) | `100% <100%> (ø)` | :arrow_up: | | [pyticketswitch/trolley.py](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70/diff?src=pr&el=tree#diff-cHl0aWNrZXRzd2l0Y2gvdHJvbGxleS5weQ==) | `94.73% <100%> (+0.09%)` | :arrow_up: | | [pyticketswitch/client.py](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70/diff?src=pr&el=tree#diff-cHl0aWNrZXRzd2l0Y2gvY2xpZW50LnB5) | `99.31% <100%> (+0.13%)` | :arrow_up: | | [pyticketswitch/availability.py](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70/diff?src=pr&el=tree#diff-cHl0aWNrZXRzd2l0Y2gvYXZhaWxhYmlsaXR5LnB5) | `100% <0%> (ø)` | :arrow_up: | | [pyticketswitch/mixins.py](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70/diff?src=pr&el=tree#diff-cHl0aWNrZXRzd2l0Y2gvbWl4aW5zLnB5) | `100% <0%> (ø)` | :arrow_up: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70?src=pr&el=footer). Last update [a22c4a3...3a2e91d](https://codecov.io/gh/ingresso-group/pyticketswitch/pull/70?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
diff --git a/pyticketswitch/client.py b/pyticketswitch/client.py index 8b00be5..7726b43 100644 --- a/pyticketswitch/client.py +++ b/pyticketswitch/client.py @@ -1081,7 +1081,8 @@ class Client(object): def get_trolley(self, token=None, number_of_seats=None, discounts=None, seats=None, send_codes=None, ticket_type_code=None, performance_id=None, price_band_code=None, - item_numbers_to_remove=None, **kwargs): + item_numbers_to_remove=None, + raise_on_unavailable_order=False, **kwargs): """Retrieve the contents of a trolley from the API. @@ -1097,14 +1098,17 @@ class Client(object): seats (list): list of seat IDs. send_codes (dict): send codes indexed on backend source code. - ticket_type_code: (string): code of ticket type to add to + ticket_type_code (string): code of ticket type to add to the trolley. - performance_id: (string): id of the performance to add to + performance_id (string): id of the performance to add to the trolley. - price_band_code: (string): code of price band to add to + price_band_code (string): code of price band to add to the trolley. - item_numbers_to_remove: (list): list of item numbers to + item_numbers_to_remove (list): list of item numbers to remove from trolley. + raise_on_unavailable_order (bool): When set to ``True`` this method + will raise an exception when the API was not able to add an + order to the trolley as it was unavailable. **kwargs: arbitary additional raw keyword arguments to add the parameters. @@ -1116,6 +1120,9 @@ class Client(object): Raises: InvalidParametersError: when there is an issue with the provided parameters. + OrderUnavailableError: when ``raise_on_unavailable_order`` is set + to ``True`` and the requested addition to a trolley was + unavailable. .. _`/f13/trolley.v1`: http://docs.ingresso.co.uk/#trolley @@ -1133,6 +1140,11 @@ class Client(object): trolley = Trolley.from_api_data(response) meta = CurrencyMeta.from_api_data(response) + if raise_on_unavailable_order: + if trolley and trolley.input_contained_unavailable_order: + raise exceptions.OrderUnavailableError( + "inputs contained unavailable order") + return trolley, meta def get_upsells(self, token=None, number_of_seats=None, discounts=None, @@ -1278,7 +1290,8 @@ class Client(object): def make_reservation(self, token=None, number_of_seats=None, discounts=None, seats=None, send_codes=None, ticket_type_code=None, performance_id=None, price_band_code=None, - item_numbers_to_remove=None, **kwargs): + item_numbers_to_remove=None, + raise_on_unavailable_order=False, **kwargs): """Attempt to reserve all the items in the given trolley @@ -1314,6 +1327,9 @@ class Client(object): the trolley item_numbers_to_remove: (list): list of item numbers to remove from trolley. + raise_on_unavailable_order (bool): When set to ``True`` this method + will raise an exception when the API was not able to add an + order to the trolley as it was unavailable. **kwargs: arbitary additional raw keyword arguments to add the parameters. @@ -1325,6 +1341,9 @@ class Client(object): Raises: InvalidParametersError: when there is an issue with the provided parameters. + OrderUnavailableError: when ``raise_on_unavailable_order`` is set + to ``True`` and the requested addition to a trolley was + unavailable. .. _`/f13/reserve.v1`: http://docs.ingresso.co.uk/#reserve @@ -1342,15 +1361,22 @@ class Client(object): reservation = Reservation.from_api_data(response) meta = CurrencyMeta.from_api_data(response) + if raise_on_unavailable_order: + if reservation and reservation.input_contained_unavailable_order: + raise exceptions.OrderUnavailableError( + "inputs contained unavailable order") + return reservation, meta - def release_reservation(self, transaction_uuid): + def release_reservation(self, transaction_uuid, **kwargs): """Release an existing reservation. Wraps `/f13/release.v1`_ Args: transaction_uuid (str): the identifier of the reservaiton. + **kwargs: arbitary additional raw keyword arguments to add the + parameters. Returns: bool: :obj:`True` if the reservation was successfully released @@ -1361,7 +1387,8 @@ class Client(object): """ params = {'transaction_uuid': transaction_uuid} - response = self.make_request('release.v1', params, method=POST) + kwargs.update(params) + response = self.make_request('release.v1', kwargs, method=POST) return response.get('released_ok', False) diff --git a/pyticketswitch/exceptions.py b/pyticketswitch/exceptions.py index f88f636..3aef367 100644 --- a/pyticketswitch/exceptions.py +++ b/pyticketswitch/exceptions.py @@ -51,3 +51,7 @@ class BackendThrottleError(BackendError): class CallbackGoneError(APIError): pass + + +class OrderUnavailableError(PyticketswitchError): + pass diff --git a/pyticketswitch/reservation.py b/pyticketswitch/reservation.py index b12d2bb..a75087e 100644 --- a/pyticketswitch/reservation.py +++ b/pyticketswitch/reservation.py @@ -46,9 +46,12 @@ class Reservation(Status): """ - def __init__(self, unreserved_orders=None, *args, **kwargs): + def __init__(self, unreserved_orders=None, + input_contained_unavailable_order=False, *args, **kwargs): + super(Reservation, self).__init__(*args, **kwargs) self.unreserved_orders = unreserved_orders + self.input_contained_unavailable_order = input_contained_unavailable_order @classmethod def from_api_data(cls, data): @@ -75,7 +78,9 @@ class Reservation(Status): for order in raw_unreserved_orders ] - inst.unreserved_orders=unreserved_orders + inst.unreserved_orders = unreserved_orders + inst.input_contained_unavailable_order = data.get( + 'input_contained_unavailable_order', False) return inst diff --git a/pyticketswitch/trolley.py b/pyticketswitch/trolley.py index 0a78e2e..df54c75 100644 --- a/pyticketswitch/trolley.py +++ b/pyticketswitch/trolley.py @@ -25,11 +25,14 @@ class Trolley(JSONMixin, object): order_count (int): the number of orders in the trolley. purchase_result (:class:`PurchaseResult <pyticketswitch.callout.Callout>`): the result of the purchase attempt when available. - + input_contained_unavailable_order (bool): indicates that the call used + to create or modify this trolley object included at least one order + that was not available. """ def __init__(self, token=None, transaction_uuid=None, transaction_id=None, bundles=None, discarded_orders=None, minutes_left=None, - order_count=None, purchase_result=None): + order_count=None, purchase_result=None, + input_contained_unavailable_order=False): self.token = token self.transaction_uuid = transaction_uuid self.transaction_id = transaction_id @@ -38,6 +41,7 @@ class Trolley(JSONMixin, object): self.minutes_left = minutes_left self.order_count = order_count self.purchase_result = purchase_result + self.input_contained_unavailable_order = input_contained_unavailable_order @classmethod def from_api_data(cls, data): @@ -82,6 +86,8 @@ class Trolley(JSONMixin, object): 'transaction_uuid': raw_contents.get('transaction_uuid'), 'transaction_id': raw_contents.get('transaction_id'), 'order_count': data.get('trolley_order_count'), + 'input_contained_unavailable_order': data.get( + 'input_contained_unavailable_order', False), } minutes = data.get('minutes_left_on_reserve')
missing "input_contained_unavailable_order" flag in trolley/reservation response Currently when you attempt to add something to a trolley that is not available (sold out, performance in the past, max tickets per order exceeded, etc) it just appears as an empty trolley without any indication that something has gone wrong. The API returns the `input_contained_unavailable_order` flag in it's response from `trolley.v1` and `reserve.v1`, and this should be added to the trolley object. I would suggest we should look at raising an exception as well.
ingresso-group/pyticketswitch
diff --git a/tests/test_client.py b/tests/test_client.py index 6dfc234..c339059 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1320,6 +1320,34 @@ class TestClient: assert 'gbp' in meta.currencies assert meta.default_currency_code == 'gbp' + def test_get_trolley_with_unavailable_order(self, client, monkeypatch): + """ + This test is to check that an unavailable order doesn't raise + any exceptions unless `raise_on_unavailable_order` is set to true + """ + response = { + 'trolley_contents': {}, + 'trolley_token': 'DEF456', + 'currency_code': 'gbp', + 'input_contained_unavailable_order': True, + 'currency_details': { + 'gbp': { + 'currency_code': 'gbp', + } + } + } + + mock_make_request = Mock(return_value=response) + monkeypatch.setattr(client, 'make_request', mock_make_request) + + # this should not raise any exceptions + client.get_trolley() + + # but this should + with pytest.raises(exceptions.OrderUnavailableError): + client.get_trolley(raise_on_unavailable_order=True) + + def test_get_upsells(self, client, monkeypatch): # fakes response = { @@ -1409,6 +1437,26 @@ class TestClient: assert 'gbp' in meta.currencies assert meta.default_currency_code == 'gbp' + def test_make_reservation_with_unavailable_order(self, client, monkeypatch): + """ + This test is to check that an unavailable order doesn't raise + any exceptions unless `raise_on_unavailable_order` is set to true + """ + data = { + "input_contained_unavailable_order": True, + "unreserved_orders": [], + } + + mock_make_request = Mock(return_value=data) + monkeypatch.setattr(client, 'make_request', mock_make_request) + + # this should not raise any exceptions + client.make_reservation() + + # but this should + with pytest.raises(exceptions.OrderUnavailableError): + client.make_reservation(raise_on_unavailable_order=True) + def test_get_status(self, client, monkeypatch): response = { 'trolley_contents': { diff --git a/tests/test_reservation.py b/tests/test_reservation.py index 91c0895..28bbf74 100644 --- a/tests/test_reservation.py +++ b/tests/test_reservation.py @@ -59,3 +59,13 @@ class TestReservation: assert len(reservation.unreserved_orders) == 1 assert reservation.minutes_left == 15 + + def test_from_api_data_with_unavailable_orders(self): + data = { + "input_contained_unavailable_order": True, + "unreserved_orders": [], + } + + reservation = Reservation.from_api_data(data) + + assert reservation.input_contained_unavailable_order is True diff --git a/tests/test_trolley.py b/tests/test_trolley.py index fb9b9df..0370757 100644 --- a/tests/test_trolley.py +++ b/tests/test_trolley.py @@ -68,6 +68,23 @@ class TestTrolley: assert trolley.discarded_orders[0].item == 3 assert trolley.discarded_orders[1].item == 6 + def test_from_api_data_with_empty_trolley(self): + data = { + "discarded_orders": [], + "input_contained_unavailable_order": True, + "trolley_token": "abc123", + "trolley_token_contents": { + "trolley_bundle_count": 0, + "trolley_order_count": 0 + } + } + + trolley = Trolley.from_api_data(data) + + assert trolley.token == 'abc123' + assert trolley.input_contained_unavailable_order is True + + def test_get_events(self): event_one = Event(id_='abc123')
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 4 }
2.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "flake8", "pylint", "pytest", "behave" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements/test.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==2.11.7 attrs==22.2.0 behave==1.2.6 certifi==2021.5.30 coverage==6.2 dill==0.3.4 distlib==0.3.9 filelock==3.4.1 flake8==5.0.4 idna==3.10 importlib-metadata==1.7.0 importlib-resources==5.4.0 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==5.2.0 multidict==5.2.0 packaging==21.3 parse==1.20.2 parse-type==0.6.0 platformdirs==2.4.0 pluggy==0.13.1 py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 PyHamcrest==2.1.0 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 -e git+https://github.com/ingresso-group/pyticketswitch.git@a22c4a3679174b1798acda89e59559930eb1f1a3#egg=pyticketswitch PyYAML==6.0.1 requests==2.9.1 requests-mock==1.11.0 six==1.11.0 toml==0.10.2 tomli==1.2.3 tox==3.14.3 typed-ast==1.5.5 typing_extensions==4.1.1 vcrpy==4.1.1 virtualenv==20.16.2 wrapt==1.16.0 yarl==1.7.2 zipp==3.6.0
name: pyticketswitch channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==2.11.7 - attrs==22.2.0 - behave==1.2.6 - coverage==6.2 - dill==0.3.4 - distlib==0.3.9 - filelock==3.4.1 - flake8==5.0.4 - idna==3.10 - importlib-metadata==1.7.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==5.2.0 - multidict==5.2.0 - packaging==21.3 - parse==1.20.2 - parse-type==0.6.0 - platformdirs==2.4.0 - pluggy==0.13.1 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pyhamcrest==2.1.0 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pyyaml==6.0.1 - requests==2.9.1 - requests-mock==1.11.0 - six==1.11.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.14.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - vcrpy==4.1.1 - virtualenv==20.16.2 - wrapt==1.16.0 - yarl==1.7.2 - zipp==3.6.0 prefix: /opt/conda/envs/pyticketswitch
[ "tests/test_client.py::TestClient::test_get_trolley_with_unavailable_order", "tests/test_client.py::TestClient::test_make_reservation_with_unavailable_order", "tests/test_reservation.py::TestReservation::test_from_api_data_with_unavailable_orders", "tests/test_trolley.py::TestTrolley::test_from_api_data_with_empty_trolley" ]
[]
[ "tests/test_client.py::TestClient::test_get_url", "tests/test_client.py::TestClient::test_make_request", "tests/test_client.py::TestClient::test_make_request_with_timeout", "tests/test_client.py::TestClient::test_make_request_with_post", "tests/test_client.py::TestClient::test_make_request_with_subuser", "tests/test_client.py::TestClient::test_make_request_with_tracking_id", "tests/test_client.py::TestClient::test_make_request_when_using_per_request_tracking_id", "tests/test_client.py::TestClient::test_make_request_bad_response_with_auth_error", "tests/test_client.py::TestClient::test_make_request_bad_response_with_error", "tests/test_client.py::TestClient::test_make_request_bad_response_without_error", "tests/test_client.py::TestClient::test_make_request_410_gone_response", "tests/test_client.py::TestClient::test_make_request_no_contents_raises", "tests/test_client.py::TestClient::test_add_optional_kwargs_extra_info", "tests/test_client.py::TestClient::test_add_optional_kwargs_reviews", "tests/test_client.py::TestClient::test_add_optional_kwargs_media", "tests/test_client.py::TestClient::test_add_optional_kwargs_cost_range", "tests/test_client.py::TestClient::test_add_optional_kwargs_best_value_offer", "tests/test_client.py::TestClient::test_add_optional_kwargs_max_saving_offer", "tests/test_client.py::TestClient::test_add_optional_kwargs_min_cost_offer", "tests/test_client.py::TestClient::test_add_optional_kwargs_top_price_offer", "tests/test_client.py::TestClient::test_add_optional_kwargs_no_singles_data", "tests/test_client.py::TestClient::test_add_optional_kwargs_cost_range_details", "tests/test_client.py::TestClient::test_add_optional_kwargs_avail_details", "tests/test_client.py::TestClient::test_add_optional_kwargs_avail_details_with_perfs", "tests/test_client.py::TestClient::test_add_optional_kwargs_source_info", "tests/test_client.py::TestClient::test_list_events", "tests/test_client.py::TestClient::test_list_events_with_keywords", "tests/test_client.py::TestClient::test_list_events_with_start_date", "tests/test_client.py::TestClient::test_list_events_with_end_date", "tests/test_client.py::TestClient::test_list_events_with_start_and_end_date", "tests/test_client.py::TestClient::test_list_events_country_code", "tests/test_client.py::TestClient::test_list_events_city_code", "tests/test_client.py::TestClient::test_list_events_geolocation", "tests/test_client.py::TestClient::test_list_events_invalid_geolocation", "tests/test_client.py::TestClient::test_list_events_include_dead", "tests/test_client.py::TestClient::test_list_events_sort_order", "tests/test_client.py::TestClient::test_list_events_pagination", "tests/test_client.py::TestClient::test_list_events_no_results", "tests/test_client.py::TestClient::test_list_events_misc_kwargs", "tests/test_client.py::TestClient::test_get_events", "tests/test_client.py::TestClient::test_get_events_event_list", "tests/test_client.py::TestClient::test_get_events_no_results", "tests/test_client.py::TestClient::test_get_events_misc_kwargs", "tests/test_client.py::TestClient::test_get_events_with_upsell", "tests/test_client.py::TestClient::test_get_events_with_addons", "tests/test_client.py::TestClient::test_get_event", "tests/test_client.py::TestClient::test_get_months", "tests/test_client.py::TestClient::test_get_months_no_results", "tests/test_client.py::TestClient::test_get_months_misc_kwargs", "tests/test_client.py::TestClient::test_list_performances_no_results", "tests/test_client.py::TestClient::test_list_performances", "tests/test_client.py::TestClient::test_list_performances_cost_range", "tests/test_client.py::TestClient::test_list_performances_best_value_offer", "tests/test_client.py::TestClient::test_list_performances_max_saving_offer", "tests/test_client.py::TestClient::test_list_performances_min_cost_offer", "tests/test_client.py::TestClient::test_list_performances_top_price_offer", "tests/test_client.py::TestClient::test_list_performances_no_singles_data", "tests/test_client.py::TestClient::test_list_performances_availability", "tests/test_client.py::TestClient::test_list_performances_pagination", "tests/test_client.py::TestClient::test_list_performances_with_start_date", "tests/test_client.py::TestClient::test_list_performancess_with_end_date", "tests/test_client.py::TestClient::test_list_performances_with_start_and_end_date", "tests/test_client.py::TestClient::test_list_performances_misc_kwargs", "tests/test_client.py::TestClient::test_get_performances", "tests/test_client.py::TestClient::test_get_performances_no_performances", "tests/test_client.py::TestClient::test_get_performances_misc_kwargs", "tests/test_client.py::TestClient::test_get_performance", "tests/test_client.py::TestClient::test_get_availability", "tests/test_client.py::TestClient::test_get_availability_with_number_of_seats", "tests/test_client.py::TestClient::test_get_availability_with_discounts", "tests/test_client.py::TestClient::test_get_availability_with_example_seats", "tests/test_client.py::TestClient::test_get_availability_with_seat_blocks", "tests/test_client.py::TestClient::test_get_availability_with_user_commission", "tests/test_client.py::TestClient::test_get_availability_no_availability", "tests/test_client.py::TestClient::test_get_send_methods", "tests/test_client.py::TestClient::test_get_send_methods_bad_data", "tests/test_client.py::TestClient::test_get_discounts", "tests/test_client.py::TestClient::test_get_discounts_bad_data", "tests/test_client.py::TestClient::test_trolley_params_with_trolley_token", "tests/test_client.py::TestClient::test_trolley_params_with_performance_id", "tests/test_client.py::TestClient::test_trolley_params_with_number_of_seats", "tests/test_client.py::TestClient::test_trolley_params_with_ticket_type_code", "tests/test_client.py::TestClient::test_trolley_params_with_price_band_code", "tests/test_client.py::TestClient::test_trolley_params_with_item_numbers_to_remove", "tests/test_client.py::TestClient::test_trolley_params_with_item_numbers_to_remove_with_no_token", "tests/test_client.py::TestClient::test_trolley_params_with_seats", "tests/test_client.py::TestClient::test_trolley_params_with_discounts", "tests/test_client.py::TestClient::test_trolley_params_with_send_codes", "tests/test_client.py::TestClient::test_trolley_params_with_invalid_send_codes", "tests/test_client.py::TestClient::test_get_trolley", "tests/test_client.py::TestClient::test_get_upsells", "tests/test_client.py::TestClient::test_get_addons", "tests/test_client.py::TestClient::test_make_reservation", "tests/test_client.py::TestClient::test_get_status", "tests/test_client.py::TestClient::test_get_status_with_trans", "tests/test_client.py::TestClient::test_test", "tests/test_client.py::TestClient::test_release_reservation", "tests/test_client.py::TestClient::test_make_purchase_card_details", "tests/test_client.py::TestClient::test_make_purchase_redirection", "tests/test_client.py::TestClient::test_make_purchase_credit", "tests/test_client.py::TestClient::test_make_purchase_opting_out_of_confirmation_email", "tests/test_client.py::TestClient::test_next_callout", "tests/test_client.py::TestClient::test_next_callout_with_additional_callout", "tests/test_client.py::TestClient::test_auth_can_be_overridden_with_subclass", "tests/test_client.py::TestClient::test_extra_params_can_be_overriden_by_subclass", "tests/test_client.py::TestClient::test_get_auth_params_raises_deprecation_warning", "tests/test_client.py::TestClient::test_make_request_using_decimal_parsing", "tests/test_client.py::TestClient::test_make_request_using_float_parsing", "tests/test_reservation.py::TestReservation::test_from_api_data", "tests/test_trolley.py::TestTrolley::test_from_api_data_with_trolley_data", "tests/test_trolley.py::TestTrolley::test_from_api_data_with_reservation_data", "tests/test_trolley.py::TestTrolley::test_get_events", "tests/test_trolley.py::TestTrolley::test_get_events_with_no_bundles", "tests/test_trolley.py::TestTrolley::test_get_event_ids", "tests/test_trolley.py::TestTrolley::test_get_bundle", "tests/test_trolley.py::TestTrolley::test_get_bundle_when_none", "tests/test_trolley.py::TestTrolley::test_get_bundle_when_no_match", "tests/test_trolley.py::TestTrolley::test_get_item", "tests/test_trolley.py::TestTrolley::test_get_orders" ]
[]
MIT License
2,597
[ "pyticketswitch/reservation.py", "pyticketswitch/client.py", "pyticketswitch/exceptions.py", "pyticketswitch/trolley.py" ]
[ "pyticketswitch/reservation.py", "pyticketswitch/client.py", "pyticketswitch/exceptions.py", "pyticketswitch/trolley.py" ]
capitalone__datacompy-18
370f7efbe1a5206c525a6da40410442a4ce8d51c
2018-05-30 04:59:48
246aad8c381f7591512f6ecef9debf6341261578
diff --git a/datacompy/core.py b/datacompy/core.py index 7fc296e..e03d75e 100644 --- a/datacompy/core.py +++ b/datacompy/core.py @@ -59,6 +59,8 @@ class Compare(object): more easily track the dataframes. df2_name : str, optional A string name for the second dataframe + ignore_spaces : bool, optional + Flag to strip whitespace (including newlines) from string columns Attributes ---------- @@ -70,7 +72,7 @@ class Compare(object): def __init__( self, df1, df2, join_columns=None, on_index=False, abs_tol=0, - rel_tol=0, df1_name='df1', df2_name='df2'): + rel_tol=0, df1_name='df1', df2_name='df2', ignore_spaces=False): if on_index and join_columns is not None: raise Exception('Only provide on_index or join_columns') @@ -93,7 +95,7 @@ class Compare(object): self.rel_tol = rel_tol self.df1_unq_rows = self.df2_unq_rows = self.intersect_rows = None self.column_stats = [] - self._compare() + self._compare(ignore_spaces) @property def df1(self): @@ -143,7 +145,7 @@ class Compare(object): if len(dataframe.drop_duplicates(subset=self.join_columns)) < len(dataframe): self._any_dupes = True - def _compare(self): + def _compare(self, ignore_spaces): """Actually run the comparison. This tries to run df1.equals(df2) first so that if they're truly equal we can tell. @@ -167,8 +169,8 @@ class Compare(object): LOG.info('Number of columns in df2 and not in df1: {}'.format( len(self.df2_unq_columns()))) LOG.debug('Merging dataframes') - self._dataframe_merge() - self._intersect_compare() + self._dataframe_merge(ignore_spaces) + self._intersect_compare(ignore_spaces) if self.matches(): LOG.info('df1 matches df2') else: @@ -186,7 +188,7 @@ class Compare(object): """Get columns that are shared between the two dataframes""" return set(self.df1.columns) & set(self.df2.columns) - def _dataframe_merge(self): + def _dataframe_merge(self, ignore_spaces): """Merge df1 to df2 on the join columns, to get df1 - df2, df2 - df1 and df1 & df2 @@ -262,7 +264,7 @@ class Compare(object): 'Number of rows in df1 and df2 (not necessarily equal): {}'.format( len(self.intersect_rows))) - def _intersect_compare(self): + def _intersect_compare(self, ignore_spaces): """Run the comparison on the intersect dataframe This loops through all columns that are shared between df1 and df2, and @@ -285,7 +287,8 @@ class Compare(object): self.intersect_rows[col_1], self.intersect_rows[col_2], self.rel_tol, - self.abs_tol) + self.abs_tol, + ignore_spaces) match_cnt = self.intersect_rows[col_match].sum() try: @@ -570,7 +573,7 @@ def render(filename, *fields): return file_open.read().format(*fields) -def columns_equal(col_1, col_2, rel_tol=0, abs_tol=0): +def columns_equal(col_1, col_2, rel_tol=0, abs_tol=0, ignore_spaces=False): """Compares two columns from a dataframe, returning a True/False series, with the same index as column 1. @@ -592,6 +595,8 @@ def columns_equal(col_1, col_2, rel_tol=0, abs_tol=0): Relative tolerance abs_tol : float, optional Absolute tolerance + ignore_spaces : bool, optional + Flag to strip whitespace (including newlines) from string columns Returns ------- @@ -616,6 +621,12 @@ def columns_equal(col_1, col_2, rel_tol=0, abs_tol=0): equal_nan=True)) except (ValueError, TypeError): try: + if ignore_spaces: + if col_1.dtype.kind == 'O': + col_1 = col_1.str.strip() + if col_2.dtype.kind == 'O': + col_2 = col_2.str.strip() + if set([col_1.dtype.kind, col_2.dtype.kind]) == set(['M','O']): compare = compare_string_and_date_columns(col_1, col_2) else:
Would be useful to have a parameter to strip spaces for comparison As probably expected, the following code will return a mismatch since 'B'<>'B ': ``` import pandas as pd import datacompy df1 = pd.DataFrame([ {'id': 1234, 'column_value': 'A'}, {'id': 2345, 'column_value': 'B'}]) df2 = pd.DataFrame([ {'id': 1234, 'column_value': 'A'}, {'id': 2345, 'column_value': 'B '}]) compare = datacompy.Compare( df1, df2, join_columns='id', abs_tol=0, rel_tol=0, ) compare.matches(ignore_extra_columns=False) # False # This method prints out a human-readable report summarizing and sampling differences print(compare.report()) ``` What I propose is an optional parameter to ignore differences where the only difference is leading or trailing spaces. In this example it is obvious that there is a trailing space. However, when we are dealing with extracts from different databases/source files, without real control over the ETL of these, sometimes we can't prevent these discrepancies. We may wish to ignore these types of mismatches to identify 'worse' mismatches more effectively. Another candidate could be ignoring case sensitivity differences. Of course these could both be easily handled with preprocessing the dataframes, but still could be some convenient enhancements!
capitalone/datacompy
diff --git a/tests/test_core.py b/tests/test_core.py index d236427..f3e8437 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -85,6 +85,28 @@ something||False assert_series_equal(expect_out, actual_out, check_names=False) +def test_string_columns_equal_with_ignore_spaces(): + data = '''a|b|expected +Hi|Hi|True +Yo|Yo|True +Hey|Hey |True +résumé|resume|False +résumé|résumé|True +💩|💩|True +💩|🤔|False + | |True + | |True +datacompy|DataComPy|False +something||False +|something|False +||True''' + df = pd.read_csv(six.StringIO(data), sep='|') + actual_out = datacompy.columns_equal( + df.a, df.b, rel_tol=0.2, ignore_spaces=True) + expect_out = df['expected'] + assert_series_equal(expect_out, actual_out, check_names=False) + + def test_date_columns_equal(): data = '''a|b|expected 2017-01-01|2017-01-01|True @@ -110,6 +132,34 @@ def test_date_columns_equal(): assert_series_equal(expect_out, actual_out_rev, check_names=False) +def test_date_columns_equal_with_ignore_spaces(): + data = '''a|b|expected +2017-01-01|2017-01-01 |True +2017-01-02 |2017-01-02|True +2017-10-01 |2017-10-10 |False +2017-01-01||False +|2017-01-01|False +||True''' + df = pd.read_csv(six.StringIO(data), sep='|') + #First compare just the strings + actual_out = datacompy.columns_equal( + df.a, df.b, rel_tol=0.2, ignore_spaces=True) + expect_out = df['expected'] + assert_series_equal(expect_out, actual_out, check_names=False) + + #Then compare converted to datetime objects + df['a'] = pd.to_datetime(df['a']) + df['b'] = pd.to_datetime(df['b']) + actual_out = datacompy.columns_equal( + df.a, df.b, rel_tol=0.2, ignore_spaces=True) + expect_out = df['expected'] + assert_series_equal(expect_out, actual_out, check_names=False) + #and reverse + actual_out_rev = datacompy.columns_equal( + df.b, df.a, rel_tol=0.2, ignore_spaces=True) + assert_series_equal(expect_out, actual_out_rev, check_names=False) + + def test_date_columns_unequal(): """I want datetime fields to match with dates stored as strings @@ -250,6 +300,20 @@ def test_mixed_column(): assert_series_equal(expect_out, actual_out, check_names=False) +def test_mixed_column_with_ignore_spaces(): + df = pd.DataFrame([ + {'a': 'hi', 'b': 'hi ', 'expected': True}, + {'a': 1, 'b': 1, 'expected': True}, + {'a': np.inf, 'b': np.inf, 'expected': True}, + {'a': Decimal('1'), 'b': Decimal('1'), 'expected': True}, + {'a': 1, 'b': '1 ', 'expected': False}, + {'a': 1, 'b': 'yo ', 'expected': False} + ]) + actual_out = datacompy.columns_equal(df.a, df.b, ignore_spaces=True) + expect_out = df['expected'] + assert_series_equal(expect_out, actual_out, check_names=False) + + def test_compare_df_setter_bad(): df = pd.DataFrame([{'a': 1, 'A': 2}, {'a': 2, 'A': 2}]) with raises(TypeError, message='df1 must be a pandas DataFrame'): @@ -565,4 +629,52 @@ def test_dupes_from_real_data(): assert compare_unq.matches() #Just render the report to make sure it renders. t = compare_acct.report() - r = compare_unq.report() \ No newline at end of file + r = compare_unq.report() + + +def test_strings_with_joins_with_ignore_spaces(): + df1 = pd.DataFrame([{'a': 'hi', 'b': ' A'}, {'a': 'bye', 'b': 'A'}]) + df2 = pd.DataFrame([{'a': 'hi', 'b': 'A'}, {'a': 'bye', 'b': 'A '}]) + compare = datacompy.Compare(df1, df2, 'a', ignore_spaces=False) + assert not compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert not compare.intersect_rows_match() + + compare = datacompy.Compare(df1, df2, 'a', ignore_spaces=True) + assert compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert compare.intersect_rows_match() + + +def test_decimal_with_joins_with_ignore_spaces(): + df1 = pd.DataFrame([{'a': 1, 'b': ' A'}, {'a': 2, 'b': 'A'}]) + df2 = pd.DataFrame([{'a': 1, 'b': 'A'}, {'a': 2, 'b': 'A '}]) + compare = datacompy.Compare(df1, df2, 'a', ignore_spaces=False) + assert not compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert not compare.intersect_rows_match() + + compare = datacompy.Compare(df1, df2, 'a', ignore_spaces=True) + assert compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert compare.intersect_rows_match() + + +def test_index_with_joins_with_ignore_spaces(): + df1 = pd.DataFrame([{'a': 1, 'b': ' A'}, {'a': 2, 'b': 'A'}]) + df2 = pd.DataFrame([{'a': 1, 'b': 'A'}, {'a': 2, 'b': 'A '}]) + compare = datacompy.Compare(df1, df2, on_index=True, ignore_spaces=False) + assert not compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert not compare.intersect_rows_match() + + compare = datacompy.Compare(df1, df2, 'a', ignore_spaces=True) + assert compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert compare.intersect_rows_match()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest>=3.0.6" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 -e git+https://github.com/capitalone/datacompy.git@370f7efbe1a5206c525a6da40410442a4ce8d51c#egg=datacompy importlib-metadata==4.8.3 iniconfig==1.1.1 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: datacompy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/datacompy
[ "tests/test_core.py::test_string_columns_equal_with_ignore_spaces", "tests/test_core.py::test_date_columns_equal_with_ignore_spaces", "tests/test_core.py::test_mixed_column_with_ignore_spaces", "tests/test_core.py::test_strings_with_joins_with_ignore_spaces", "tests/test_core.py::test_decimal_with_joins_with_ignore_spaces", "tests/test_core.py::test_index_with_joins_with_ignore_spaces" ]
[ "tests/test_core.py::test_compare_df_setter_bad", "tests/test_core.py::test_compare_df_setter_bad_index", "tests/test_core.py::test_compare_on_index_and_join_columns", "tests/test_core.py::test_simple_dupes_index" ]
[ "tests/test_core.py::test_numeric_columns_equal_abs", "tests/test_core.py::test_numeric_columns_equal_rel", "tests/test_core.py::test_string_columns_equal", "tests/test_core.py::test_date_columns_equal", "tests/test_core.py::test_date_columns_unequal", "tests/test_core.py::test_bad_date_columns", "tests/test_core.py::test_rounded_date_columns", "tests/test_core.py::test_decimal_float_columns_equal", "tests/test_core.py::test_decimal_float_columns_equal_rel", "tests/test_core.py::test_decimal_columns_equal", "tests/test_core.py::test_decimal_columns_equal_rel", "tests/test_core.py::test_infinity_and_beyond", "tests/test_core.py::test_mixed_column", "tests/test_core.py::test_compare_df_setter_good", "tests/test_core.py::test_compare_df_setter_different_cases", "tests/test_core.py::test_compare_df_setter_good_index", "tests/test_core.py::test_columns_overlap", "tests/test_core.py::test_columns_no_overlap", "tests/test_core.py::test_10k_rows", "tests/test_core.py::test_subset", "tests/test_core.py::test_not_subset", "tests/test_core.py::test_large_subset", "tests/test_core.py::test_string_joiner", "tests/test_core.py::test_decimal_with_joins", "tests/test_core.py::test_decimal_with_nulls", "tests/test_core.py::test_strings_with_joins", "tests/test_core.py::test_index_joining", "tests/test_core.py::test_index_joining_strings_i_guess", "tests/test_core.py::test_index_joining_non_overlapping", "tests/test_core.py::test_temp_column_name", "tests/test_core.py::test_temp_column_name_one_has", "tests/test_core.py::test_temp_column_name_both_have", "tests/test_core.py::test_temp_column_name_one_already", "tests/test_core.py::test_simple_dupes_one_field", "tests/test_core.py::test_simple_dupes_two_fields", "tests/test_core.py::test_simple_dupes_one_field_two_vals", "tests/test_core.py::test_simple_dupes_one_field_three_to_two_vals", "tests/test_core.py::test_dupes_from_real_data" ]
[]
Apache License 2.0
2,598
[ "datacompy/core.py" ]
[ "datacompy/core.py" ]
elastic__rally-514
fc63d066a0a28fe7a683d4d41acc2ab2bd53d522
2018-05-30 07:18:45
085e3d482717d88dfc2d41aa34502eb108abbfe9
diff --git a/docs/metrics.rst b/docs/metrics.rst index 6681f90e..bf24fb91 100644 --- a/docs/metrics.rst +++ b/docs/metrics.rst @@ -143,12 +143,12 @@ Rally stores the following metrics: * ``segments_terms_memory_in_bytes``: Number of bytes used for terms as reported by the indices stats API. * ``segments_norms_memory_in_bytes``: Number of bytes used for norms as reported by the indices stats API. * ``segments_points_memory_in_bytes``: Number of bytes used for points as reported by the indices stats API. -* ``merges_total_time``: Total runtime of merges as reported by the indices stats API. Note that this is not Wall clock time (i.e. if M merge threads ran for N minutes, we will report M * N minutes, not N minutes). -* ``merges_total_throttled_time``: Total time within merges have been throttled as reported by the indices stats API. Note that this is not Wall clock time. -* ``indexing_total_time``: Total time used for indexing as reported by the indices stats API. Note that this is not Wall clock time. -* ``indexing_throttle_time``: Total time that indexing has been throttled as reported by the indices stats API. Note that this is not Wall clock time. -* ``refresh_total_time``: Total time used for index refresh as reported by the indices stats API. Note that this is not Wall clock time. -* ``flush_total_time``: Total time used for index flush as reported by the indices stats API. Note that this is not Wall clock time. +* ``merges_total_time``: Total runtime of merges as reported by the indices stats API. Note that this is not Wall clock time (i.e. if M merge threads ran for N minutes, we will report M * N minutes, not N minutes). These metrics records also have a ``per-shard`` property that contains the times per primary shard in an array. +* ``merges_total_throttled_time``: Total time within merges have been throttled as reported by the indices stats API. Note that this is not Wall clock time. These metrics records also have a ``per-shard`` property that contains the times per primary shard in an array. +* ``indexing_total_time``: Total time used for indexing as reported by the indices stats API. Note that this is not Wall clock time. These metrics records also have a ``per-shard`` property that contains the times per primary shard in an array. +* ``indexing_throttle_time``: Total time that indexing has been throttled as reported by the indices stats API. Note that this is not Wall clock time. These metrics records also have a ``per-shard`` property that contains the times per primary shard in an array. +* ``refresh_total_time``: Total time used for index refresh as reported by the indices stats API. Note that this is not Wall clock time. These metrics records also have a ``per-shard`` property that contains the times per primary shard in an array. +* ``flush_total_time``: Total time used for index flush as reported by the indices stats API. Note that this is not Wall clock time. These metrics records also have a ``per-shard`` property that contains the times per primary shard in an array. * ``final_index_size_bytes``: Final resulting index size on the file system after all nodes have been shutdown at the end of the benchmark. It includes all files in the nodes' data directories (actual index files and translog). * ``store_size_in_bytes``: The size in bytes of the index (excluding the translog) as reported by the indices stats API. * ``translog_size_in_bytes``: The size in bytes of the translog as reported by the indices stats API. diff --git a/docs/summary_report.rst b/docs/summary_report.rst index e883466e..112fdb3d 100644 --- a/docs/summary_report.rst +++ b/docs/summary_report.rst @@ -9,36 +9,71 @@ Total indexing time * **Definition**: Total time used for indexing as reported by the indices stats API. Note that this is not Wall clock time (i.e. if M indexing threads ran for N minutes, we will report M * N minutes, not N minutes). * **Corresponding metrics key**: ``indexing_total_time`` +Indexing time per shard +----------------------- + +* **Definition**: Minimum, median and maximum time used for indexing per primary shard as reported by the indices stats API. +* **Corresponding metrics key**: ``indexing_total_time`` (property: ``per-shard``) + Total indexing throttle time ---------------------------- * **Definition**: Total time that indexing has been throttled as reported by the indices stats API. Note that this is not Wall clock time (i.e. if M indexing threads ran for N minutes, we will report M * N minutes, not N minutes). * **Corresponding metrics key**: ``indexing_throttle_time`` +Indexing throttle time per shard +-------------------------------- + +* **Definition**: Minimum, median and maximum time used that indexing has been throttled per primary shard as reported by the indices stats API. +* **Corresponding metrics key**: ``indexing_throttle_time`` (property: ``per-shard``) + Total merge time ---------------- * **Definition**: Total runtime of merges as reported by the indices stats API. Note that this is not Wall clock time. * **Corresponding metrics key**: ``merges_total_time`` +Merge time per shard +-------------------- + +* **Definition**: Minimum, median and maximum time of merges per primary shard as reported by the indices stats API. +* **Corresponding metrics key**: ``merges_total_time`` (property: ``per-shard``) + Total refresh time ------------------ * **Definition**: Total time used for index refresh as reported by the indices stats API. Note that this is not Wall clock time. * **Corresponding metrics key**: ``refresh_total_time`` +Refresh time per shard +---------------------- + +* **Definition**: Minimum, median and maximum time for index refresh per primary shard as reported by the indices stats API. +* **Corresponding metrics key**: ``refresh_total_time`` (property: ``per-shard``) + Total flush time ---------------- * **Definition**: Total time used for index flush as reported by the indices stats API. Note that this is not Wall clock time. * **Corresponding metrics key**: ``flush_total_time`` +Flush time per shard +-------------------- + +* **Definition**: Minimum, median and maximum time for index flush per primary shard as reported by the indices stats API. +* **Corresponding metrics key**: ``flush_total_time`` (property: ``per-shard``) + Total merge throttle time ------------------------- * **Definition**: Total time within merges have been throttled as reported by the indices stats API. Note that this is not Wall clock time. * **Corresponding metrics key**: ``merges_total_throttled_time`` +Merge throttle time per shard +----------------------------- + +* **Definition**: Minimum, median and maximum time that merges have been throttled per primary shard as reported by the indices stats API. +* **Corresponding metrics key**: ``merges_total_throttled_time`` (property: ``per-shard``) Merge time (``X``) ------------------ @@ -54,7 +89,7 @@ Where ``X`` is one of: .. -* **Definition**: Different merge times as reported by Lucene. Only available if Lucene index writer trace logging is enabled (use `--car-params="verbose_iw_logging_enabled:true"` for that). +* **Definition**: Different merge times as reported by Lucene. Only available if Lucene index writer trace logging is enabled (use ``--car-params="verbose_iw_logging_enabled:true"`` for that). * **Corresponding metrics keys**: ``merge_parts_total_time_*`` diff --git a/esrally/mechanic/telemetry.py b/esrally/mechanic/telemetry.py index 839b5809..a09ec2c2 100644 --- a/esrally/mechanic/telemetry.py +++ b/esrally/mechanic/telemetry.py @@ -7,7 +7,7 @@ import tabulate import threading from esrally import metrics, time, exceptions -from esrally.utils import io, sysstats, process, console, versions +from esrally.utils import io, sysstats, console, versions def list_telemetry(): @@ -1047,11 +1047,12 @@ class IndexStats(InternalTelemetryDevice): # the pipeline "benchmark-only" where we don't have control over the cluster and the user might not have restarted # the cluster so we can at least tell them. if self.first_time: - index_times = self.index_times(self.index_stats()["primaries"]) - for k, v in index_times.items(): - if v > 0: + for t in self.index_times(self.index_stats(), per_shard_stats=False): + n = t["name"] + v = t["value"] + if t["value"] > 0: console.warn("%s is %d ms indicating that the cluster is not in a defined clean state. Recorded index time " - "metrics may be misleading." % (k, v), logger=self.logger) + "metrics may be misleading." % (n, v), logger=self.logger) self.first_time = False def on_benchmark_stop(self): @@ -1059,43 +1060,66 @@ class IndexStats(InternalTelemetryDevice): self.logger.info("Gathering indices stats for all primaries on benchmark stop.") index_stats = self.index_stats() self.logger.info("Returned indices stats:\n%s", json.dumps(index_stats, indent=2)) - if "primaries" not in index_stats: + if "_all" not in index_stats or "primaries" not in index_stats["_all"]: return - p = index_stats["primaries"] + p = index_stats["_all"]["primaries"] # actually this is add_count self.add_metrics(self.extract_value(p, ["segments", "count"]), "segments_count") self.add_metrics(self.extract_value(p, ["segments", "memory_in_bytes"]), "segments_memory_in_bytes", "byte") - for metric_key, value in self.index_times(p).items(): - self.logger.info("Adding [%s] = [%s] to metrics store.", str(metric_key), str(value)) - self.add_metrics(value, metric_key, "ms") + for t in self.index_times(index_stats): + self.metrics_store.put_doc(doc=t, level=metrics.MetaInfoScope.cluster) self.add_metrics(self.extract_value(p, ["segments", "doc_values_memory_in_bytes"]), "segments_doc_values_memory_in_bytes", "byte") self.add_metrics(self.extract_value(p, ["segments", "stored_fields_memory_in_bytes"]), "segments_stored_fields_memory_in_bytes", "byte") self.add_metrics(self.extract_value(p, ["segments", "terms_memory_in_bytes"]), "segments_terms_memory_in_bytes", "byte") self.add_metrics(self.extract_value(p, ["segments", "norms_memory_in_bytes"]), "segments_norms_memory_in_bytes", "byte") self.add_metrics(self.extract_value(p, ["segments", "points_memory_in_bytes"]), "segments_points_memory_in_bytes", "byte") - self.add_metrics(self.extract_value(index_stats, ["total", "store", "size_in_bytes"]), "store_size_in_bytes", "byte") - self.add_metrics(self.extract_value(index_stats, ["total", "translog", "size_in_bytes"]), "translog_size_in_bytes", "byte") + self.add_metrics(self.extract_value(index_stats, ["_all", "total", "store", "size_in_bytes"]), "store_size_in_bytes", "byte") + self.add_metrics(self.extract_value(index_stats, ["_all", "total", "translog", "size_in_bytes"]), "translog_size_in_bytes", "byte") def index_stats(self): # noinspection PyBroadException try: - stats = self.client.indices.stats(metric="_all", level="shards") - return stats["_all"] + return self.client.indices.stats(metric="_all", level="shards") except BaseException: self.logger.exception("Could not retrieve index stats.") return {} - def index_times(self, p): - return { - "merges_total_time": self.extract_value(p, ["merges", "total_time_in_millis"], default_value=0), - "merges_total_throttled_time": self.extract_value(p, ["merges", "total_throttled_time_in_millis"], default_value=0), - "indexing_total_time": self.extract_value(p, ["indexing", "index_time_in_millis"], default_value=0), - "indexing_throttle_time": self.extract_value(p, ["indexing", "throttle_time_in_millis"], default_value=0), - "refresh_total_time": self.extract_value(p, ["refresh", "total_time_in_millis"], default_value=0), - "flush_total_time": self.extract_value(p, ["flush", "total_time_in_millis"], default_value=0) - } + def index_times(self, stats, per_shard_stats=True): + times = [] + self.index_time(times, stats, "merges_total_time", ["merges", "total_time_in_millis"], per_shard_stats), + self.index_time(times, stats, "merges_total_throttled_time", ["merges", "total_throttled_time_in_millis"], per_shard_stats), + self.index_time(times, stats, "indexing_total_time", ["indexing", "index_time_in_millis"], per_shard_stats), + self.index_time(times, stats, "indexing_throttle_time", ["indexing", "throttle_time_in_millis"], per_shard_stats), + self.index_time(times, stats, "refresh_total_time", ["refresh", "total_time_in_millis"], per_shard_stats), + self.index_time(times, stats, "flush_total_time", ["flush", "total_time_in_millis"], per_shard_stats), + return times + + def index_time(self, values, stats, name, path, per_shard_stats): + primary_total_stats = self.extract_value(stats, ["_all", "primaries"], default_value={}) + value = self.extract_value(primary_total_stats, path) + if value: + doc = { + "name": name, + "value": value, + "unit": "ms", + } + if per_shard_stats: + doc["per-shard"] = self.primary_shard_stats(stats, path) + values.append(doc) + + def primary_shard_stats(self, stats, path): + shard_stats = [] + try: + for idx, shards in stats["indices"].items(): + for shard_number, shard in shards["shards"].items(): + for shard_metrics in shard: + if shard_metrics["routing"]["primary"]: + shard_stats.append(self.extract_value(shard_metrics, path, default_value=0)) + except KeyError: + self.logger.warning("Could not determine primary shard stats at path [%s].", ",".join(path)) + return shard_stats def add_metrics(self, value, metric_key, unit=None): if value is not None: diff --git a/esrally/reporter.py b/esrally/reporter.py index 33204fe9..ea013fd3 100644 --- a/esrally/reporter.py +++ b/esrally/reporter.py @@ -3,6 +3,7 @@ import csv import io import sys import logging +import statistics import tabulate from esrally import metrics, exceptions @@ -132,11 +133,17 @@ class StatsCalculator: self.logger.debug("Gathering indexing metrics.") result.total_time = self.sum("indexing_total_time") + result.total_time_per_shard = self.shard_stats("indexing_total_time") result.indexing_throttle_time = self.sum("indexing_throttle_time") + result.indexing_throttle_time_per_shard = self.shard_stats("indexing_throttle_time") result.merge_time = self.sum("merges_total_time") + result.merge_time_per_shard = self.shard_stats("merges_total_time") result.refresh_time = self.sum("refresh_total_time") + result.refresh_time_per_shard = self.shard_stats("refresh_total_time") result.flush_time = self.sum("flush_total_time") + result.flush_time_per_shard = self.shard_stats("flush_total_time") result.merge_throttle_time = self.sum("merges_total_throttled_time") + result.merge_throttle_time_per_shard = self.shard_stats("merges_total_throttled_time") self.logger.debug("Gathering merge part metrics.") result.merge_part_time_postings = self.sum("merge_parts_total_time_postings") @@ -207,6 +214,25 @@ class StatsCalculator: "unit": unit } + def shard_stats(self, metric_name): + values = self.store.get_raw(metric_name, lap=self.lap, mapper=lambda doc: doc["per-shard"]) + unit = self.store.get_unit(metric_name) + if values: + flat_values = [w for v in values for w in v] + return { + "min": min(flat_values), + "median": statistics.median(flat_values), + "max": max(flat_values), + "unit": unit + } + else: + return { + "min": None, + "median": None, + "max": None, + "unit": unit + } + def error_rate(self, task_name): return self.store.get_error_rate(task=task_name, sample_type=metrics.SampleType.Normal, lap=self.lap) @@ -237,11 +263,17 @@ class Stats: self.op_metrics = self.v(d, "op_metrics", default=[]) self.node_metrics = self.v(d, "node_metrics", default=[]) self.total_time = self.v(d, "total_time") + self.total_time_per_shard = self.v(d, "total_time_per_shard") self.indexing_throttle_time = self.v(d, "indexing_throttle_time") + self.indexing_throttle_time_per_shard = self.v(d, "indexing_throttle_time_per_shard") self.merge_time = self.v(d, "merge_time") + self.merge_time_per_shard = self.v(d, "merge_time_per_shard") self.refresh_time = self.v(d, "refresh_time") + self.refresh_time_per_shard = self.v(d, "refresh_time_per_shard") self.flush_time = self.v(d, "flush_time") + self.flush_time_per_shard = self.v(d, "flush_time_per_shard") self.merge_throttle_time = self.v(d, "merge_throttle_time") + self.merge_throttle_time_per_shard = self.v(d, "merge_throttle_time_per_shard") self.ml_max_processing_time = self.v(d, "ml_max_processing_time") self.merge_part_time_postings = self.v(d, "merge_part_time_postings") @@ -459,14 +491,22 @@ class SummaryReporter: ) def report_total_times(self, stats): + totals = [] + totals += self.report_total_time("indexing time", stats.total_time, stats.total_time_per_shard) + totals += self.report_total_time("indexing throttle time", stats.indexing_throttle_time, stats.indexing_throttle_time_per_shard) + totals += self.report_total_time("merge time", stats.merge_time, stats.merge_time_per_shard) + totals += self.report_total_time("merge throttle time", stats.merge_throttle_time, stats.merge_throttle_time_per_shard) + totals += self.report_total_time("refresh time", stats.refresh_time, stats.refresh_time_per_shard) + totals += self.report_total_time("flush time", stats.flush_time, stats.flush_time_per_shard) + return totals + + def report_total_time(self, name, total_time, total_time_per_shard): unit = "min" return self.join( - self.line("Total indexing time", "", stats.total_time, unit, convert.ms_to_minutes), - self.line("Total indexing throttle time", "", stats.indexing_throttle_time, unit, convert.ms_to_minutes), - self.line("Total merge time", "", stats.merge_time, unit, convert.ms_to_minutes), - self.line("Total refresh time", "", stats.refresh_time, unit, convert.ms_to_minutes), - self.line("Total flush time", "", stats.flush_time, unit, convert.ms_to_minutes), - self.line("Total merge throttle time", "", stats.merge_throttle_time, unit, convert.ms_to_minutes) + self.line("Total {}".format(name), "", total_time, unit, convert.ms_to_minutes), + self.line("Min {} per shard".format(name), "", total_time_per_shard["min"], unit, convert.ms_to_minutes), + self.line("Median {} per shard".format(name), "", total_time_per_shard["median"], unit, convert.ms_to_minutes), + self.line("Max {} per shard".format(name), "", total_time_per_shard["max"], unit, convert.ms_to_minutes), ) def report_merge_part_times(self, stats): @@ -665,19 +705,38 @@ class ComparisonReporter: ) def report_total_times(self, baseline_stats, contender_stats): + totals = [] + totals += self.report_total_time("indexing time", + baseline_stats.total_time, baseline_stats.total_time_per_shard, + contender_stats.total_time, contender_stats.total_time_per_shard) + totals += self.report_total_time("indexing throttle time", + baseline_stats.indexing_throttle_time, baseline_stats.indexing_throttle_time_per_shard, + contender_stats.indexing_throttle_time, contender_stats.indexing_throttle_time_per_shard) + totals += self.report_total_time("merge time", + baseline_stats.merge_time, baseline_stats.merge_time_per_shard, + contender_stats.merge_time, contender_stats.merge_time_per_shard) + totals += self.report_total_time("merge throttle time", + baseline_stats.merge_throttle_time, baseline_stats.merge_throttle_time_per_shard, + contender_stats.merge_throttle_time, contender_stats.merge_throttle_time_per_shard) + totals += self.report_total_time("refresh time", + baseline_stats.refresh_time, baseline_stats.refresh_time_per_shard, + contender_stats.refresh_time, contender_stats.refresh_time_per_shard) + totals += self.report_total_time("flush time", + baseline_stats.flush_time, baseline_stats.flush_time_per_shard, + contender_stats.flush_time, contender_stats.flush_time_per_shard) + return totals + + def report_total_time(self, name, baseline_total, baseline_per_shard, contender_total, contender_per_shard): + unit = "min" return self.join( - self.line("Total indexing time", baseline_stats.total_time, contender_stats.total_time, "", "min", - treat_increase_as_improvement=False, formatter=convert.ms_to_minutes), - self.line("Total indexing throttle time", baseline_stats.indexing_throttle_time, contender_stats.indexing_throttle_time, "", "min", + self.line("Total {}".format(name), baseline_total, contender_total, "", unit, treat_increase_as_improvement=False, formatter=convert.ms_to_minutes), - self.line("Total merge time", baseline_stats.merge_time, contender_stats.merge_time, "", "min", + self.line("Min {} per shard".format(name), baseline_per_shard["min"], contender_per_shard["min"], "", unit, treat_increase_as_improvement=False, formatter=convert.ms_to_minutes), - self.line("Total refresh time", baseline_stats.refresh_time, contender_stats.refresh_time, "", "min", + self.line("Median {} per shard".format(name), baseline_per_shard["median"], contender_per_shard["median"], "", unit, treat_increase_as_improvement=False, formatter=convert.ms_to_minutes), - self.line("Total flush time", baseline_stats.flush_time, contender_stats.flush_time, "", "min", + self.line("Max {} per shard".format(name), baseline_per_shard["max"], contender_per_shard["max"], "", unit, treat_increase_as_improvement=False, formatter=convert.ms_to_minutes), - self.line("Total merge throttle time", baseline_stats.merge_throttle_time, contender_stats.merge_throttle_time, "", "min", - treat_increase_as_improvement=False, formatter=convert.ms_to_minutes) ) def report_gc_times(self, baseline_stats, contender_stats):
Overhaul confusing index time related metrics Currently we report various indexing time related metrics like which are based on the indices stats API. However, these numbers are the sum on index level (i.e. sum of all shards). This means that the number is dependent on shard count and will be usually larger than the benchmark's Wall clock time both of which can be confusing to users. Hence, we should report these numbers on shard level instead and provide min/max values.
elastic/rally
diff --git a/tests/mechanic/telemetry_test.py b/tests/mechanic/telemetry_test.py index 40a2ab4c..bd3ae5d1 100644 --- a/tests/mechanic/telemetry_test.py +++ b/tests/mechanic/telemetry_test.py @@ -1385,9 +1385,10 @@ class GcTimesSummaryTests(TestCase): class IndexStatsTests(TestCase): + @mock.patch("esrally.metrics.EsMetricsStore.put_doc") @mock.patch("esrally.metrics.EsMetricsStore.put_value_cluster_level") @mock.patch("esrally.metrics.EsMetricsStore.put_count_cluster_level") - def test_stores_available_index_stats(self, metrics_store_cluster_count, metrics_store_cluster_value): + def test_stores_available_index_stats(self, metrics_store_cluster_count, metrics_store_cluster_value, metrics_store_put_doc): client = Client(indices=SubClient({ "_all": { "primaries": { @@ -1429,17 +1430,17 @@ class IndexStatsTests(TestCase): "points_memory_in_bytes": 512 }, "merges": { - "total_time_in_millis": 300, - "total_throttled_time_in_millis": 120 + "total_time_in_millis": 509341, + "total_throttled_time_in_millis": 98925 }, "indexing": { - "index_time_in_millis": 2000 + "index_time_in_millis": 1065688 }, "refresh": { - "total_time_in_millis": 200 + "total_time_in_millis": 158465 }, "flush": { - "total_time_in_millis": 100 + "total_time_in_millis": 19082 } }, "total": { @@ -1453,21 +1454,144 @@ class IndexStatsTests(TestCase): "uncommitted_size_in_bytes": 430 } } + }, + "indices": { + "idx-001": { + "shards": { + "0": [ + { + "routing": { + "primary": False + }, + "indexing": { + "index_total": 2280171, + "index_time_in_millis": 533662, + "throttle_time_in_millis": 0 + }, + "merges": { + "total_time_in_millis": 280689, + "total_stopped_time_in_millis": 0, + "total_throttled_time_in_millis": 58846, + "total_auto_throttle_in_bytes": 8085428 + }, + "refresh": { + "total_time_in_millis": 81004 + }, + "flush": { + "total_time_in_millis": 9879 + } + } + ], + "1": [ + { + "routing": { + "primary": True, + }, + "indexing": { + "index_time_in_millis": 532026, + }, + "merges": { + "total_time_in_millis": 228652, + "total_throttled_time_in_millis": 40079, + }, + "refresh": { + "total_time_in_millis": 77461, + }, + "flush": { + "total_time_in_millis": 9203 + } + } + ] + } + }, + "idx-002": { + "shards": { + "0": [ + { + "routing": { + "primary": True, + }, + "indexing": { + "index_time_in_millis": 533662, + }, + "merges": { + "total_time_in_millis": 280689, + "total_throttled_time_in_millis": 58846, + }, + "refresh": { + "total_time_in_millis": 81004, + }, + "flush": { + "total_time_in_millis": 9879 + } + } + ], + "1": [ + { + "routing": { + "primary": False, + }, + "indexing": { + "index_time_in_millis": 532026, + "throttle_time_in_millis": 296 + }, + "merges": { + "total_time_in_millis": 228652, + "total_throttled_time_in_millis": 40079, + }, + "refresh": { + "total_time_in_millis": 77461, + }, + "flush": { + "total_time_in_millis": 9203 + } + } + ] + } + } } }) t.on_benchmark_stop() + metrics_store_put_doc.assert_has_calls([ + mock.call(doc={ + "name": "merges_total_time", + "value": 509341, + "unit": "ms", + "per-shard": [228652, 280689] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "merges_total_throttled_time", + "value": 98925, + "unit": "ms", + "per-shard": [40079, 58846] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "indexing_total_time", + "value": 1065688, + "unit": "ms", + "per-shard": [532026, 533662] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "refresh_total_time", + "value": 158465, + "unit": "ms", + "per-shard": [77461, 81004] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "flush_total_time", + "value": 19082, + "unit": "ms", + "per-shard": [9203, 9879] + }, level=metrics.MetaInfoScope.cluster), + ]) + metrics_store_cluster_count.assert_has_calls([ mock.call("segments_count", 5) ]) metrics_store_cluster_value.assert_has_calls([ mock.call("segments_memory_in_bytes", 2048, "byte"), - mock.call("merges_total_time", 300, "ms"), - mock.call("merges_total_throttled_time", 120, "ms"), - mock.call("indexing_total_time", 2000, "ms"), - mock.call("refresh_total_time", 200, "ms"), - mock.call("flush_total_time", 100, "ms"), mock.call("segments_doc_values_memory_in_bytes", 128, "byte"), mock.call("segments_stored_fields_memory_in_bytes", 1024, "byte"), mock.call("segments_terms_memory_in_bytes", 256, "byte"), @@ -1476,9 +1600,10 @@ class IndexStatsTests(TestCase): mock.call("translog_size_in_bytes", 2647984713, "byte"), ], any_order=True) + @mock.patch("esrally.metrics.EsMetricsStore.put_doc") @mock.patch("esrally.metrics.EsMetricsStore.put_value_cluster_level") @mock.patch("esrally.metrics.EsMetricsStore.put_count_cluster_level") - def test_index_stats_are_per_lap(self, metrics_store_cluster_count, metrics_store_cluster_value): + def test_index_stats_are_per_lap(self, metrics_store_cluster_count, metrics_store_cluster_value, metrics_store_put_doc): client = Client(indices=SubClient({ "_all": { "primaries": { @@ -1569,14 +1694,74 @@ class IndexStatsTests(TestCase): t.on_benchmark_stop() + metrics_store_put_doc.assert_has_calls([ + # 1st lap + mock.call(doc={ + "name": "merges_total_time", + "value": 300, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "merges_total_throttled_time", + "value": 120, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "indexing_total_time", + "value": 2000, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "refresh_total_time", + "value": 200, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "flush_total_time", + "value": 100, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + # 2nd lap + mock.call(doc={ + "name": "merges_total_time", + "value": 900, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "merges_total_throttled_time", + "value": 120, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "indexing_total_time", + "value": 8000, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "refresh_total_time", + "value": 500, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + mock.call(doc={ + "name": "flush_total_time", + "value": 300, + "unit": "ms", + "per-shard": [] + }, level=metrics.MetaInfoScope.cluster), + ]) + metrics_store_cluster_value.assert_has_calls([ # 1st lap mock.call("segments_memory_in_bytes", 2048, "byte"), - mock.call("merges_total_time", 300, "ms"), - mock.call("merges_total_throttled_time", 120, "ms"), - mock.call("indexing_total_time", 2000, "ms"), - mock.call("refresh_total_time", 200, "ms"), - mock.call("flush_total_time", 100, "ms"), mock.call("segments_doc_values_memory_in_bytes", 128, "byte"), mock.call("segments_stored_fields_memory_in_bytes", 1024, "byte"), mock.call("segments_terms_memory_in_bytes", 256, "byte"), @@ -1584,11 +1769,6 @@ class IndexStatsTests(TestCase): # 2nd lap mock.call("segments_memory_in_bytes", 2048, "byte"), - mock.call("merges_total_time", 900, "ms"), - mock.call("merges_total_throttled_time", 120, "ms"), - mock.call("indexing_total_time", 8000, "ms"), - mock.call("refresh_total_time", 500, "ms"), - mock.call("flush_total_time", 300, "ms"), mock.call("segments_doc_values_memory_in_bytes", 128, "byte"), mock.call("segments_stored_fields_memory_in_bytes", 1024, "byte"), mock.call("segments_terms_memory_in_bytes", 256, "byte"),
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 4 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-benchmark" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 elasticsearch==6.2.0 -e git+https://github.com/elastic/rally.git@fc63d066a0a28fe7a683d4d41acc2ab2bd53d522#egg=esrally importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==2.9.5 jsonschema==2.5.1 MarkupSafe==2.0.1 packaging==21.3 pluggy==1.0.0 psutil==5.4.0 py==1.11.0 py-cpuinfo==3.2.0 pyparsing==3.1.4 pytest==7.0.1 pytest-benchmark==3.4.1 tabulate==0.8.1 thespian==3.9.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.22 zipp==3.6.0
name: rally channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - elasticsearch==6.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==2.9.5 - jsonschema==2.5.1 - markupsafe==2.0.1 - packaging==21.3 - pluggy==1.0.0 - psutil==5.4.0 - py==1.11.0 - py-cpuinfo==3.2.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-benchmark==3.4.1 - tabulate==0.8.1 - thespian==3.9.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.22 - zipp==3.6.0 prefix: /opt/conda/envs/rally
[ "tests/mechanic/telemetry_test.py::IndexStatsTests::test_index_stats_are_per_lap", "tests/mechanic/telemetry_test.py::IndexStatsTests::test_stores_available_index_stats" ]
[]
[ "tests/mechanic/telemetry_test.py::TelemetryTests::test_merges_options_set_by_different_devices", "tests/mechanic/telemetry_test.py::StartupTimeTests::test_store_calculated_metrics", "tests/mechanic/telemetry_test.py::MergePartsDeviceTests::test_store_calculated_metrics", "tests/mechanic/telemetry_test.py::MergePartsDeviceTests::test_store_nothing_if_no_metrics_present", "tests/mechanic/telemetry_test.py::JfrTests::test_sets_options_for_java_9_or_above_custom_recording_template", "tests/mechanic/telemetry_test.py::JfrTests::test_sets_options_for_java_9_or_above_default_recording_template", "tests/mechanic/telemetry_test.py::JfrTests::test_sets_options_for_pre_java_9_custom_recording_template", "tests/mechanic/telemetry_test.py::JfrTests::test_sets_options_for_pre_java_9_default_recording_template", "tests/mechanic/telemetry_test.py::GcTests::test_sets_options_for_java_9_or_above", "tests/mechanic/telemetry_test.py::GcTests::test_sets_options_for_pre_java_9", "tests/mechanic/telemetry_test.py::CcrStatsTests::test_negative_sample_interval_forbidden", "tests/mechanic/telemetry_test.py::CcrStatsTests::test_wrong_cluster_name_in_ccr_stats_indices_forbidden", "tests/mechanic/telemetry_test.py::CcrStatsRecorderTests::test_raises_exception_on_transport_error", "tests/mechanic/telemetry_test.py::CcrStatsRecorderTests::test_stores_default_ccr_stats", "tests/mechanic/telemetry_test.py::CcrStatsRecorderTests::test_stores_default_ccr_stats_many_shards", "tests/mechanic/telemetry_test.py::CcrStatsRecorderTests::test_stores_filtered_ccr_stats", "tests/mechanic/telemetry_test.py::NodeStatsRecorderTests::test_negative_sample_interval_forbidden", "tests/mechanic/telemetry_test.py::NodeStatsRecorderTests::test_stores_all_nodes_stats", "tests/mechanic/telemetry_test.py::NodeStatsRecorderTests::test_stores_default_nodes_stats", "tests/mechanic/telemetry_test.py::ClusterEnvironmentInfoTests::test_stores_cluster_level_metrics_on_attach", "tests/mechanic/telemetry_test.py::NodeEnvironmentInfoTests::test_stores_node_level_metrics_on_attach", "tests/mechanic/telemetry_test.py::ExternalEnvironmentInfoTests::test_fallback_when_host_not_available", "tests/mechanic/telemetry_test.py::ExternalEnvironmentInfoTests::test_stores_all_node_metrics_on_attach", "tests/mechanic/telemetry_test.py::ClusterMetaDataInfoTests::test_enriches_cluster_nodes_for_elasticsearch_1_x", "tests/mechanic/telemetry_test.py::ClusterMetaDataInfoTests::test_enriches_cluster_nodes_for_elasticsearch_after_1_x", "tests/mechanic/telemetry_test.py::GcTimesSummaryTests::test_stores_only_diff_of_gc_times", "tests/mechanic/telemetry_test.py::IndexSizeTests::test_stores_index_size_for_data_paths", "tests/mechanic/telemetry_test.py::IndexSizeTests::test_stores_nothing_if_no_data_path" ]
[]
Apache License 2.0
2,599
[ "docs/metrics.rst", "esrally/mechanic/telemetry.py", "esrally/reporter.py", "docs/summary_report.rst" ]
[ "docs/metrics.rst", "esrally/mechanic/telemetry.py", "esrally/reporter.py", "docs/summary_report.rst" ]
python-pillow__Pillow-3148
06efe1826b1075444ff86015ecc1b55b309b16e8
2018-05-30 11:46:22
cba0004cdc2af5939dec0c9319272d6cdd440bce
diff --git a/docs/reference/ImageColor.rst b/docs/reference/ImageColor.rst index f3e6a6f90..187306f1b 100644 --- a/docs/reference/ImageColor.rst +++ b/docs/reference/ImageColor.rst @@ -31,6 +31,13 @@ The ImageColor module supports the following string formats: (black=0%, normal=50%, white=100%). For example, ``hsl(0,100%,50%)`` is pure red. +* Hue-Saturation-Value (HSV) functions, given as ``hsv(hue, saturation%, + value%)`` where hue and saturation are the same as HSL, and value is between + 0% and 100% (black=0%, normal=100%). For example, ``hsv(0,100%,100%)`` is + pure red. This format is also known as Hue-Saturation-Brightness (HSB), and + can be given as ``hsb(hue, saturation%, brightness%)``, where each of the + values are used as they are in HSV. + * Common HTML color names. The :py:mod:`~PIL.ImageColor` module provides some 140 standard color names, based on the colors supported by the X Window system and most web browsers. color names are case insensitive. For example, diff --git a/src/PIL/ImageColor.py b/src/PIL/ImageColor.py index 0e9702228..08c00fd54 100644 --- a/src/PIL/ImageColor.py +++ b/src/PIL/ImageColor.py @@ -101,6 +101,20 @@ def getrgb(color): int(rgb[2] * 255 + 0.5) ) + m = re.match(r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color) + if m: + from colorsys import hsv_to_rgb + rgb = hsv_to_rgb( + float(m.group(1)) / 360.0, + float(m.group(2)) / 100.0, + float(m.group(3)) / 100.0, + ) + return ( + int(rgb[0] * 255 + 0.5), + int(rgb[1] * 255 + 0.5), + int(rgb[2] * 255 + 0.5) + ) + m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color) if m:
PIL.ImageColor.getrgb add support for HSB/HSV format The current `PIL.ImageColor.getrgb` does not support [HSB/HSV](https://en.wikipedia.org/wiki/HSL_and_HSV) format, only the related HSL, but for easier conversion of some coordinates it would be nice to have support for HSB/HSV also.
python-pillow/Pillow
diff --git a/Tests/test_imagecolor.py b/Tests/test_imagecolor.py index 81ad179e6..0aac21278 100644 --- a/Tests/test_imagecolor.py +++ b/Tests/test_imagecolor.py @@ -78,10 +78,21 @@ class TestImageColor(PillowTestCase): self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(360,100%,50%)")) self.assertEqual((0, 255, 255), ImageColor.getrgb("hsl(180,100%,50%)")) + self.assertEqual((255, 0, 0), ImageColor.getrgb("hsv(0,100%,100%)")) + self.assertEqual((255, 0, 0), ImageColor.getrgb("hsv(360,100%,100%)")) + self.assertEqual((0, 255, 255), ImageColor.getrgb("hsv(180,100%,100%)")) + + # alternate format + self.assertEqual(ImageColor.getrgb("hsb(0,100%,50%)"), + ImageColor.getrgb("hsv(0,100%,50%)")) + # floats self.assertEqual((254, 3, 3), ImageColor.getrgb("hsl(0.1,99.2%,50.3%)")) self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(360.,100.0%,50%)")) + self.assertEqual((253, 2, 2), ImageColor.getrgb("hsv(0.1,99.2%,99.3%)")) + self.assertEqual((255, 0, 0), ImageColor.getrgb("hsv(360.,100.0%,100%)")) + # case insensitivity self.assertEqual(ImageColor.getrgb("RGB(255,0,0)"), ImageColor.getrgb("rgb(255,0,0)")) @@ -91,6 +102,10 @@ class TestImageColor(PillowTestCase): ImageColor.getrgb("rgba(255,0,0,0)")) self.assertEqual(ImageColor.getrgb("HSL(0,100%,50%)"), ImageColor.getrgb("hsl(0,100%,50%)")) + self.assertEqual(ImageColor.getrgb("HSV(0,100%,50%)"), + ImageColor.getrgb("hsv(0,100%,50%)")) + self.assertEqual(ImageColor.getrgb("HSB(0,100%,50%)"), + ImageColor.getrgb("hsb(0,100%,50%)")) # space agnosticism self.assertEqual((255, 0, 0), @@ -101,6 +116,8 @@ class TestImageColor(PillowTestCase): ImageColor.getrgb("rgba( 255 , 0 , 0 , 0 )")) self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl( 0 , 100% , 50% )")) + self.assertEqual((255, 0, 0), + ImageColor.getrgb("hsv( 0 , 100% , 100% )")) # wrong number of components self.assertRaises(ValueError, ImageColor.getrgb, "rgb(255,0)") @@ -120,6 +137,12 @@ class TestImageColor(PillowTestCase): self.assertRaises(ValueError, ImageColor.getrgb, "hsl(0,100,50%)") self.assertRaises(ValueError, ImageColor.getrgb, "hsl(0,100%,50)") + self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0,100%)") + self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0,100%,0%,0%)") + self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0%,100%,50%)") + self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0,100,50%)") + self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0,100%,50)") + # look for rounding errors (based on code by Tim Hatch) def test_rounding_errors(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
5.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc libjpeg-dev zlib1g-dev libtiff5-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev libharfbuzz-dev libfribidi-dev libxcb1-dev" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 babel==2.17.0 blessed==1.20.0 build==1.2.2.post1 certifi==2025.1.31 charset-normalizer==3.4.1 check-manifest==0.50 cov-core==1.15.0 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 docutils==0.21.2 exceptiongroup==1.2.2 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 jarn.viewdoc==2.7 Jinja2==3.1.6 MarkupSafe==3.0.2 olefile==0.47 packaging==24.2 -e git+https://github.com/python-pillow/Pillow.git@06efe1826b1075444ff86015ecc1b55b309b16e8#egg=Pillow pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 Pygments==2.19.1 pyproject_hooks==1.2.0 pyroma==4.2 pytest==8.3.5 pytest-cov==6.0.0 pytz==2025.2 requests==2.32.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 tomli==2.2.1 trove-classifiers==2025.3.19.19 urllib3==2.3.0 wcwidth==0.2.13 zipp==3.21.0
name: Pillow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - babel==2.17.0 - blessed==1.20.0 - build==1.2.2.post1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - check-manifest==0.50 - cov-core==1.15.0 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - docutils==0.21.2 - exceptiongroup==1.2.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jarn-viewdoc==2.7 - jinja2==3.1.6 - markupsafe==3.0.2 - olefile==0.47 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pygments==2.19.1 - pyproject-hooks==1.2.0 - pyroma==4.2 - pytest==8.3.5 - pytest-cov==6.0.0 - pytz==2025.2 - requests==2.32.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - tomli==2.2.1 - trove-classifiers==2025.3.19.19 - urllib3==2.3.0 - wcwidth==0.2.13 - zipp==3.21.0 prefix: /opt/conda/envs/Pillow
[ "Tests/test_imagecolor.py::TestImageColor::test_functions", "Tests/test_imagecolor.py::TestImageColor::test_hash", "Tests/test_imagecolor.py::TestImageColor::test_rounding_errors" ]
[]
[ "Tests/test_imagecolor.py::TestImageColor::test_colormap" ]
[]
MIT-CMU License
2,600
[ "docs/reference/ImageColor.rst", "src/PIL/ImageColor.py" ]
[ "docs/reference/ImageColor.rst", "src/PIL/ImageColor.py" ]
fniessink__next-action-88
b9bfd4e21bd2df93dc35dca32a467626b739540b
2018-05-30 18:26:43
212cdfe8673e4c4438a8b7de1a8df67da326281a
diff --git a/CHANGELOG.md b/CHANGELOG.md index f38a53a..60da2e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Removed + +- The `--no-config-file` option was removed. To not read any configuration file, use the `--config-file` option without specifying a configuration filename. + ## [0.12.0] - 2018-05-28 ### Added diff --git a/README.md b/README.md index 2e858c4..07408b3 100644 --- a/README.md +++ b/README.md @@ -15,14 +15,15 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the ## Table of contents - - [Demo](#demo) - - [Installation](#installation) - - [Usage](#usage) - - [Limiting the tasks from which next actions are selected](#limiting-the-tasks-from-which-next-actions-are-selected) - - [Showing more than one next action](#showing-more-than-one-next-action) - - [Styling the output](#styling-the-output) - - [Configuring *Next-action*](#configuring-next-action) - - [Develop](#develop) +- [Demo](#demo) +- [Installation](#installation) +- [Usage](#usage) + - [Limiting the tasks from which next actions are selected](#limiting-the-tasks-from-which-next-actions-are-selected) + - [Showing more than one next action](#showing-more-than-one-next-action) + - [Styling the output](#styling-the-output) + - [Configuring *Next-action*](#configuring-next-action) +- [Develop](#develop) + ## Demo ![gif](https://raw.githubusercontent.com/fniessink/next-action/master/docs/demo.gif) @@ -37,7 +38,7 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the ```console $ next-action --help -usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] +usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task @@ -48,9 +49,9 @@ optional arguments: -h, --help show this help message and exit --version show program's version number and exit --write-config-file generate a sample configuration file and exit - -c <config.cfg>, --config-file <config.cfg> - filename of configuration file to read (default: ~/.next-action.cfg) - -C, --no-config-file don't read the configuration file + -c [<config.cfg>], --config-file [<config.cfg>] + filename of configuration file to read (default: ~/.next-action.cfg); omit filename to not + read any configuration file -f <todo.txt>, --file <todo.txt> filename of todo.txt file to read; can be '-' to read from standard input; argument can be repeated to read tasks from multiple todo.txt files (default: ~/todo.txt) @@ -175,13 +176,15 @@ style: default To make this the configuration that *Next-action* reads by default, redirect the output to `~/.next-action.cfg` like this: `next-action --write-config-file > ~/.next-action.cfg`. -If you want to use a configuration file that is not in the default location (`~/.next-action.cfg`), you'll need to explicitly tell *Next-action* its location: +If you want to use a configuration file that is not in the default location (`~/.next-action.cfg`), you'll need to explicitly specify its location: ```console $ next-action --config-file docs/.next-action.cfg (A) Call mom @phone ``` +To skip reading the default configuration file, and also not read an alternative configuration file, use the `--config-file` option without arguments. + The configuration file format is [YAML](http://yaml.org). The options currently supported are which todo.txt files must be read, how many next actions should be shown, and the styling. #### Configuring a default todo.txt @@ -253,7 +256,7 @@ To run the unit tests: $ python -m unittest ............................................................................................................................................... ---------------------------------------------------------------------- -Ran 143 tests in 0.461s +Ran 143 tests in 0.420s OK ``` diff --git a/docs/update_readme.py b/docs/update_readme.py index 86a3553..3c77201 100644 --- a/docs/update_readme.py +++ b/docs/update_readme.py @@ -21,7 +21,7 @@ def create_toc(lines, toc_header, min_level=2, max_level=3): level = line.count("#", 0, 6) if level < min_level or level > max_level or line.startswith(toc_header): continue - indent = (level - 1) * 2 + indent = (level - min_level) * 2 title = line.split(" ", 1)[1].rstrip() slug = title.lower().replace(" ", "-").replace("*", "").replace(".", "") result.append("{0}- [{1}](#{2})".format(" " * indent, title, slug)) @@ -68,17 +68,16 @@ class StateMachine(object): def print_toc(self, line): """ Print the table of contents. """ print(self.toc) - if line.startswith(" "): + if "- [" in line: return self.in_old_toc print(line) return self.default def in_old_toc(self, line): """ Skip the old table of contents. """ - if line.startswith(" "): + if "- [" in line: return self.in_old_toc - if line: - print(line) + print(line) return self.default diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index fec3e3a..52dc719 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -22,7 +22,7 @@ class NextActionArgumentParser(argparse.ArgumentParser): "todo.txt file based on task properties such as priority, due date, and creation date. Limit " "the tasks from which the next action is selected by specifying contexts the tasks must have " "and/or projects the tasks must belong to.", - usage=textwrap.fill("next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] " + usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] " "[-n <number> | -a] [-o] [-p [<priority>]] [<context|project> ...]", width=shutil.get_terminal_size().columns - len("usage: "))) self.__default_filenames = ["~/todo.txt"] @@ -37,10 +37,9 @@ class NextActionArgumentParser(argparse.ArgumentParser): config_file.add_argument( "--write-config-file", help="generate a sample configuration file and exit", action="store_true") config_file.add_argument( - "-c", "--config-file", metavar="<config.cfg>", type=str, default="~/.next-action.cfg", - help="filename of configuration file to read (default: %(default)s)") - config_file.add_argument( - "-C", "--no-config-file", help="don't read the configuration file", action="store_true") + "-c", "--config-file", metavar="<config.cfg>", type=str, default="~/.next-action.cfg", nargs="?", + help="filename of configuration file to read (default: %(default)s); omit filename to not read any " + "configuration file") self.add_argument( "-f", "--file", action="append", metavar="<todo.txt>", default=self.__default_filenames[:], type=str, help="filename of todo.txt file to read; can be '-' to read from standard input; argument can be " @@ -86,7 +85,7 @@ class NextActionArgumentParser(argparse.ArgumentParser): """ Parse the command-line arguments. """ namespace, remaining = self.parse_known_args(args, namespace) self.parse_remaining_args(remaining, namespace) - if not namespace.no_config_file: + if getattr(namespace, "config_file", self.get_default("config_file")) is not None: self.process_config_file(namespace) if namespace.write_config_file: write_config_file()
Merge --config and --no-config options by making the config argument optional
fniessink/next-action
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py index d7e02d2..6f126d8 100644 --- a/tests/unittests/arguments/test_config.py +++ b/tests/unittests/arguments/test_config.py @@ -85,7 +85,7 @@ class ConfigFileTest(ConfigTestCase): self.assertEqual([call(USAGE_MESSAGE), call("next-action: error: can't open file: some problem\n")], mock_stderr_write.call_args_list) - @patch.object(sys, "argv", ["next-action", "--no-config-file"]) + @patch.object(sys, "argv", ["next-action", "--config-file"]) @patch.object(config, "open") def test_skip_config(self, mock_file_open): """ Test that the config file is not read if the user doesn't want to. """ diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py index 20358f6..6a262af 100644 --- a/tests/unittests/arguments/test_parser.py +++ b/tests/unittests/arguments/test_parser.py @@ -10,7 +10,7 @@ from next_action.arguments import config, parse_arguments USAGE_MESSAGE = textwrap.fill( - "usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] " + "usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] " "[-p [<priority>]] [<context|project> ...]", 120) + "\n" diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index 4778730..f26c609 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -65,7 +65,7 @@ class CLITest(unittest.TestCase): os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough. self.assertRaises(SystemExit, next_action) self.assertEqual(call("""\ -usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] +usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task @@ -76,9 +76,9 @@ optional arguments: -h, --help show this help message and exit --version show program's version number and exit --write-config-file generate a sample configuration file and exit - -c <config.cfg>, --config-file <config.cfg> - filename of configuration file to read (default: ~/.next-action.cfg) - -C, --no-config-file don't read the configuration file + -c [<config.cfg>], --config-file [<config.cfg>] + filename of configuration file to read (default: ~/.next-action.cfg); omit filename to not + read any configuration file -f <todo.txt>, --file <todo.txt> filename of todo.txt file to read; can be '-' to read from standard input; argument can be repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 4 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
Cerberus==1.2 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@b9bfd4e21bd2df93dc35dca32a467626b739540b#egg=next_action packaging==24.2 pluggy==1.5.0 Pygments==2.2.0 pytest==8.3.5 PyYAML==3.12 tomli==2.2.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cerberus==1.2 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pygments==2.2.0 - pytest==8.3.5 - pyyaml==3.12 - tomli==2.2.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config", "tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid", "tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_config.py::NumberTest::test_all_false", "tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_zero", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style", "tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number", "tests/unittests/test_cli.py::CLITest::test_help", "tests/unittests/test_cli.py::CLITest::test_missing_file" ]
[]
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config", "tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files", "tests/unittests/arguments/test_config.py::NumberTest::test_all_true", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::NumberTest::test_valid_number", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style", "tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style", "tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice", "tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename", "tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default", "tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument", "tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions", "tests/unittests/arguments/test_parser.py::NumberTest::test_default_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_number", "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_show_all_actions", "tests/unittests/test_cli.py::CLITest::test_version" ]
[]
Apache License 2.0
2,601
[ "docs/update_readme.py", "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
[ "docs/update_readme.py", "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
fniessink__next-action-89
212cdfe8673e4c4438a8b7de1a8df67da326281a
2018-05-30 19:29:27
212cdfe8673e4c4438a8b7de1a8df67da326281a
diff --git a/CHANGELOG.md b/CHANGELOG.md index 60da2e1..838c5c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] -### Removed +### Added + +- Using the `--style` option without arguments ignores the style specified in the configuration file, if any. Closes #83. + +### Changed -- The `--no-config-file` option was removed. To not read any configuration file, use the `--config-file` option without specifying a configuration filename. +- The `--no-config-file` option was removed. To not read any configuration file, use the `--config-file` option without specifying a configuration filename. Closes #82. ## [0.12.0] - 2018-05-28 diff --git a/README.md b/README.md index 07408b3..653b98d 100644 --- a/README.md +++ b/README.md @@ -38,8 +38,8 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the ```console $ next-action --help -usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] -[<context|project> ...] +usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] [-s +[<style>]] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by @@ -61,7 +61,7 @@ optional arguments: -o, --overdue show only overdue next actions -p [<priority>], --priority [<priority>] minimum priority (A-Z) of next actions to show (default: None) - -s <style>, --style <style> + -s [<style>], --style [<style>] colorize the output; available styles: abap, algol, algol_nu, arduino, autumn, borland, bw, colorful, default, emacs, friendly, fruity, igor, lovelace, manni, monokai, murphy, native, paraiso-dark, paraiso-light, pastie, perldoc, rainbow_dash, rrt, tango, trac, vim, vs, xcode @@ -160,6 +160,8 @@ The next actions can be colorized using the `--style` argument. Run `next-action When you've decided on a style you prefer, it makes sense to configure the style in the configuration file. See the section below on how to configure *Next-action*. +Not passing an argument to `--style` cancels the style that is configured in the configuration file, if any. + ### Configuring *Next-action* In addition to specifying options on the command-line, you can also configure options in a configuration file. By default, *Next-action* tries to read a file called [.next-action.cfg](https://raw.githubusercontent.com/fniessink/next-action/master/docs/.next-action.cfg) in your home folder. @@ -254,9 +256,9 @@ To run the unit tests: ```console $ python -m unittest -............................................................................................................................................... +................................................................................................................................................ ---------------------------------------------------------------------- -Ran 143 tests in 0.420s +Ran 144 tests in 0.426s OK ``` diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index 52dc719..8966b0a 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -23,7 +23,7 @@ class NextActionArgumentParser(argparse.ArgumentParser): "the tasks from which the next action is selected by specifying contexts the tasks must have " "and/or projects the tasks must belong to.", usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] " - "[-n <number> | -a] [-o] [-p [<priority>]] [<context|project> ...]", + "[-n <number> | -a] [-o] [-p [<priority>]] [-s [<style>]] [<context|project> ...]", width=shutil.get_terminal_size().columns - len("usage: "))) self.__default_filenames = ["~/todo.txt"] self.add_optional_arguments() @@ -56,7 +56,7 @@ class NextActionArgumentParser(argparse.ArgumentParser): help="minimum priority (A-Z) of next actions to show (default: %(default)s)") styles = sorted(list(get_all_styles())) self.add_argument( - "-s", "--style", metavar="<style>", choices=styles, default=None, + "-s", "--style", metavar="<style>", choices=styles, default=None, nargs="?", help="colorize the output; available styles: {0} (default: %(default)s)".format(", ".join(styles))) def add_positional_arguments(self) -> None:
Make it possible to overwrite the style in the configuration file by not passing a style to the --style argument
fniessink/next-action
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py index 6f126d8..2efa764 100644 --- a/tests/unittests/arguments/test_config.py +++ b/tests/unittests/arguments/test_config.py @@ -240,6 +240,12 @@ class ConfigStyleTest(ConfigTestCase): """ Test that a command line style overrides the style in the config file. """ self.assertEqual("vim", parse_arguments()[1].style) + @patch.object(sys, "argv", ["next-action", "--style"]) + @patch.object(config, "open", mock_open(read_data="style: default")) + def test_cancel_style(self): + """ Test that --style without style cancels the style in the config file. """ + self.assertEqual(None, parse_arguments()[1].style) + @patch.object(sys, "argv", ["next-action"]) @patch.object(config, "open", mock_open(read_data="style: invalid_style")) @patch.object(sys.stderr, "write") diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py index 6a262af..f9eebd5 100644 --- a/tests/unittests/arguments/test_parser.py +++ b/tests/unittests/arguments/test_parser.py @@ -11,7 +11,7 @@ from next_action.arguments import config, parse_arguments USAGE_MESSAGE = textwrap.fill( "usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] " - "[-p [<priority>]] [<context|project> ...]", 120) + "\n" + "[-p [<priority>]] [-s [<style>]] [<context|project> ...]", 120) + "\n" class ParserTestCase(unittest.TestCase): diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index f26c609..b477698 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -65,8 +65,8 @@ class CLITest(unittest.TestCase): os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough. self.assertRaises(SystemExit, next_action) self.assertEqual(call("""\ -usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] -[<context|project> ...] +usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] [-s +[<style>]] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by @@ -88,7 +88,7 @@ optional arguments: -o, --overdue show only overdue next actions -p [<priority>], --priority [<priority>] minimum priority (A-Z) of next actions to show (default: None) - -s <style>, --style <style> + -s [<style>], --style [<style>] colorize the output; available styles: abap, algol, algol_nu, arduino, autumn, borland, bw, colorful, default, emacs, friendly, fruity, igor, lovelace, manni, monokai, murphy, native, paraiso-dark, paraiso-light, pastie, perldoc, rainbow_dash, rrt, tango, trac, vim, vs, xcode
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
Cerberus==1.2 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@212cdfe8673e4c4438a8b7de1a8df67da326281a#egg=next_action packaging==24.2 pluggy==1.5.0 Pygments==2.2.0 pytest==8.3.5 PyYAML==3.12 tomli==2.2.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cerberus==1.2 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pygments==2.2.0 - pytest==8.3.5 - pyyaml==3.12 - tomli==2.2.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key", "tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid", "tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_config.py::NumberTest::test_all_false", "tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_zero", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style", "tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number", "tests/unittests/test_cli.py::CLITest::test_help", "tests/unittests/test_cli.py::CLITest::test_missing_file" ]
[]
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config", "tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files", "tests/unittests/arguments/test_config.py::NumberTest::test_all_true", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::NumberTest::test_valid_number", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style", "tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style", "tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice", "tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename", "tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default", "tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument", "tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions", "tests/unittests/arguments/test_parser.py::NumberTest::test_default_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_number", "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_show_all_actions", "tests/unittests/test_cli.py::CLITest::test_version" ]
[]
Apache License 2.0
2,602
[ "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
[ "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
peterbe__hashin-65
bbe0b6c379e25fbd8d3e702473e8e29677ccd9c0
2018-05-30 21:13:24
bbe0b6c379e25fbd8d3e702473e8e29677ccd9c0
diff --git a/hashin.py b/hashin.py index c1bb79b..1590560 100755 --- a/hashin.py +++ b/hashin.py @@ -58,6 +58,11 @@ parser.add_argument( help='Verbose output', action='store_true', ) +parser.add_argument( + '--include-prereleases', + help='Include pre-releases (off by default)', + action='store_true', +) parser.add_argument( '-p', '--python-version', help='Python version to add wheels for. May be used multiple times.', @@ -83,6 +88,10 @@ class PackageError(Exception): pass +class NoVersionsError(Exception): + """When there are no valid versions found.""" + + def _verbose(*args): print('* ' + ' '.join(args)) @@ -127,6 +136,7 @@ def run_single_package( algorithm, python_versions=None, verbose=False, + include_prereleases=False, ): restriction = None if ';' in spec: @@ -143,7 +153,8 @@ def run_single_package( version=version, verbose=verbose, python_versions=python_versions, - algorithm=algorithm + algorithm=algorithm, + include_prereleases=include_prereleases, ) package = data['package'] @@ -202,7 +213,7 @@ def amend_requirements_content(requirements, package, new_lines): return requirements -def get_latest_version(data): +def get_latest_version(data, include_prereleases): """ Return the version string of what we think is the latest version. In the data blob from PyPI there is the info->version key which @@ -214,11 +225,22 @@ def get_latest_version(data): # This feels kinda strange but it has worked for years return data['info']['version'] all_versions = [] + count_prereleases = 0 for version in data['releases']: v = parse(version) - if not v.is_prerelease: + if not v.is_prerelease or include_prereleases: all_versions.append((v, version)) + else: + count_prereleases += 1 all_versions.sort(reverse=True) + if not all_versions: + msg = "Not a single valid version found." + if not include_prereleases and count_prereleases: + msg += ( + " But, found {0} pre-releases. Consider running again " + "with the --include-prereleases flag." + ) + raise NoVersionsError(msg) # return the highest non-pre-release version return str(all_versions[0][1]) @@ -378,6 +400,7 @@ def get_package_hashes( algorithm=DEFAULT_ALGORITHM, python_versions=(), verbose=False, + include_prereleases=False, ): """ Gets the hashes for the given package. @@ -404,7 +427,7 @@ def get_package_hashes( """ data = get_package_data(package, verbose) if not version: - version = get_latest_version(data) + version = get_latest_version(data, include_prereleases) assert version if verbose: _verbose('Latest version for {0} is {1}'.format( @@ -472,6 +495,7 @@ def main(): args.algorithm, args.python_version, verbose=args.verbose, + include_prereleases=args.include_prereleases, ) except PackageError as exception: print(str(exception), file=sys.stderr)
`hashin black` fails ``` ▶ hashin black Traceback (most recent call last): File "/usr/local/bin/hashin", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/hashin.py", line 474, in main verbose=args.verbose, File "/usr/local/lib/python3.6/site-packages/hashin.py", line 120, in run run_single_package(spec, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/hashin.py", line 146, in run_single_package algorithm=algorithm File "/usr/local/lib/python3.6/site-packages/hashin.py", line 407, in get_package_hashes version = get_latest_version(data) File "/usr/local/lib/python3.6/site-packages/hashin.py", line 223, in get_latest_version return str(all_versions[0][1]) IndexError: list index out of range ```
peterbe/hashin
diff --git a/tests/test_arg_parse.py b/tests/test_arg_parse.py index 7d00e74..a6b6236 100644 --- a/tests/test_arg_parse.py +++ b/tests/test_arg_parse.py @@ -18,6 +18,7 @@ def test_everything(): requirements_file='reqs.txt', verbose=True, version=False, + include_prereleases=False, ) assert args == (expected, []) @@ -37,6 +38,7 @@ def test_everything_long(): requirements_file='reqs.txt', verbose=True, version=False, + include_prereleases=False, ) assert args == (expected, []) @@ -50,5 +52,6 @@ def test_minimal(): requirements_file='requirements.txt', verbose=False, version=False, + include_prereleases=False, ) assert args == (expected, []) diff --git a/tests/test_cli.py b/tests/test_cli.py index c0b566f..72cf2de 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -73,7 +73,10 @@ class Tests(TestCase): @mock.patch('hashin.urlopen') def test_get_latest_version_simple(self, murlopen): - version = hashin.get_latest_version({'info': {'version': '0.3'}}) + version = hashin.get_latest_version( + {'info': {'version': '0.3'}}, + False + ) self.assertEqual(version, '0.3') @mock.patch('hashin.urlopen') @@ -91,9 +94,43 @@ class Tests(TestCase): '2.0b2': {}, '2.0c3': {}, } - }) + }, False) self.assertEqual(version, '0.999') + @mock.patch('hashin.urlopen') + def test_get_latest_version_only_pre_release(self, murlopen): + self.assertRaises( + hashin.NoVersionsError, + hashin.get_latest_version, + { + 'info': { + 'version': '0.3', + }, + 'releases': { + '1.1.0rc1': {}, + '1.1rc1': {}, + '1.0a1': {}, + '2.0b2': {}, + '2.0c3': {}, + } + }, + False, + ) + + version = hashin.get_latest_version({ + 'info': { + 'version': '0.3', + }, + 'releases': { + '1.1.0rc1': {}, + '1.1rc1': {}, + '1.0a1': {}, + '2.0b2': {}, + '2.0c3': {}, + } + }, True) + self.assertEqual(version, '2.0c3') + @mock.patch('hashin.urlopen') def test_get_latest_version_non_pre_release_leading_zeros(self, murlopen): version = hashin.get_latest_version({ @@ -105,7 +142,7 @@ class Tests(TestCase): '0.04.21': {}, '0.04.09': {}, } - }) + }, False) self.assertEqual(version, '0.04.21') @mock.patch('hashin.urlopen')
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 -e git+https://github.com/peterbe/hashin.git@bbe0b6c379e25fbd8d3e702473e8e29677ccd9c0#egg=hashin iniconfig==2.1.0 mock==5.2.0 packaging==24.2 pip-api==0.0.34 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1
name: hashin channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - mock==5.2.0 - packaging==24.2 - pip-api==0.0.34 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/hashin
[ "tests/test_arg_parse.py::test_everything", "tests/test_arg_parse.py::test_everything_long", "tests/test_arg_parse.py::test_minimal", "tests/test_cli.py::Tests::test_get_latest_version_non_pre_release", "tests/test_cli.py::Tests::test_get_latest_version_non_pre_release_leading_zeros", "tests/test_cli.py::Tests::test_get_latest_version_only_pre_release", "tests/test_cli.py::Tests::test_get_latest_version_simple" ]
[]
[ "tests/test_cli.py::Tests::test_amend_requirements_content_new", "tests/test_cli.py::Tests::test_amend_requirements_content_new_similar_name", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement_2", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement_amonst_others", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement_amonst_others_2", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement_single_to_multi", "tests/test_cli.py::Tests::test_expand_python_version", "tests/test_cli.py::Tests::test_filter_releases", "tests/test_cli.py::Tests::test_get_hashes_error", "tests/test_cli.py::Tests::test_get_package_hashes", "tests/test_cli.py::Tests::test_get_package_hashes_unknown_algorithm", "tests/test_cli.py::Tests::test_get_package_hashes_without_version", "tests/test_cli.py::Tests::test_main_packageerrors_stderr", "tests/test_cli.py::Tests::test_main_version", "tests/test_cli.py::Tests::test_non_200_ok_download", "tests/test_cli.py::Tests::test_release_url_metadata_python", "tests/test_cli.py::Tests::test_run", "tests/test_cli.py::Tests::test_run_case_insensitive", "tests/test_cli.py::Tests::test_run_contained_names", "tests/test_cli.py::Tests::test_run_pep_0496", "tests/test_cli.py::Tests::test_run_without_specific_version" ]
[]
MIT License
2,603
[ "hashin.py" ]
[ "hashin.py" ]
HXLStandard__libhxl-python-174
1bc7e92a3844dd443f9e31f478357ea7b599c831
2018-05-30 21:52:05
1bc7e92a3844dd443f9e31f478357ea7b599c831
diff --git a/hxl/validation.py b/hxl/validation.py index 3eb1eba..922bfaf 100644 --- a/hxl/validation.py +++ b/hxl/validation.py @@ -1508,11 +1508,6 @@ def validate(data, schema=None): issue_map = dict() - def make_rule_hash(rule): - """Make a good-enough hash for a rule.""" - s = "\r".join([str(rule.severity), str(rule.description), str(rule.tag_pattern)]) - return base64.urlsafe_b64encode(hashlib.md5(s.encode('utf-8')).digest())[:8].decode('ascii') - def add_issue(issue): hash = make_rule_hash(issue.rule) issue_map.setdefault(hash, []).append(issue) @@ -1562,9 +1557,10 @@ def make_json_report(status, issue_map, schema_url=None, data_url=None): # add the issue objects for rule_id, locations in issue_map.items(): - json_report['stats']['total'] += len(locations) - json_report['stats'][locations[0].rule.severity] += len(locations) - json_report['issues'].append(make_json_issue(rule_id, locations)) + json_issue = make_json_issue(rule_id, locations) + json_report['stats']['total'] += len(json_issue['locations']) + json_report['stats'][locations[0].rule.severity] += len(json_issue['locations']) + json_report['issues'].append(json_issue) return json_report @@ -1581,6 +1577,15 @@ def make_json_issue(rule_id, locations): if not description: description = model.message + # get all unique locations + location_keys = set() + json_locations = [] + for location in locations: + location_key = (location.row.row_number, location.column.column_number, location.value, location.suggested_value,) + if not location_key in location_keys: + json_locations.append(make_json_location(location)) + location_keys.add(location_key) + # make the issue json_issue = { "rule_id": rule_id, @@ -1589,7 +1594,7 @@ def make_json_issue(rule_id, locations): "severity": model.rule.severity, "location_count": len(locations), "scope": model.scope, - "locations": [make_json_location(location) for location in locations] + "locations": json_locations } return json_issue @@ -1622,4 +1627,10 @@ def make_json_location(location): return json_location + +def make_rule_hash(rule): + """Make a good-enough hash for a rule.""" + s = "\r".join([str(rule.severity), str(rule.description), str(rule.tag_pattern)]) + return base64.urlsafe_b64encode(hashlib.md5(s.encode('utf-8')).digest())[:8].decode('ascii') + # end
Double counting of errors p-code adm name combination consistency errors When I put the below into data check, I get 2 of every cell eg. F3,F3,F4,F4,F5,F5... https://data.humdata.org/dataset/77c97850-4004-4285-94db-0b390a962d6e/resource/d6c0dbac-683d-42d7-82b4-a6379bd4f48e/download/mrt_population_statistics_ons_rgph_2013_2017.xlsx
HXLStandard/libhxl-python
diff --git a/tests/test_validation.py b/tests/test_validation.py index 43ab00b..7e8b4f3 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -655,8 +655,8 @@ class TestValidateDataset(unittest.TestCase): def test_double_correlation(self): """Test correlation when more than one column has same tagspec""" SCHEMA = [ - ['#valid_tag', '#valid_correlation'], - ['#adm1+code', '#adm1+name'] + ['#valid_tag', '#description', '#valid_correlation', '#valid_value+list'], + ['#adm1+code', 'xxxxx', '#adm1+name', 'X001|X002'] ] DATASET = [ ['#adm1+name', '#adm1+code', '#adm1+code'],
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 1 }
4.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 -e git+https://github.com/HXLStandard/libhxl-python.git@1bc7e92a3844dd443f9e31f478357ea7b599c831#egg=libhxl packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 python-io-wrapper==0.3.1 requests==2.32.3 six==1.17.0 tomli==2.2.1 Unidecode==1.3.8 urllib3==2.3.0 xlrd==2.0.1
name: libhxl-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-io-wrapper==0.3.1 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - unidecode==1.3.8 - urllib3==2.3.0 - xlrd==2.0.1 prefix: /opt/conda/envs/libhxl-python
[ "tests/test_validation.py::TestValidateDataset::test_double_correlation" ]
[ "tests/test_validation.py::TestValidateDataset::test_default_schema", "tests/test_validation.py::TestLoad::test_load_default", "tests/test_validation.py::TestJSONSchema::test_truthy", "tests/test_validation.py::TestJSONReport::test_default", "tests/test_validation.py::TestJSONReport::test_top_level" ]
[ "tests/test_validation.py::TestTests::test_consistent_datatypes", "tests/test_validation.py::TestTests::test_correlation", "tests/test_validation.py::TestTests::test_datatype", "tests/test_validation.py::TestTests::test_enumeration", "tests/test_validation.py::TestTests::test_enumeration_suggested_values", "tests/test_validation.py::TestTests::test_outliers", "tests/test_validation.py::TestTests::test_range", "tests/test_validation.py::TestTests::test_regex", "tests/test_validation.py::TestTests::test_required", "tests/test_validation.py::TestTests::test_spelling_case_insensitive", "tests/test_validation.py::TestTests::test_spelling_case_sensitive", "tests/test_validation.py::TestTests::test_unique_row", "tests/test_validation.py::TestTests::test_unique_value", "tests/test_validation.py::TestTests::test_whitespace", "tests/test_validation.py::TestRule::test_datatype", "tests/test_validation.py::TestRule::test_range", "tests/test_validation.py::TestRule::test_regex", "tests/test_validation.py::TestRule::test_row_restrictions", "tests/test_validation.py::TestRule::test_value_enumeration", "tests/test_validation.py::TestRule::test_whitespace", "tests/test_validation.py::TestValidateColumns::test_bad_value_url", "tests/test_validation.py::TestValidateColumns::test_min_occurs", "tests/test_validation.py::TestValidateColumns::test_required", "tests/test_validation.py::TestValidateRow::test_date", "tests/test_validation.py::TestValidateRow::test_email", "tests/test_validation.py::TestValidateRow::test_minmax", "tests/test_validation.py::TestValidateRow::test_number", "tests/test_validation.py::TestValidateRow::test_url", "tests/test_validation.py::TestValidateDataset::test_consistent_datatype", "tests/test_validation.py::TestValidateDataset::test_correlation", "tests/test_validation.py::TestValidateDataset::test_different_indicator_datatypes", "tests/test_validation.py::TestValidateDataset::test_outliers", "tests/test_validation.py::TestValidateDataset::test_spellings", "tests/test_validation.py::TestValidateDataset::test_spellings_multiple", "tests/test_validation.py::TestValidateDataset::test_suggested_value_correlation_key", "tests/test_validation.py::TestValidateDataset::test_unique_compound", "tests/test_validation.py::TestValidateDataset::test_unique_single", "tests/test_validation.py::TestLoad::test_load_bad", "tests/test_validation.py::TestLoad::test_load_good", "tests/test_validation.py::TestJSONReport::test_errors" ]
[]
The Unlicense
2,604
[ "hxl/validation.py" ]
[ "hxl/validation.py" ]
streamlink__streamlink-1717
9d63e64bbcbdaac647cd5059704c287819069d4a
2018-05-30 22:15:34
b7e57851c642b0019313e04df289b6369322e8dd
codecov[bot]: # [Codecov](https://codecov.io/gh/streamlink/streamlink/pull/1717?src=pr&el=h1) Report > Merging [#1717](https://codecov.io/gh/streamlink/streamlink/pull/1717?src=pr&el=desc) into [master](https://codecov.io/gh/streamlink/streamlink/commit/1307bc19e5c54d7bd8f6bba0d1c84a736a72c7ba?src=pr&el=desc) will **increase** coverage by `0.16%`. > The diff coverage is `40%`. ```diff @@ Coverage Diff @@ ## master #1717 +/- ## ========================================== + Coverage 36.96% 37.12% +0.16% ========================================== Files 237 238 +1 Lines 13785 13914 +129 ========================================== + Hits 5095 5166 +71 - Misses 8690 8748 +58 ``` gravyboat: Is this good to go now after the tests and matrix addition? beardypig: I still need to work on the 2 factor auth stuff, I'll remove the WIP label once I've done that :) gravyboat: Okay cool thanks for the clarification. I wasn't sure if you were planning on working on that here or in another PR. zer0def: Are public broadcasts (those not requiring being logged in) a consideration in this PR? beardypig: I hadn’t realised you could access them without a login - should be a simple enough to change though :) beardypig: @zer0def I have updated the plugin to support public streams :) beardypig: @gravyboat I have proposed a possible method to allow this plugin to request user input and maintain the disconnect between `streamlink` and `streamlink_cli`.
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index a122186d..112bd9c7 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -43,8 +43,7 @@ btsports sport.bt.com Yes Yes Requires subscription a btv btv.bg Yes No Requires login, and geo-restricted to Bulgaria. cam4 cam4.com Yes No camsoda camsoda.com Yes No -canalplus - mycanal.fr No Yes Streams may be geo-restricted to France. - - cnews.fr +canalplus mycanal.fr No Yes Streams may be geo-restricted to France. cdnbg - tv.bnt.bg Yes No Streams may be geo-restricted to Bulgaria. - bgonair.bg - kanal3.bg @@ -57,6 +56,7 @@ cinergroup - showtv.com.tr Yes No - showmax.com.tr - showturk.com.tr - bloomberght.com +cnews cnews.fr Yes Yes crunchyroll crunchyroll.com -- Yes cybergame cybergame.tv Yes Yes dailymotion dailymotion.com Yes Yes @@ -192,6 +192,7 @@ srgssr - srf.ch Yes No Streams are geo-restric - rtr.ch ssh101 ssh101.com Yes No startv startv.com.tr Yes No +steam steamcommunity.com Yes No Some streams will require a Steam account. streamable streamable.com - Yes streamboat streamboat.tv Yes No streamingvideoprovider streamingvid... [2]_ Yes -- RTMP streams requires rtmpdump with diff --git a/src/streamlink/plugins/canalplus.py b/src/streamlink/plugins/canalplus.py index b0c4bb23..8279ce0b 100644 --- a/src/streamlink/plugins/canalplus.py +++ b/src/streamlink/plugins/canalplus.py @@ -13,10 +13,9 @@ class CanalPlus(Plugin): SECRET = 'pqzerjlsmdkjfoiuerhsdlfknaes' _url_re = re.compile(r''' - (https|http):// + https?:// ( - www.mycanal.fr/(.*)/(.*)/p/(?P<video_id>[0-9]+) | - www\.cnews\.fr/.+ + www.mycanal.fr/(.*)/(.*)/p/(?P<video_id>[0-9]+) ) ''', re.VERBOSE) _video_id_re = re.compile(r'(\bdata-video="|<meta property="og:video" content=".+?&videoId=)(?P<video_id>[0-9]+)"') diff --git a/src/streamlink/plugins/cnews.py b/src/streamlink/plugins/cnews.py new file mode 100644 index 00000000..824d4d3f --- /dev/null +++ b/src/streamlink/plugins/cnews.py @@ -0,0 +1,24 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http, useragents + + +class CNEWS(Plugin): + _url_re = re.compile(r'https?://www.cnews.fr/[^ ]+') + _embed_video_url_re = re.compile(r'class="dm-video-embed_video" src="(?P<dm_url>.*)"') + _embed_live_url_re = re.compile(r'class="wrapper-live-player main-live-player"><iframe src="(?P<dm_url>.*)"') + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) + + def _get_streams(self): + # Retrieve URL page and search for Dailymotion URL + res = http.get(self.url, headers={'User-Agent': useragents.CHROME}) + match = self._embed_live_url_re.search(res.text) or self._embed_video_url_re.search(res.text) + if match is not None: + return self.session.streams(match.group('dm_url')) + + +__plugin__ = CNEWS diff --git a/src/streamlink/plugins/steam.py b/src/streamlink/plugins/steam.py new file mode 100644 index 00000000..fcbf0ce5 --- /dev/null +++ b/src/streamlink/plugins/steam.py @@ -0,0 +1,210 @@ +import base64 +import logging +import re +import time + +from Crypto.Cipher import PKCS1_v1_5 +from Crypto.PublicKey import RSA + +import streamlink +from streamlink.exceptions import FatalPluginError +from streamlink.plugin import Plugin, PluginArguments, PluginArgument +from streamlink.plugin.api import http +from streamlink.plugin.api import validate +from streamlink.plugin.api.validate import Schema +from streamlink.stream.dash import DASHStream + +log = logging.getLogger(__name__) + + +class SteamLoginFailed(Exception): + pass + + +class SteamBroadcastPlugin(Plugin): + _url_re = re.compile(r"https?://steamcommunity.com/broadcast/watch/(\d+)") + _get_broadcast_url = "https://steamcommunity.com/broadcast/getbroadcastmpd/" + _user_agent = "streamlink/{}".format(streamlink.__version__) + _broadcast_schema = Schema({ + "success": validate.any("ready", "unavailable", "waiting", "waiting_to_start", "waiting_for_start"), + "retry": int, + "broadcastid": validate.any(validate.text, int), + validate.optional("url"): validate.url(), + validate.optional("viewertoken"): validate.text + }) + _get_rsa_key_url = "https://steamcommunity.com/login/getrsakey/" + _rsa_key_schema = validate.Schema({ + "publickey_exp": validate.all(validate.text, validate.transform(lambda x: int(x, 16))), + "publickey_mod": validate.all(validate.text, validate.transform(lambda x: int(x, 16))), + "success": True, + "timestamp": validate.text, + "token_gid": validate.text + }) + _dologin_url = "https://steamcommunity.com/login/dologin/" + _dologin_schema = validate.Schema({ + "success": bool, + "requires_twofactor": bool, + validate.optional("message"): validate.text, + validate.optional("emailauth_needed"): bool, + validate.optional("emaildomain"): validate.text, + validate.optional("emailsteamid"): validate.text, + validate.optional("login_complete"): bool, + validate.optional("captcha_needed"): bool, + validate.optional("captcha_gid"): validate.any(validate.text, int) + }) + _captcha_url = "https://steamcommunity.com/public/captcha.php?gid={}" + + arguments = PluginArguments( + PluginArgument( + "email", + metavar="EMAIL", + requires=["password"], + help=""" + A Steam account email address to access friends/private streams + """ + ), + PluginArgument( + "password", + metavar="PASSWORD", + sensitive=True, + help=""" + A Steam account password to use with --steam-email. + """ + )) + + def __init__(self, url): + super(SteamBroadcastPlugin, self).__init__(url) + http.headers["User-Agent"] = self._user_agent + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + @property + def donotcache(self): + return str(int(time.time() * 1000)) + + def encrypt_password(self, email, password): + """ + Get the RSA key for the user and encrypt the users password + :param email: steam account + :param password: password for account + :return: encrypted password + """ + res = http.get(self._get_rsa_key_url, params=dict(username=email, donotcache=self.donotcache)) + rsadata = http.json(res, schema=self._rsa_key_schema) + + rsa = RSA.construct((rsadata["publickey_mod"], rsadata["publickey_exp"])) + cipher = PKCS1_v1_5.new(rsa) + return base64.b64encode(cipher.encrypt(password.encode("utf8"))), rsadata["timestamp"] + + def dologin(self, email, password, emailauth="", emailsteamid="", captchagid="-1", captcha_text="", twofactorcode=""): + """ + Logs in to Steam + + """ + epassword, rsatimestamp = self.encrypt_password(email, password) + + login_data = { + 'username': email, + "password": epassword, + "emailauth": emailauth, + "loginfriendlyname": "Streamlink", + "captchagid": captchagid, + "captcha_text": captcha_text, + "emailsteamid": emailsteamid, + "rsatimestamp": rsatimestamp, + "remember_login": True, + "donotcache": self.donotcache, + "twofactorcode": twofactorcode + } + + res = http.post(self._dologin_url, data=login_data) + + resp = http.json(res, schema=self._dologin_schema) + + if not resp[u"success"]: + if resp.get(u"captcha_needed"): + # special case for captcha + captchagid = resp[u"captcha_gid"] + log.error("Captcha result required, open this URL to see the captcha: {}".format( + self._captcha_url.format(captchagid))) + try: + captcha_text = self.input_ask("Captcha text") + except FatalPluginError: + captcha_text = None + if not captcha_text: + return False + else: + # If the user must enter the code that was emailed to them + if resp.get(u"emailauth_needed"): + if not emailauth: + try: + emailauth = self.input_ask("Email auth code required") + except FatalPluginError: + emailauth = None + if not emailauth: + return False + else: + raise SteamLoginFailed("Email auth key error") + + # If the user must enter a two factor auth code + if resp.get(u"requires_twofactor"): + try: + twofactorcode = self.input_ask("Two factor auth code required") + except FatalPluginError: + twofactorcode = None + if not twofactorcode: + return False + + if resp.get(u"message"): + raise SteamLoginFailed(resp[u"message"]) + + return self.dologin(email, password, + emailauth=emailauth, + emailsteamid=resp.get(u"emailsteamid", u""), + captcha_text=captcha_text, + captchagid=captchagid, + twofactorcode=twofactorcode) + elif resp.get("login_complete"): + return True + else: + log.error("Something when wrong when logging in to Steam") + return False + + def login(self, email, password): + log.info("Attempting to login to Steam as {}".format(email)) + return self.dologin(email, password) + + def _get_broadcast_stream(self, steamid, viewertoken=0): + res = http.get(self._get_broadcast_url, + params=dict(broadcastid=0, + steamid=steamid, + viewertoken=viewertoken)) + return http.json(res, schema=self._broadcast_schema) + + def _get_streams(self): + streamdata = None + if self.get_option("email"): + if self.login(self.get_option("email"), self.get_option("password")): + log.info("Logged in as {0}".format(self.get_option("email"))) + self.save_cookies(lambda c: "steamMachineAuth" in c.name) + + # extract the steam ID from the URL + steamid = self._url_re.match(self.url).group(1) + + while streamdata is None or streamdata[u"success"] in ("waiting", "waiting_for_start"): + streamdata = self._get_broadcast_stream(steamid) + + if streamdata[u"success"] == "ready": + return DASHStream.parse_manifest(self.session, streamdata["url"]) + elif streamdata[u"success"] == "unavailable": + log.error("This stream is currently unavailable") + return + else: + r = streamdata[u"retry"] / 1000.0 + log.info("Waiting for stream, will retry again in {} seconds...".format(r)) + time.sleep(r) + + +__plugin__ = SteamBroadcastPlugin
Support for Steam Broadcasting Hey boys and girls, Recently jumped ship over to streamlink and was wondering if you guys could figure out how to enable support for Steam Broadcasting. The folks over at livestreamer gave it a crack, but development for it soon died out. (Here's the link to the livestreamer issue thread: https://github.com/chrippa/livestreamer/issues/621) This may be a bit of an ask because it requires the user to be logged in but I'm fully happy to enter in my steam information to get it working. Here's a link to the directory of live broadcasts: http://steamcommunity.com/?subsection=broadcasts Hope this isn't too much of a challenge for you guys. Cheers.
streamlink/streamlink
diff --git a/tests/test_plugin_canalplus.py b/tests/test_plugin_canalplus.py index 62daf272..30646c58 100644 --- a/tests/test_plugin_canalplus.py +++ b/tests/test_plugin_canalplus.py @@ -10,10 +10,10 @@ class TestPluginCanalPlus(unittest.TestCase): self.assertTrue(CanalPlus.can_handle_url("https://www.mycanal.fr/sport/infosport-laurey-et-claudia/p/1473752")) self.assertTrue(CanalPlus.can_handle_url("https://www.mycanal.fr/docus-infos/ses-debuts-a-madrid-extrait-le-k-benzema/p/1469050")) self.assertTrue(CanalPlus.can_handle_url("https://www.mycanal.fr/d8-docs-mags/au-revoir-johnny-hallyday-le-doc/p/1473054")) - self.assertTrue(CanalPlus.can_handle_url("http://www.cnews.fr/direct")) - self.assertTrue(CanalPlus.can_handle_url("http://www.cnews.fr/politique/video/des-electeurs-toujours-autant-indecis-174769")) - self.assertTrue(CanalPlus.can_handle_url("http://www.cnews.fr/magazines/plus-de-recul/de-recul-du-14042017-174594")) # shouldn't match + self.assertFalse(CanalPlus.can_handle_url("http://www.cnews.fr/direct")) + self.assertFalse(CanalPlus.can_handle_url("http://www.cnews.fr/politique/video/des-electeurs-toujours-autant-indecis-174769")) + self.assertFalse(CanalPlus.can_handle_url("http://www.cnews.fr/magazines/plus-de-recul/de-recul-du-14042017-174594")) self.assertFalse(CanalPlus.can_handle_url("http://www.canalplus.fr/")) self.assertFalse(CanalPlus.can_handle_url("http://www.c8.fr/")) self.assertFalse(CanalPlus.can_handle_url("http://replay.c8.fr/")) diff --git a/tests/test_plugin_cnews.py b/tests/test_plugin_cnews.py new file mode 100644 index 00000000..c7bdfd9f --- /dev/null +++ b/tests/test_plugin_cnews.py @@ -0,0 +1,16 @@ +import unittest + +from streamlink.plugins.cnews import CNEWS + + +class TestPluginCNEWS(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(CNEWS.can_handle_url("http://www.cnews.fr/le-direct")) + self.assertTrue(CNEWS.can_handle_url("http://www.cnews.fr/direct")) + self.assertTrue(CNEWS.can_handle_url("http://www.cnews.fr/emission/2018-06-12/meteo-du-12062018-784730")) + self.assertTrue(CNEWS.can_handle_url("http://www.cnews.fr/emission/2018-06-12/le-journal-des-faits-divers-du-12062018-784704")) + # shouldn't match + self.assertFalse(CNEWS.can_handle_url("http://www.cnews.fr/")) + self.assertFalse(CNEWS.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(CNEWS.can_handle_url("http://www.youtube.com/")) diff --git a/tests/test_plugin_steam.py b/tests/test_plugin_steam.py new file mode 100644 index 00000000..db16601f --- /dev/null +++ b/tests/test_plugin_steam.py @@ -0,0 +1,15 @@ +import unittest + +from streamlink.plugins.steam import SteamBroadcastPlugin + + +class TestPluginSteamBroadcastPlugin(unittest.TestCase): + def test_can_handle_url(self): + self.assertTrue(SteamBroadcastPlugin.can_handle_url('https://steamcommunity.com/broadcast/watch/12432432')) + self.assertTrue(SteamBroadcastPlugin.can_handle_url('http://steamcommunity.com/broadcast/watch/342342')) + + def test_can_handle_url_negative(self): + # shouldn't match + self.assertFalse(SteamBroadcastPlugin.can_handle_url('http://steamcommunity.com/broadcast')) + self.assertFalse(SteamBroadcastPlugin.can_handle_url('https://steamcommunity.com')) + self.assertFalse(SteamBroadcastPlugin.can_handle_url('https://youtube.com'))
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
0.13
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 codecov==2.1.13 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 freezegun==1.5.1 idna==3.10 iniconfig==2.1.0 iso-639==0.4.5 iso3166==2.1.1 isodate==0.7.2 Jinja2==3.1.6 MarkupSafe==3.0.2 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pycryptodome==3.22.0 pynsist==2.8 PySocks==1.7.1 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 requests==2.32.3 requests-mock==1.12.1 requests_download==0.1.2 six==1.17.0 -e git+https://github.com/streamlink/streamlink.git@9d63e64bbcbdaac647cd5059704c287819069d4a#egg=streamlink tomli==2.2.1 urllib3==2.3.0 websocket-client==1.8.0 yarg==0.1.10
name: streamlink channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - codecov==2.1.13 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - freezegun==1.5.1 - idna==3.10 - iniconfig==2.1.0 - iso-639==0.4.5 - iso3166==2.1.1 - isodate==0.7.2 - jinja2==3.1.6 - markupsafe==3.0.2 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pycryptodome==3.22.0 - pynsist==2.8 - pysocks==1.7.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - requests==2.32.3 - requests-download==0.1.2 - requests-mock==1.12.1 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 - websocket-client==1.8.0 - yarg==0.1.10 prefix: /opt/conda/envs/streamlink
[ "tests/test_plugin_canalplus.py::TestPluginCanalPlus::test_can_handle_url", "tests/test_plugin_cnews.py::TestPluginCNEWS::test_can_handle_url", "tests/test_plugin_steam.py::TestPluginSteamBroadcastPlugin::test_can_handle_url", "tests/test_plugin_steam.py::TestPluginSteamBroadcastPlugin::test_can_handle_url_negative" ]
[]
[]
[]
BSD 2-Clause "Simplified" License
2,605
[ "src/streamlink/plugins/cnews.py", "docs/plugin_matrix.rst", "src/streamlink/plugins/steam.py", "src/streamlink/plugins/canalplus.py" ]
[ "src/streamlink/plugins/cnews.py", "docs/plugin_matrix.rst", "src/streamlink/plugins/steam.py", "src/streamlink/plugins/canalplus.py" ]
graphql-python__graphene-751
7bd77a0817677656e2ed8e8ac235ab5e8d557487
2018-05-30 22:59:46
f039af2810806ab42521426777b3a0d061b02802
diff --git a/graphene/relay/node.py b/graphene/relay/node.py index 6596757..5c787ff 100644 --- a/graphene/relay/node.py +++ b/graphene/relay/node.py @@ -101,8 +101,8 @@ class Node(AbstractNode): if only_type: assert graphene_type == only_type, ( - 'Must receive an {} id.' - ).format(graphene_type._meta.name) + 'Must receive a {} id.' + ).format(only_type._meta.name) # We make sure the ObjectType implements the "Node" interface if cls not in graphene_type._meta.interfaces:
Incorrectly formatted error message. The error message generated here is incorrect. It should be `only_type._meta.name` instead of `graphene_type._meta.name`. This way the expected value will be reported, which is what the message says it is. https://github.com/graphql-python/graphene/blob/7bd77a0817677656e2ed8e8ac235ab5e8d557487/graphene/relay/node.py#L105 Also, it's better to use "a" instead of "an" as a default preposition in messages. https://github.com/graphql-python/graphene/blob/7bd77a0817677656e2ed8e8ac235ab5e8d557487/graphene/relay/node.py#L104
graphql-python/graphene
diff --git a/graphene/relay/tests/test_node.py b/graphene/relay/tests/test_node.py index 10dc5d9..df44fcb 100644 --- a/graphene/relay/tests/test_node.py +++ b/graphene/relay/tests/test_node.py @@ -115,7 +115,7 @@ def test_node_field_only_type_wrong(): '{ onlyNode(id:"%s") { __typename, name } } ' % Node.to_global_id("MyOtherNode", 1) ) assert len(executed.errors) == 1 - assert str(executed.errors[0]) == 'Must receive an MyOtherNode id.' + assert str(executed.errors[0]) == 'Must receive a MyNode id.' assert executed.data == {'onlyNode': None} @@ -132,7 +132,7 @@ def test_node_field_only_lazy_type_wrong(): '{ onlyNodeLazy(id:"%s") { __typename, name } } ' % Node.to_global_id("MyOtherNode", 1) ) assert len(executed.errors) == 1 - assert str(executed.errors[0]) == 'Must receive an MyOtherNode id.' + assert str(executed.errors[0]) == 'Must receive a MyNode id.' assert executed.data == {'onlyNodeLazy': None}
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-benchmark", "pytest-cov", "pytest-mock", "snapshottest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aniso8601==3.0.2 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 coveralls==3.3.1 docopt==0.6.2 fastdiff==0.3.0 -e git+https://github.com/graphql-python/graphene.git@7bd77a0817677656e2ed8e8ac235ab5e8d557487#egg=graphene graphql-core==2.3.2 graphql-relay==0.4.5 idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work iso8601==1.1.0 mock==5.2.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work promise==2.3 py @ file:///opt/conda/conda-bld/py_1644396412707/work py-cpuinfo==9.0.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-benchmark==3.4.1 pytest-cov==4.0.0 pytest-mock==3.6.1 pytz==2025.2 requests==2.27.1 Rx==1.6.3 six==1.17.0 snapshottest==0.6.0 termcolor==1.1.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work tomli==1.2.3 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 wasmer==1.1.0 wasmer-compiler-cranelift==1.1.0 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: graphene channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - aniso8601==3.0.2 - charset-normalizer==2.0.12 - coverage==6.2 - coveralls==3.3.1 - docopt==0.6.2 - fastdiff==0.3.0 - graphql-core==2.3.2 - graphql-relay==0.4.5 - idna==3.10 - iso8601==1.1.0 - mock==5.2.0 - promise==2.3 - py-cpuinfo==9.0.0 - pytest-benchmark==3.4.1 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytz==2025.2 - requests==2.27.1 - rx==1.6.3 - six==1.17.0 - snapshottest==0.6.0 - termcolor==1.1.0 - tomli==1.2.3 - urllib3==1.26.20 - wasmer==1.1.0 - wasmer-compiler-cranelift==1.1.0 prefix: /opt/conda/envs/graphene
[ "graphene/relay/tests/test_node.py::test_node_field_only_type_wrong", "graphene/relay/tests/test_node.py::test_node_field_only_lazy_type_wrong" ]
[]
[ "graphene/relay/tests/test_node.py::test_node_good", "graphene/relay/tests/test_node.py::test_node_query", "graphene/relay/tests/test_node.py::test_subclassed_node_query", "graphene/relay/tests/test_node.py::test_node_requesting_non_node", "graphene/relay/tests/test_node.py::test_node_query_incorrect_id", "graphene/relay/tests/test_node.py::test_node_field", "graphene/relay/tests/test_node.py::test_node_field_custom", "graphene/relay/tests/test_node.py::test_node_field_only_type", "graphene/relay/tests/test_node.py::test_node_field_only_lazy_type", "graphene/relay/tests/test_node.py::test_str_schema" ]
[]
MIT License
2,606
[ "graphene/relay/node.py" ]
[ "graphene/relay/node.py" ]
python-cmd2__cmd2-424
7000604ac826a637539c388ad8f5ff8a3ebfc419
2018-05-31 04:03:54
60a212c1c585f0c4c06ffcfeb9882520af8dbf35
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index b6e7cf19..2d8766f4 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -124,7 +124,7 @@ try: except ImportError: ipython_available = False -__version__ = '0.9.1' +__version__ = '0.9.2a' # optional attribute, when tagged on a function, allows cmd2 to categorize commands diff --git a/docs/conf.py b/docs/conf.py index 997405dd..25ba2a78 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -62,7 +62,7 @@ author = 'Catherine Devlin and Todd Leonhardt' # The short X.Y version. version = '0.9' # The full version, including alpha/beta/rc tags. -release = '0.9.1' +release = '0.9.2a' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/setup.py b/setup.py index 0127ae5b..59c53b68 100755 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ Setuptools setup file, used to install or test 'cmd2' """ from setuptools import setup -VERSION = '0.9.1' +VERSION = '0.9.2a' DESCRIPTION = "cmd2 - a tool for building interactive command line applications in Python" LONG_DESCRIPTION = """cmd2 is a tool for building interactive command line applications in Python. Its goal is to make it quick and easy for developers to build feature-rich and user-friendly interactive command line applications. It @@ -73,7 +73,7 @@ EXTRAS_REQUIRE = { # install with 'pip install -e .[dev]' 'dev': [ 'pytest', 'pytest-cov', 'tox', 'pylint', 'sphinx', 'sphinx-rtd-theme', - 'sphinx-autobuild','invoke', 'twine', + 'sphinx-autobuild', 'invoke', 'twine>=1.11', ] } diff --git a/tasks.py b/tasks.py index 000af0a5..5c0bd772 100644 --- a/tasks.py +++ b/tasks.py @@ -1,7 +1,12 @@ # # coding=utf-8 -"""Development related tasks to be run with 'invoke'""" +"""Development related tasks to be run with 'invoke'. +Make sure you satisfy the following Python module requirements if you are trying to publish a release to PyPI: + - twine >= 1.11.0 + - wheel >= 0.31.0 + - setuptools >= 39.1.0 +""" import os import shutil
Fix twine upload Running the new **invoke pypi** command to build and upload a release to PyPI fails in the very last step with the following error message: ```sh Uploading distributions to https://pypi.python.org/pypi Note: you are uploading to the old upload URL. It's recommended to use the new URL "https://upload.pypi.org/legacy/" or to leave the URL unspecified and allow twine to choose. Uploading cmd2-0.9.0.post1-py3-none-any.whl 100%|██████████| 76.8k/76.8k [00:00<00:00, 721kB/s] RedirectDetected: "https://pypi.python.org/pypi" attempted to redirect to "https://pypi.org/pypi" during upload. Aborting... ``` The command being executed when this occurs is: ```sh twine upload dist/* ```
python-cmd2/cmd2
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index 33d9ca41..68aa0b98 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -28,7 +28,7 @@ from .conftest import run_cmd, normalize, BASE_HELP, BASE_HELP_VERBOSE, \ def test_ver(): - assert cmd2.__version__ == '0.9.1' + assert cmd2.__version__ == '0.9.2a' def test_empty_statement(base_app):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 4 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 astroid==2.11.7 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 -e git+https://github.com/python-cmd2/cmd2.git@7000604ac826a637539c388ad8f5ff8a3ebfc419#egg=cmd2 colorama==0.4.5 coverage==6.2 cryptography==40.0.2 dill==0.3.4 distlib==0.3.9 docutils==0.18.1 filelock==3.4.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 invoke==2.2.0 isort==5.10.1 jeepney==0.7.1 Jinja2==3.0.3 keyring==23.4.1 lazy-object-proxy==1.7.1 livereload==2.6.3 MarkupSafe==2.0.1 mccabe==0.7.0 packaging==21.3 pkginfo==1.10.0 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pycparser==2.21 Pygments==2.14.0 pylint==2.13.9 pyparsing==3.1.4 pyperclip==1.9.0 pytest==7.0.1 pytest-cov==4.0.0 pytz==2025.2 readme-renderer==34.0 requests==2.27.1 requests-toolbelt==1.0.0 rfc3986==1.5.0 SecretStorage==3.3.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-autobuild==2021.3.14 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 toml==0.10.2 tomli==1.2.3 tornado==6.1 tox==3.28.0 tqdm==4.64.1 twine==3.8.0 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 wcwidth==0.2.13 webencodings==0.5.1 wrapt==1.16.0 zipp==3.6.0
name: cmd2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - astroid==2.11.7 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cffi==1.15.1 - charset-normalizer==2.0.12 - colorama==0.4.5 - coverage==6.2 - cryptography==40.0.2 - dill==0.3.4 - distlib==0.3.9 - docutils==0.18.1 - filelock==3.4.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - invoke==2.2.0 - isort==5.10.1 - jeepney==0.7.1 - jinja2==3.0.3 - keyring==23.4.1 - lazy-object-proxy==1.7.1 - livereload==2.6.3 - markupsafe==2.0.1 - mccabe==0.7.0 - packaging==21.3 - pkginfo==1.10.0 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycparser==2.21 - pygments==2.14.0 - pylint==2.13.9 - pyparsing==3.1.4 - pyperclip==1.9.0 - pytest==7.0.1 - pytest-cov==4.0.0 - pytz==2025.2 - readme-renderer==34.0 - requests==2.27.1 - requests-toolbelt==1.0.0 - rfc3986==1.5.0 - secretstorage==3.3.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-autobuild==2021.3.14 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - toml==0.10.2 - tomli==1.2.3 - tornado==6.1 - tox==3.28.0 - tqdm==4.64.1 - twine==3.8.0 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - wcwidth==0.2.13 - webencodings==0.5.1 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/cmd2
[ "tests/test_cmd2.py::test_ver" ]
[ "tests/test_cmd2.py::test_which_editor_good" ]
[ "tests/test_cmd2.py::test_empty_statement", "tests/test_cmd2.py::test_base_help", "tests/test_cmd2.py::test_base_help_verbose", "tests/test_cmd2.py::test_base_help_history", "tests/test_cmd2.py::test_base_argparse_help", "tests/test_cmd2.py::test_base_invalid_option", "tests/test_cmd2.py::test_base_shortcuts", "tests/test_cmd2.py::test_base_show", "tests/test_cmd2.py::test_base_show_long", "tests/test_cmd2.py::test_base_show_readonly", "tests/test_cmd2.py::test_cast", "tests/test_cmd2.py::test_cast_problems", "tests/test_cmd2.py::test_base_set", "tests/test_cmd2.py::test_set_not_supported", "tests/test_cmd2.py::test_set_quiet", "tests/test_cmd2.py::test_base_shell", "tests/test_cmd2.py::test_base_py", "tests/test_cmd2.py::test_base_run_python_script", "tests/test_cmd2.py::test_base_run_pyscript", "tests/test_cmd2.py::test_recursive_pyscript_not_allowed", "tests/test_cmd2.py::test_pyscript_with_nonexist_file", "tests/test_cmd2.py::test_pyscript_with_exception", "tests/test_cmd2.py::test_pyscript_requires_an_argument", "tests/test_cmd2.py::test_base_error", "tests/test_cmd2.py::test_history_span", "tests/test_cmd2.py::test_history_get", "tests/test_cmd2.py::test_base_history", "tests/test_cmd2.py::test_history_script_format", "tests/test_cmd2.py::test_history_with_string_argument", "tests/test_cmd2.py::test_history_with_integer_argument", "tests/test_cmd2.py::test_history_with_integer_span", "tests/test_cmd2.py::test_history_with_span_start", "tests/test_cmd2.py::test_history_with_span_end", "tests/test_cmd2.py::test_history_with_span_index_error", "tests/test_cmd2.py::test_history_output_file", "tests/test_cmd2.py::test_history_edit", "tests/test_cmd2.py::test_history_run_all_commands", "tests/test_cmd2.py::test_history_run_one_command", "tests/test_cmd2.py::test_base_load", "tests/test_cmd2.py::test_load_with_empty_args", "tests/test_cmd2.py::test_load_with_nonexistent_file", "tests/test_cmd2.py::test_load_with_empty_file", "tests/test_cmd2.py::test_load_with_binary_file", "tests/test_cmd2.py::test_load_with_utf8_file", "tests/test_cmd2.py::test_load_nested_loads", "tests/test_cmd2.py::test_base_runcmds_plus_hooks", "tests/test_cmd2.py::test_base_relative_load", "tests/test_cmd2.py::test_relative_load_requires_an_argument", "tests/test_cmd2.py::test_output_redirection", "tests/test_cmd2.py::test_feedback_to_output_true", "tests/test_cmd2.py::test_feedback_to_output_false", "tests/test_cmd2.py::test_allow_redirection", "tests/test_cmd2.py::test_pipe_to_shell", "tests/test_cmd2.py::test_pipe_to_shell_error", "tests/test_cmd2.py::test_base_timing", "tests/test_cmd2.py::test_base_debug", "tests/test_cmd2.py::test_base_colorize", "tests/test_cmd2.py::test_edit_no_editor", "tests/test_cmd2.py::test_edit_file", "tests/test_cmd2.py::test_edit_file_with_spaces", "tests/test_cmd2.py::test_edit_blank", "tests/test_cmd2.py::test_base_py_interactive", "tests/test_cmd2.py::test_exclude_from_history", "tests/test_cmd2.py::test_base_cmdloop_with_queue", "tests/test_cmd2.py::test_base_cmdloop_without_queue", "tests/test_cmd2.py::test_cmdloop_without_rawinput", "tests/test_cmd2.py::test_precmd_hook_success", "tests/test_cmd2.py::test_precmd_hook_failure", "tests/test_cmd2.py::test_interrupt_quit", "tests/test_cmd2.py::test_interrupt_noquit", "tests/test_cmd2.py::test_default_to_shell_unknown", "tests/test_cmd2.py::test_default_to_shell_good", "tests/test_cmd2.py::test_default_to_shell_failure", "tests/test_cmd2.py::test_ansi_prompt_not_esacped", "tests/test_cmd2.py::test_ansi_prompt_escaped", "tests/test_cmd2.py::test_custom_command_help", "tests/test_cmd2.py::test_custom_help_menu", "tests/test_cmd2.py::test_help_undocumented", "tests/test_cmd2.py::test_help_overridden_method", "tests/test_cmd2.py::test_help_cat_base", "tests/test_cmd2.py::test_help_cat_verbose", "tests/test_cmd2.py::test_select_options", "tests/test_cmd2.py::test_select_invalid_option", "tests/test_cmd2.py::test_select_list_of_strings", "tests/test_cmd2.py::test_select_list_of_tuples", "tests/test_cmd2.py::test_select_uneven_list_of_tuples", "tests/test_cmd2.py::test_help_with_no_docstring", "tests/test_cmd2.py::test_which_editor_bad", "tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception", "tests/test_cmd2.py::test_multiline_complete_statement_without_terminator", "tests/test_cmd2.py::test_clipboard_failure", "tests/test_cmd2.py::test_cmdresult", "tests/test_cmd2.py::test_is_text_file_bad_input", "tests/test_cmd2.py::test_eof", "tests/test_cmd2.py::test_eos", "tests/test_cmd2.py::test_echo", "tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true", "tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false", "tests/test_cmd2.py::test_raw_input", "tests/test_cmd2.py::test_stdin_input", "tests/test_cmd2.py::test_empty_stdin_input", "tests/test_cmd2.py::test_poutput_string", "tests/test_cmd2.py::test_poutput_zero", "tests/test_cmd2.py::test_poutput_empty_string", "tests/test_cmd2.py::test_poutput_none", "tests/test_cmd2.py::test_alias", "tests/test_cmd2.py::test_alias_lookup_invalid_alias", "tests/test_cmd2.py::test_unalias", "tests/test_cmd2.py::test_unalias_all", "tests/test_cmd2.py::test_unalias_non_existing", "tests/test_cmd2.py::test_create_invalid_alias[\">\"]", "tests/test_cmd2.py::test_create_invalid_alias[\"no>pe\"]", "tests/test_cmd2.py::test_create_invalid_alias[\"no", "tests/test_cmd2.py::test_create_invalid_alias[\"nopipe|\"]", "tests/test_cmd2.py::test_create_invalid_alias[\"noterm;\"]", "tests/test_cmd2.py::test_create_invalid_alias[noembedded\"quotes]", "tests/test_cmd2.py::test_ppaged", "tests/test_cmd2.py::test_parseline_empty", "tests/test_cmd2.py::test_parseline" ]
[]
MIT License
2,607
[ "docs/conf.py", "cmd2/cmd2.py", "tasks.py", "setup.py" ]
[ "docs/conf.py", "cmd2/cmd2.py", "tasks.py", "setup.py" ]
diogommartins__simple_json_logger-14
1bc3c8d12784d55417e8d46b4fe9b44bd8cd1f99
2018-05-31 14:58:34
1bc3c8d12784d55417e8d46b4fe9b44bd8cd1f99
diff --git a/setup.py b/setup.py index a1dddaa..db14acc 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from setuptools import setup, find_packages -VERSION = '0.2.2' +VERSION = '0.2.3' setup(name='simple_json_logger', diff --git a/simple_json_logger/formatter.py b/simple_json_logger/formatter.py index b4eb58a..629eecb 100644 --- a/simple_json_logger/formatter.py +++ b/simple_json_logger/formatter.py @@ -1,7 +1,7 @@ import logging try: from logging import _levelToName -except ImportError: +except ImportError: # pragma: no cover from logging import _levelNames as _levelToName import traceback @@ -32,7 +32,7 @@ class JsonFormatter(logging.Formatter): return obj.strftime(DATETIME_FORMAT) elif istraceback(obj): tb = ''.join(traceback.format_tb(obj)) - return tb.strip() + return tb.strip().split('\n') elif isinstance(obj, Exception): return "Exception: %s" % str(obj) elif callable(obj):
Fix multiline log for stacktraces Multiline stack traces must be formatted as a list of strings
diogommartins/simple_json_logger
diff --git a/tests/test_logger.py b/tests/test_logger.py index a98e7f4..8094814 100644 --- a/tests/test_logger.py +++ b/tests/test_logger.py @@ -78,12 +78,11 @@ class LoggerTests(unittest.TestCase): json_log = json.loads(logged_content) exc_class, exc_message, exc_traceback = json_log['exc_info'] - self.assertIn(member=exception_message, - container=exc_message) + self.assertEqual('Exception: {}'.format(exception_message), exc_message) current_func_name = inspect.currentframe().f_code.co_name - self.assertIn(member=current_func_name, - container=exc_traceback) + self.assertIn(current_func_name, exc_traceback[0]) + self.assertIn('raise Exception(exception_message)', exc_traceback[1]) def test_it_logs_datetime_objects(self): message = {
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 2 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "freezegun==0.3.8", "pytest", "pytest-cov", "codecov" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 codecov==2.1.13 coverage==7.8.0 exceptiongroup==1.2.2 freezegun==0.3.8 idna==3.10 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 requests==2.32.3 -e git+https://github.com/diogommartins/simple_json_logger.git@1bc3c8d12784d55417e8d46b4fe9b44bd8cd1f99#egg=simple_json_logger six==1.17.0 tomli==2.2.1 urllib3==2.3.0
name: simple_json_logger channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - codecov==2.1.13 - coverage==7.8.0 - exceptiongroup==1.2.2 - freezegun==0.3.8 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/simple_json_logger
[ "tests/test_logger.py::LoggerTests::test_it_logs_exceptions_tracebacks" ]
[ "tests/test_logger.py::LoggerTests::test_it_calls_stderr_for_high_log_leves", "tests/test_logger.py::LoggerTests::test_it_calls_stdout_for_low_levels_and_stderr_for_high_levels", "tests/test_logger.py::LoggerTests::test_it_replaces_default_handlers_if_a_stream_is_provided" ]
[ "tests/test_logger.py::LoggerTests::test_callable_values_are_called_before_serialization", "tests/test_logger.py::LoggerTests::test_extra_param_adds_content_to_document_root", "tests/test_logger.py::LoggerTests::test_extra_parameter_adds_content_to_root_of_all_messages", "tests/test_logger.py::LoggerTests::test_extra_parameter_on_log_method_function_call_updates_extra_parameter_on_init", "tests/test_logger.py::LoggerTests::test_flatten_instance_attr_adds_messages_to_document_root", "tests/test_logger.py::LoggerTests::test_flatten_instance_attr_overwrites_default_attributes", "tests/test_logger.py::LoggerTests::test_flatten_method_parameter_does_nothing_is_message_isnt_a_dict", "tests/test_logger.py::LoggerTests::test_flatten_method_parameter_overwrites_default_attributes", "tests/test_logger.py::LoggerTests::test_flatten_param_adds_message_to_document_root", "tests/test_logger.py::LoggerTests::test_it_escapes_strings", "tests/test_logger.py::LoggerTests::test_it_forwards_serializer_kwargs_instance_attr_to_serializer", "tests/test_logger.py::LoggerTests::test_it_forwards_serializer_kwargs_parameter_to_serializer", "tests/test_logger.py::LoggerTests::test_it_logs_current_log_time", "tests/test_logger.py::LoggerTests::test_it_logs_datetime_objects", "tests/test_logger.py::LoggerTests::test_it_logs_valid_json_string_if_message_is_json_serializeable", "tests/test_logger.py::LoggerTests::test_it_logs_valid_json_string_if_message_isnt_json_serializeable" ]
[]
null
2,608
[ "setup.py", "simple_json_logger/formatter.py" ]
[ "setup.py", "simple_json_logger/formatter.py" ]
mroberge__hydrofunctions-28
115ea0905e8ecc1ff287a9298b65efc3bb921c75
2018-05-31 20:40:05
115ea0905e8ecc1ff287a9298b65efc3bb921c75
diff --git a/.travis.yml b/.travis.yml index 560083b..0c2dbc9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,9 +20,9 @@ install: # https://github.com/travis-ci/travis-ci/issues/2650#issuecomment-252285413 # https://github.com/travis-ci/travis-ci/issues/2650#issuecomment-266721196 - # the "--only-binary" option was added in pip 7 back in 2015; still to be safe + # the "--only-binary" option was added in pip 7 back in 2015; still to be safe, upgrade pip - pip install --upgrade pip setuptools wheel - - pip install --only-binary=numpy,scipy,pandas,Ipython numpy scipy pandas ipython + - pip install --only-binary=numpy,scipy,pandas,Ipython,matplotlib numpy scipy pandas ipython matplotlib # Install codecov so I can use it (and coverage.py) to run setup.py # However, keep codecov in setup.py so that it gets installed for local usage too. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 14500ef..55c2fcb 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -130,7 +130,9 @@ Ready to contribute? Here's how to set up `hydrofunctions` for local development #. After you've made a small change, make sure you didn't break anything by running the tests again. I find it easiest to run the tests from the command - line. + line:: + + > python setup.py tests #. Before you make too many changes, 'commit' what you've done. Ideally, each group of changes that you put into a commit will be logically related to each diff --git a/HISTORY.rst b/HISTORY.rst index c484228..2694c74 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -55,5 +55,6 @@ History ---------------------- * Added a flow duration chart (mcr) +* Added the cycleplot chart (mcr) * Added code coverage (mcr) * improved the build scripts for TravisCI (mcr) \ No newline at end of file diff --git a/hydrofunctions/__init__.py b/hydrofunctions/__init__.py index f3e4159..556517d 100644 --- a/hydrofunctions/__init__.py +++ b/hydrofunctions/__init__.py @@ -34,6 +34,7 @@ List all of the different attributes and methods with dir():: Read more about Hydrofunctions here: https://hydrofunctions.readthedocs.io/ """ +from __future__ import absolute_import, print_function __title__ = 'hydrofunctions' __version__ = '0.1.6' diff --git a/hydrofunctions/charts.py b/hydrofunctions/charts.py index f67b513..b17dcf7 100644 --- a/hydrofunctions/charts.py +++ b/hydrofunctions/charts.py @@ -8,17 +8,15 @@ Charting functions for Hydrofunctions. # See https://matplotlib.org/faq/howto_faq.html # Basically, matplotlib usually uses an 'X11 connection' by default; Travis CI # does not have this configured, so you need to set your backend explicitly. +from __future__ import absolute_import, print_function import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter +import numpy as np -# I don't need these yet, but soon... -import bokeh -import seaborn - -def flow_duration(Qdf, xscale='logit', yscale='log', ylabel='Discharge', symbol='.'): +def flow_duration(Qdf, xscale='logit', yscale='log', ylabel='Stream Discharge (m³/s)', symbol='.'): """Creates a flow duration chart from a dataframe of discharges. Args: @@ -37,7 +35,7 @@ def flow_duration(Qdf, xscale='logit', yscale='log', ylabel='Discharge', symbol= yscale ('log' | 'linear'): The type of y scale for plotting discharge. Default is 'log'. - ylabel (str, default: 'Discharge'): The label for the Y axis. + ylabel (str, default: 'Stream Discharge (m³/s)'): The label for the Y axis. xlabel (not implemented) @@ -72,3 +70,112 @@ def flow_duration(Qdf, xscale='logit', yscale='log', ylabel='Discharge', symbol= #ax.set_xlabel('Probability of Exceedence') ax.xaxis.set_minor_formatter(NullFormatter()) return fig, ax + + +def cycleplot(DF, cycle='diurnal', compare=None): + # inspired by: https://jakevdp.github.io/PythonDataScienceHandbook/03.11-working-with-time-series.html + + if cycle == 'annual': + # aggregate into 365 bins to show annual cycles. Same as annual-date + aggregateby = DF.index.dayofyear + x_label = ' (day # of the year)' + elif cycle == 'annual-date': + aggregateby = DF.index.dayofyear + x_label = ' (day # of the year)' + elif cycle == 'annual-week': + # aggregate into 52 bins to show annual cycles. + aggregateby = DF.index.week + x_label = ' (week # of the year)' + elif cycle == 'annual-month': + # aggregate into 12 binds to show annual cycles. + aggregateby = DF.index.month + x_label = ' (month # of the year)' + elif cycle == 'weekly': + # aggregate into 7 bins to show week-long cycles. + # Note: 7-day cycles are not natural cycles. + aggregateby = DF.index.weekday + x_label = ' (day of the week, Monday = 0)' + elif cycle == 'diurnal': + # aggregate into 24 bins to show 24-hour daily (diurnal) cycles. + aggregateby = DF.index.hour + x_label = ' (hour of the day)' + elif cycle == 'diurnal-smallest': + # Uses the smallest unit available in the time index to show 24-hour diurnal cycles. + aggregateby = DF.index.time + x_label = ' (time of day)' + elif cycle == 'diurnal-hour': + # aggregate into 24 bins to show 24-hour daily (diurnal) cycles. + aggregateby = DF.index.hour + x_label = ' (hour of the day)' + else: + print("The cycle label '", cycle, "' is not recognized as an option. Using cycle='diurnal' instead.") + aggregateby = DF.index.hour + x_label = ' (hour of the day)' + + if compare is None: + # Don't make a comparison plot. + # TODO: This is a silly categorization to force all values in the index into the same category. + compareby = np.where(DF.index.weekday < 20, 'A', 'B') + sub_titles = [''] + elif compare == 'month': + # Break the time series into 12 months to compare to each other. + compareby = DF.index.month + sub_titles = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] + elif compare == 'weekday': + # Break the time series into 7 days of the week to compare to each other. + compareby = DF.index.weekday + sub_titles = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] + elif compare == 'weekend': + # Break the time series into 2 groups, Weekdays and Weekends for comparison. + compareby = np.where(DF.index.weekday < 5, 'Weekday', 'Weekend') + sub_titles = ['Weekdays', 'Weekends'] + elif compare == 'night': + # Break the time series into 2 groups to compare day versus night. + compareby = np.where((DF.index.hour >= 6) & (DF.index.hour < 19), 'Day', 'Night') + sub_titles = ['Day', 'Night'] + else: + print("The compare label '", compare, "' is not recognized as an option. Using compare=None instead.") + compareby = np.where(DF.index.weekday < 20, 'A', 'B') + sub_titles = ['data'] + + selection = [compareby, aggregateby] + compare = list(np.unique(compareby)) + + # group first by the compareby series, then by the cycle. + by_time = DF.groupby(selection) + mean = by_time.mean() + Q2 = by_time.quantile(.2) + Q4 = by_time.quantile(.4) + Q5 = by_time.quantile(.5) + Q6 = by_time.quantile(.6) + Q8 = by_time.quantile(.8) + + Nplots = len(compare) + fig, axs = plt.subplots(1, Nplots, figsize=(14, 6), sharey=True, sharex=True) + if Nplots == 1: + # If there is only one subplot, it gets returned as a single subplot instead of as a numpy array. In this case, we convert it to an array. + axs = np.array([axs]) + + for i, item in enumerate(compare): + axs[i].plot(mean.loc[item], label='mean') + # axs[i].plot(Q2.loc[item], label='20th percentile', color='black', linestyle='dotted', linewidth=2) + axs[i].plot(Q5.loc[item], label='median', color='black', linestyle='dotted', linewidth=2) + # axs[i].plot(Q8.loc[item], label='80th percentile', color='grey', linestyle='dashed', linewidth=1) + axs[i].fill_between(Q2.loc[item].index, Q2.loc[item].values.flatten(), Q8.loc[item].values.flatten(), facecolor='grey', alpha=0.5) + axs[i].fill_between(Q4.loc[item].index, Q4.loc[item].values.flatten(), Q6.loc[item].values.flatten(), facecolor='grey', alpha=0.5) + axs[i].set_title(sub_titles[i]) + # axs[i].xaxis.set_major_locator(plt.MaxNLocator(4)) + # axs[i].xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H')) + + # Set the legend on either the ax or fig. + axs[0].legend(loc='best', fancybox=True, framealpha=0.5) + # fig.legend(loc='upper center', shadow=True, frameon=True, fancybox=True, framealpha=0.5) + + # Get the yaxis limits, set bottom to zero. + ymin, ymax = axs[0].get_ylim() + axs[0].set_ylim(0, ymax) + axs[0].set_ylabel('Stream Discharge (m³/s)') + axs[0].set_xlabel('Time' + x_label) + plt.tight_layout() + + return fig, axs diff --git a/hydrofunctions/hydrofunctions.py b/hydrofunctions/hydrofunctions.py index 6a72215..c9be04e 100644 --- a/hydrofunctions/hydrofunctions.py +++ b/hydrofunctions/hydrofunctions.py @@ -167,12 +167,12 @@ def get_nwis(site, service, start_date=None, end_date=None, stateCd=None, return response -def get_nwis_property(response_obj, key=None, remove_duplicates=False): +def get_nwis_property(nwis_dict, key=None, remove_duplicates=False): """Returns a list containing property data from an NWIS response object. Args: - response_obj (obj): - a response object as returned by get_nwis(). + nwis_dict (dict): + the json returned in a response object as produced by get_nwis().json(). key (str): a valid NWIS response property key. Default is None. The index is \ @@ -204,7 +204,7 @@ def get_nwis_property(response_obj, key=None, remove_duplicates=False): ValueError when the key is not available in """ - nwis_dict = response_obj.json() + #nwis_dict = response_obj.json() # strip header and all metadata. ts = nwis_dict['value']['timeSeries'] @@ -257,12 +257,12 @@ def get_nwis_property(response_obj, key=None, remove_duplicates=False): return vals -def extract_nwis_df(response_obj): +def extract_nwis_df(nwis_dict): """Returns a Pandas dataframe from an NWIS response object. Args: - response_obj (obj): - a response object as returned by get_nwis(). + nwis_dict (obj): + the json from a response object as returned by get_nwis().json(). Returns: a pandas dataframe. @@ -271,7 +271,7 @@ def extract_nwis_df(response_obj): HydroNoDataError when the request is valid, but NWIS has no data for the parameters provided in the request. """ - nwis_dict = response_obj.json() + #nwis_dict = response_obj.json() # strip header and all metadata. ts = nwis_dict['value']['timeSeries'] @@ -296,8 +296,8 @@ def extract_nwis_df(response_obj): " have any data for this request.") # create lists of timeseries keys and noDataValues - keys = get_nwis_property(response_obj) - noDataValues = get_nwis_property(response_obj, key='noDataValue', + keys = get_nwis_property(nwis_dict) + noDataValues = get_nwis_property(nwis_dict, key='noDataValue', remove_duplicates=True) # determine the NWIS data item with the maximum amount of data so that # it can be processed first @@ -340,6 +340,27 @@ def extract_nwis_df(response_obj): 'qualifiers': tsqual}) dfa[tsname] = dfa[tsname].astype(float) dfa[tsqual] = dfa[tsqual].apply(lambda x: ' '.join(x)) + + # TODO: + + # The problem with adding all of these dataframes to a single large + # dataframe using pd.concat is that sites that collect less frequently + # will get padded with NANs for all of the time indecies that they + # don't have data for. + + # A second problem is that every other column will have data, and the + # the other columns will have flags. There is no simple way to + # select only the data columns except to take the odd numbered columns. + + # A POSSIBLE SOLUTION: create a data structure that is composed of + # Stacked dataframes. Each data frame will correspond to a single site, + # The first column will correspond to discharge, the second to flags, + # and any others can be derived values like baseflow or other measured + # parameters. The dataframes will be stacked, and be part of an object + # that allows you to select by a range of dates, by sites, and by the + # type of column. In this respect, it might be similar to XArray, + # except that package requires their n-dimensional structures to all be + # the same datatype. DF = pd.concat([DF, dfa], axis=1) # replace missing values in the dataframe diff --git a/hydrofunctions/station.py b/hydrofunctions/station.py index 1600a76..f3d1828 100644 --- a/hydrofunctions/station.py +++ b/hydrofunctions/station.py @@ -114,7 +114,7 @@ class NWIS(Station): self.stateCd = stateCd self.countyCd = countyCd self.bBox = bBox - self.ok = None + self.ok = False self.parameterCd = parameterCd self.period = typing.check_period(period) self.response = None @@ -164,16 +164,16 @@ class NWIS(Station): # set self.json without calling it. self.json = lambda: self.response.json() # set self.df without calling it. - self.df = lambda: hf.extract_nwis_df(self.response) + self.df = lambda: hf.extract_nwis_df(self.json()) # Another option might be to do this: # self.df = hf.extract_nwis_df(self.response) # This would make myInstance.df return a plain df. self.ok = self.response.ok - self.siteName = hf.get_nwis_property(self.response, + self.siteName = hf.get_nwis_property(self.json(), key='siteName', remove_duplicates=True) - self.name = hf.get_nwis_property(self.response, + self.name = hf.get_nwis_property(self.json(), key='name', remove_duplicates=True) diff --git a/hydrofunctions/typing.py b/hydrofunctions/typing.py index c1331d5..530acf8 100644 --- a/hydrofunctions/typing.py +++ b/hydrofunctions/typing.py @@ -17,6 +17,7 @@ Suggested format for these functions: * then do a regular expression to check that the input is more or less valid. * raise exceptions when user input breaks format. """ +from __future__ import absolute_import, print_function import re diff --git a/setup.py b/setup.py index d27fb50..da3c624 100644 --- a/setup.py +++ b/setup.py @@ -27,8 +27,6 @@ readme = relative2absolute(readme, relative, stem) requirements = [ 'matplotlib', - 'bokeh', - 'seaborn', 'numpy', 'pandas', 'requests', diff --git a/tox.ini b/tox.ini deleted file mode 100644 index 8420e7c..0000000 --- a/tox.ini +++ /dev/null @@ -1,18 +0,0 @@ -[tox] -envlist = py34, py35, py36, flake8 - -[testenv:flake8] -basepython=python -deps=flake8 -commands=flake8 hydrofunctions - -[testenv] -setenv = - PYTHONPATH = {toxinidir}:{toxinidir}/hydrofunctions - -commands = python setup.py test - -; If you want to make tox run the tests with the same versions, create a -; requirements.txt with the pinned versions and uncomment the following lines: -; deps = -; -r{toxinidir}/requirements.txt
Travis-CI failure: python 3.5 segmentation fault * HydroFunctions version: 0.1.6 all branches * Python version: 3.5 * Operating System: Linux (Travis-ci build) * Travis Job [#184](https://travis-ci.org/mroberge/hydrofunctions/jobs/379854009) ### Description Travis-ci suddenly exits during the first test with a segmentation fault. This does not affect Python 3.4 or 3.6. ### What I Did ``` python setup.py test ... running build_ext test_charts_cycleplot_exists (tests.test_charts.TestCyclePlot) ... /home/travis/.travis/job_stages: line 57: 1794 Segmentation fault (core dumped) python setup.py test ```
mroberge/hydrofunctions
diff --git a/tests/__init__.py b/tests/__init__.py index 40a96af..c2559a5 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,1 +1,2 @@ # -*- coding: utf-8 -*- +from __future__ import absolute_import, print_function diff --git a/tests/test_charts.py b/tests/test_charts.py index bb350bf..a20d465 100644 --- a/tests/test_charts.py +++ b/tests/test_charts.py @@ -7,10 +7,11 @@ Tests for the charts.py module. from __future__ import absolute_import, print_function import unittest import matplotlib -# attempted matplotlib.use('Agg') here, but it was too late; backend already set import pandas as pd from hydrofunctions import charts +import hydrofunctions as hf +from .test_data import JSON15min2month as test_json dummy = {'col1': [1, 2, 3, 38, 23, 1, 19], 'col2': [3, 4, 45, 23, 2, 4, 76]} @@ -36,7 +37,7 @@ class TestFlowDuration(unittest.TestCase): self.assertEqual(actual_xscale, 'logit') self.assertEqual(actual_yscale, 'log') - self.assertEqual(actual_ylabel, 'Discharge') + self.assertEqual(actual_ylabel, 'Stream Discharge (m³/s)') self.assertEqual(actual_marker, '.') def test_charts_flowduration_accepts_params(self): @@ -59,5 +60,27 @@ class TestFlowDuration(unittest.TestCase): self.assertEqual(actual_marker, ',') +class TestCyclePlot(unittest.TestCase): + + def test_charts_cycleplot_exists(self): + expected = hf.extract_nwis_df(test_json) + actual_fig, actual_ax = charts.cycleplot(expected) + self.assertIsInstance(actual_fig, matplotlib.figure.Figure) + self.assertIsInstance(actual_ax[0], matplotlib.axes.Axes) + + def test_charts_cycleplot_parts(self): + expected = hf.extract_nwis_df(test_json) + + actual_fig, actual_ax = charts.cycleplot(expected) + + actual_xscale = actual_ax[0].xaxis.get_scale() + actual_yscale = actual_ax[0].yaxis.get_scale() + actual_ylabel = actual_ax[0].yaxis.get_label_text() + + self.assertEqual(actual_xscale, 'linear') + self.assertEqual(actual_yscale, 'linear') + self.assertEqual(actual_ylabel, 'Stream Discharge (m³/s)') + + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/tests/test_data.py b/tests/test_data.py new file mode 100644 index 0000000..af257f6 --- /dev/null +++ b/tests/test_data.py @@ -0,0 +1,3085 @@ +# -*- coding: utf-8 -*- +""" +Created on Tue May 15 19:33:19 2018 + +@author: Marty +""" + + +JSON15min2month = { +'declaredType': 'org.cuahsi.waterml.TimeSeriesResponseType', + 'globalScope': True, + 'name': 'ns1:timeSeriesResponseType', + 'nil': False, + 'scope': 'javax.xml.bind.JAXBElement$GlobalScope', + 'typeSubstituted': False, + 'value': {'queryInfo': {'criteria': {'locationParam': '[ALL:03213700]', + 'parameter': [], + 'timeParam': {'beginDateTime': '2016-09-01T00:00:00.000', + 'endDateTime': '2017-11-01T23:59:59.000'}, + 'variableParam': '[00060]'}, + 'note': [{'title': 'filter:sites', 'value': '[ALL:03213700]'}, + {'title': 'filter:timeRange', + 'value': '[mode=RANGE, modifiedSince=null] interval={INTERVAL[2016-09-01T00:00:00.000-04:00/2017-11-01T23:59:59.000Z]}'}, + {'title': 'filter:methodId', 'value': 'methodIds=[ALL]'}, + {'title': 'requestDT', 'value': '2018-05-15T23:32:02.320Z'}, + {'title': 'requestId', 'value': '2b84b1f0-5898-11e8-a9ea-3440b59d3362'}, + {'title': 'disclaimer', + 'value': 'Provisional data are subject to revision. Go to http://waterdata.usgs.gov/nwis/help/?provisional for more information.'}, + {'title': 'server', 'value': 'nadww02'}], + 'queryURL': 'http://nwis.waterservices.usgs.gov/nwis/iv/format=json%2C1.1&sites=03213700&parameterCd=00060&startDT=2016-09-01&endDT=2017-11-01'}, + 'timeSeries': [{'name': 'USGS:03213700:00060:00000', + 'sourceInfo': {'geoLocation': {'geogLocation': {'latitude': 37.67315699, + 'longitude': -82.2801408, + 'srs': 'EPSG:4326'}, + 'localSiteXY': []}, + 'note': [], + 'siteCode': [{'agencyCode': 'USGS', + 'network': 'NWIS', + 'value': '03213700'}], + 'siteName': 'TUG FORK AT WILLIAMSON, WV', + 'siteProperty': [{'name': 'siteTypeCd', 'value': 'ST'}, + {'name': 'hucCd', 'value': '05070201'}, + {'name': 'stateCd', 'value': '21'}, + {'name': 'countyCd', 'value': '21195'}], + 'siteType': [], + 'timeZoneInfo': {'daylightSavingsTimeZone': {'zoneAbbreviation': 'EDT', + 'zoneOffset': '-04:00'}, + 'defaultTimeZone': {'zoneAbbreviation': 'EST', 'zoneOffset': '-05:00'}, + 'siteUsesDaylightSavingsTime': True}}, + 'values': [{'censorCode': [], + 'method': [{'methodDescription': '', 'methodID': 160874}], + 'offset': [], + 'qualifier': [{'network': 'NWIS', + 'qualifierCode': 'e', + 'qualifierDescription': 'Value has been edited or estimated by USGS personnel and is write protected.', + 'qualifierID': 0, + 'vocabulary': 'uv_rmk_cd'}, + {'network': 'NWIS', + 'qualifierCode': 'A', + 'qualifierDescription': 'Approved for publication -- Processing and review completed.', + 'qualifierID': 1, + 'vocabulary': 'uv_rmk_cd'}, + {'network': 'NWIS', + 'qualifierCode': 'P', + 'qualifierDescription': 'Provisional data subject to revision.', + 'qualifierID': 2, + 'vocabulary': 'uv_rmk_cd'}], + 'qualityControlLevel': [], + 'sample': [], + 'source': [], + 'value': [{'dateTime': '2016-09-01T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '366'}, + {'dateTime': '2016-09-01T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '363'}, + {'dateTime': '2016-09-01T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '363'}, + {'dateTime': '2016-09-01T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '363'}, + {'dateTime': '2016-09-01T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '363'}, + {'dateTime': '2016-09-01T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '363'}, + {'dateTime': '2016-09-01T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '360'}, + {'dateTime': '2016-09-01T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '357'}, + {'dateTime': '2016-09-01T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '357'}, + {'dateTime': '2016-09-01T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '357'}, + {'dateTime': '2016-09-01T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '357'}, + {'dateTime': '2016-09-01T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '354'}, + {'dateTime': '2016-09-01T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '354'}, + {'dateTime': '2016-09-01T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '354'}, + {'dateTime': '2016-09-01T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '351'}, + {'dateTime': '2016-09-01T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '351'}, + {'dateTime': '2016-09-01T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '351'}, + {'dateTime': '2016-09-01T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '348'}, + {'dateTime': '2016-09-01T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '345'}, + {'dateTime': '2016-09-01T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '345'}, + {'dateTime': '2016-09-01T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '345'}, + {'dateTime': '2016-09-01T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '342'}, + {'dateTime': '2016-09-01T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '339'}, + {'dateTime': '2016-09-01T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '339'}, + {'dateTime': '2016-09-01T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '336'}, + {'dateTime': '2016-09-01T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '336'}, + {'dateTime': '2016-09-01T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '334'}, + {'dateTime': '2016-09-01T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '334'}, + {'dateTime': '2016-09-01T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '334'}, + {'dateTime': '2016-09-01T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '331'}, + {'dateTime': '2016-09-01T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '331'}, + {'dateTime': '2016-09-01T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '331'}, + {'dateTime': '2016-09-01T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '328'}, + {'dateTime': '2016-09-01T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '328'}, + {'dateTime': '2016-09-01T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '325'}, + {'dateTime': '2016-09-01T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '328'}, + {'dateTime': '2016-09-01T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '325'}, + {'dateTime': '2016-09-01T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '325'}, + {'dateTime': '2016-09-01T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '325'}, + {'dateTime': '2016-09-01T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '325'}, + {'dateTime': '2016-09-01T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '322'}, + {'dateTime': '2016-09-01T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '319'}, + {'dateTime': '2016-09-01T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '319'}, + {'dateTime': '2016-09-01T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '319'}, + {'dateTime': '2016-09-01T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '319'}, + {'dateTime': '2016-09-01T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '319'}, + {'dateTime': '2016-09-01T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '319'}, + {'dateTime': '2016-09-01T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '317'}, + {'dateTime': '2016-09-01T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '314'}, + {'dateTime': '2016-09-01T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '314'}, + {'dateTime': '2016-09-01T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '311'}, + {'dateTime': '2016-09-01T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '311'}, + {'dateTime': '2016-09-01T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '311'}, + {'dateTime': '2016-09-01T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '311'}, + {'dateTime': '2016-09-01T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '308'}, + {'dateTime': '2016-09-01T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '308'}, + {'dateTime': '2016-09-01T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '308'}, + {'dateTime': '2016-09-01T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '308'}, + {'dateTime': '2016-09-01T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '308'}, + {'dateTime': '2016-09-01T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '308'}, + {'dateTime': '2016-09-01T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '308'}, + {'dateTime': '2016-09-01T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '305'}, + {'dateTime': '2016-09-01T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '305'}, + {'dateTime': '2016-09-01T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '305'}, + {'dateTime': '2016-09-01T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '305'}, + {'dateTime': '2016-09-01T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '305'}, + {'dateTime': '2016-09-01T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '305'}, + {'dateTime': '2016-09-01T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '305'}, + {'dateTime': '2016-09-01T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-01T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-01T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '303'}, + {'dateTime': '2016-09-02T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '297'}, + {'dateTime': '2016-09-02T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '300'}, + {'dateTime': '2016-09-02T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '297'}, + {'dateTime': '2016-09-02T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '297'}, + {'dateTime': '2016-09-02T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '297'}, + {'dateTime': '2016-09-02T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '297'}, + {'dateTime': '2016-09-02T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '293'}, + {'dateTime': '2016-09-02T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '293'}, + {'dateTime': '2016-09-02T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '293'}, + {'dateTime': '2016-09-02T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '290'}, + {'dateTime': '2016-09-02T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '286'}, + {'dateTime': '2016-09-02T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '283'}, + {'dateTime': '2016-09-02T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-02T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-02T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '280'}, + {'dateTime': '2016-09-03T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '276'}, + {'dateTime': '2016-09-03T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '273'}, + {'dateTime': '2016-09-03T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '266'}, + {'dateTime': '2016-09-03T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '266'}, + {'dateTime': '2016-09-03T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '266'}, + {'dateTime': '2016-09-03T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '270'}, + {'dateTime': '2016-09-03T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '266'}, + {'dateTime': '2016-09-03T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '266'}, + {'dateTime': '2016-09-03T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '266'}, + {'dateTime': '2016-09-03T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '266'}, + {'dateTime': '2016-09-03T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '263'}, + {'dateTime': '2016-09-03T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '263'}, + {'dateTime': '2016-09-03T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '263'}, + {'dateTime': '2016-09-03T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-03T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '263'}, + {'dateTime': '2016-09-03T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-03T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '260'}, + {'dateTime': '2016-09-04T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '257'}, + {'dateTime': '2016-09-04T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '254'}, + {'dateTime': '2016-09-04T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '254'}, + {'dateTime': '2016-09-04T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '250'}, + {'dateTime': '2016-09-04T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-04T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-04T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-05T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '247'}, + {'dateTime': '2016-09-05T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '244'}, + {'dateTime': '2016-09-05T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-05T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '238'}, + {'dateTime': '2016-09-05T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-05T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-05T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-05T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-06T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-06T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-06T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-06T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-06T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-07T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-07T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-07T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-07T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-07T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-07T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-07T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-07T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-07T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-07T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-07T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-07T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-08T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-08T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-08T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-08T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-08T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-08T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-08T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-08T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '200'}, + {'dateTime': '2016-09-09T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-09T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-09T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-09T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-09T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-09T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T10:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T10:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T10:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T10:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T11:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T11:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T11:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T11:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T12:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T12:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T12:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T12:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T13:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T13:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T13:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T13:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T14:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T14:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T14:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T14:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T15:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T15:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T15:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T15:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T16:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T16:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-10T16:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T16:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T17:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T17:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T17:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T17:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T18:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T18:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T18:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T18:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T19:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T19:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T19:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T19:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T20:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T20:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T20:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T20:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T21:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T21:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T21:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T21:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T22:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '205'}, + {'dateTime': '2016-09-10T22:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '202'}, + {'dateTime': '2016-09-10T22:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-10T22:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '226'}, + {'dateTime': '2016-09-10T23:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-10T23:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-10T23:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-10T23:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-11T00:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '241'}, + {'dateTime': '2016-09-11T00:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '235'}, + {'dateTime': '2016-09-11T00:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '232'}, + {'dateTime': '2016-09-11T00:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '229'}, + {'dateTime': '2016-09-11T01:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-11T01:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '223'}, + {'dateTime': '2016-09-11T01:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '220'}, + {'dateTime': '2016-09-11T01:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T02:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T02:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T02:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T02:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T03:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T03:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T03:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T03:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T04:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T04:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T04:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T04:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T05:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T05:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T05:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '217'}, + {'dateTime': '2016-09-11T05:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-11T06:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-11T06:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-11T06:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '214'}, + {'dateTime': '2016-09-11T06:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-11T07:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-11T07:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-11T07:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-11T07:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-11T08:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-11T08:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-11T08:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-11T08:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-11T09:00:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-11T09:15:00.000-04:00', + 'qualifiers': ['A'], + 'value': '208'}, + {'dateTime': '2016-09-11T09:30:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'}, + {'dateTime': '2016-09-11T09:45:00.000-04:00', + 'qualifiers': ['A'], + 'value': '211'} + ]}], + 'variable': {'noDataValue': -999999.0, + 'note': [], + 'oid': '45807197', + 'options': {'option': [{'name': 'Statistic', 'optionCode': '00000'}]}, + 'unit': {'unitCode': 'ft3/s'}, + 'valueType': 'Derived Value', + 'variableCode': [{'default': True, + 'network': 'NWIS', + 'value': '00060', + 'variableID': 45807197, + 'vocabulary': 'NWIS:UnitValues'}], + 'variableDescription': 'Discharge, cubic feet per second', + 'variableName': 'Streamflow, ft&#179;/s', + 'variableProperty': []}}]}} diff --git a/tests/test_hydrofunctions.py b/tests/test_hydrofunctions.py index 85a50ca..cd6dd8e 100644 --- a/tests/test_hydrofunctions.py +++ b/tests/test_hydrofunctions.py @@ -14,6 +14,7 @@ import unittest import pandas as pd import hydrofunctions as hf +from .test_data import JSON15min2month as test_json class fakeResponse(object): @@ -22,6 +23,9 @@ class fakeResponse(object): self.status_code = code self.url = "fake url" self.reason = "fake reason" + # .json will return a function + # .json() will return test_json + self.json = lambda: test_json if code == 200: pass else: @@ -89,58 +93,43 @@ class TestHydrofunctions(unittest.TestCase): headers=expected_headers) self.assertEqual(actual, expected) - @unittest.skip('Stop requesting data during test.') def test_hf_extract_nwis_df(self): - # TODO: I need to make a response fixture to test this out!! - test = hf.get_nwis("01589440", "dv", "2013-01-01", "2013-01-05") - actual = hf.extract_nwis_df(test) + # TODO: I need to check this was parsed correctly! + actual = hf.extract_nwis_df(test_json) self.assertIs(type(actual), pd.core.frame.DataFrame, msg="Did not return a df") - @unittest.skip('Stop requesting data during test.') def test_hf_extract_nwis_stations_df(self): sites = ["01638500", "01646502"] # TODO: test should be the json for a multiple site request. - test = hf.get_nwis(sites, "dv", - "2013-01-01", "2013-01-05") - actual = hf.extract_nwis_df(test) - vD = hf.get_nwis_property(test, key='variableDescription') + actual = hf.extract_nwis_df(test_json) + vD = hf.get_nwis_property(test_json, key='variableDescription') self.assertIs(type(actual), pd.core.frame.DataFrame, msg="Did not return a df") - @unittest.skip('Stop requesting data during test.') def test_hf_extract_nwis_iv_gwstations_df(self): # TODO: I need to make a response fixture to test this out!! sites = ["380616075380701", "394008077005601"] - test = hf.get_nwis(sites, "iv", - "2018-01-01", "2018-01-05", parameterCd='72019') - actual = hf.extract_nwis_df(test) + actual = hf.extract_nwis_df(test_json) self.assertIs(type(actual), pd.core.frame.DataFrame, msg="Did not return a df") - - @unittest.skip('Stop requesting data during test.') def test_hf_extract_nwis_bBox_df(self): sites = None bBox = (-105.430, 39.655, -104, 39.863) # TODO: test should be the json for a multiple site request. - test = hf.get_nwis(sites, "dv", - "2013-01-01", "2013-01-05", bBox=bBox) - names = hf.get_nwis_property(test, key='name') + names = hf.get_nwis_property(test_json, key='name') self.assertIs(type(names), list, msg="Did not return a list") - actual = hf.extract_nwis_df(test) + actual = hf.extract_nwis_df(test_json) self.assertIs(type(actual), pd.core.frame.DataFrame, msg="Did not return a df") - @unittest.skip('Stop requesting data during test.') def test_hf_extract_nwis_bBox2_df(self): sites = None bBox = '-105.430,39.655,-104,39.863' # TODO: test should be the json for a multiple site request. - test = hf.get_nwis(sites, "dv", - "2013-01-01", "2013-01-05", bBox=bBox) - names = hf.get_nwis_property(test, key='name') - actual = hf.extract_nwis_df(test) + names = hf.get_nwis_property(test_json, key='name') + actual = hf.extract_nwis_df(test_json) self.assertIs(type(actual), pd.core.frame.DataFrame, msg="Did not return a df") diff --git a/tests/test_station.py b/tests/test_station.py index a996808..800668b 100644 --- a/tests/test_station.py +++ b/tests/test_station.py @@ -21,6 +21,7 @@ class fakeResponse(object): self.status_code = code self.url = "fake url" self.reason = "fake reason" + self.json = lambda: {'data': 'fake json'} if code == 200: self.ok = True else:
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 9 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backcall==0.2.0 bokeh==2.3.3 certifi==2021.5.30 charset-normalizer==2.0.12 cycler==0.11.0 decorator==5.1.1 -e git+https://github.com/mroberge/hydrofunctions.git@115ea0905e8ecc1ff287a9298b65efc3bb921c75#egg=hydrofunctions idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 kiwisolver==1.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 numpy==1.19.5 packaging==21.3 pandas==1.1.5 parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 Pillow==8.4.0 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 scipy==1.5.4 seaborn==0.11.2 six==1.17.0 tomli==1.2.3 tornado==6.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 wcwidth==0.2.13 zipp==3.6.0
name: hydrofunctions channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backcall==0.2.0 - bokeh==2.3.3 - charset-normalizer==2.0.12 - cycler==0.11.0 - decorator==5.1.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - kiwisolver==1.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==8.4.0 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - scipy==1.5.4 - seaborn==0.11.2 - six==1.17.0 - tomli==1.2.3 - tornado==6.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/hydrofunctions
[ "tests/test_charts.py::TestFlowDuration::test_charts_flowduration_defaults", "tests/test_charts.py::TestCyclePlot::test_charts_cycleplot_exists", "tests/test_charts.py::TestCyclePlot::test_charts_cycleplot_parts", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_extract_nwis_bBox2_df", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_extract_nwis_bBox_df", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_extract_nwis_df", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_extract_nwis_iv_gwstations_df", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_extract_nwis_stations_df" ]
[]
[ "tests/test_charts.py::TestFlowDuration::test_charts_flowduration_accepts_params", "tests/test_charts.py::TestFlowDuration::test_charts_flowduration_exists", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_get_nwis_calls_correct_url", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_get_nwis_calls_correct_url_multiple_sites", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_nwis_custom_status_codes_returns_None_for_200", "tests/test_hydrofunctions.py::TestHydrofunctions::test_hf_nwis_custom_status_codes_returns_status_for_non200", "tests/test_station.py::TestStation::test_multiple_instances_only_one_list", "tests/test_station.py::TestStation::test_station_dict_keeps_keys", "tests/test_station.py::TestStation::test_station_dict_returns_dict", "tests/test_station.py::TestStation::test_station_dict_returns_instance", "tests/test_station.py::TestStation::test_station_id_sets", "tests/test_station.py::TestStation::test_station_is_obj", "tests/test_station.py::TestStation::test_station_site_defaults_to_None", "tests/test_station.py::TestStation::test_station_subclasses_maintain_same_station_dict", "tests/test_station.py::TestNWIS::test_NWIS_end_defaults_to_None", "tests/test_station.py::TestNWIS::test_NWIS_get_data_calls_get_nwis_correctly", "tests/test_station.py::TestNWIS::test_NWIS_get_data_calls_get_nwis_mult_sites", "tests/test_station.py::TestNWIS::test_NWIS_service_defaults_to_dv", "tests/test_station.py::TestNWIS::test_NWIS_setters_parameterCd", "tests/test_station.py::TestNWIS::test_NWIS_setters_work", "tests/test_station.py::TestNWIS::test_NWIS_start_defaults_to_None", "tests/test_station.py::TestNWIS::test_hf_get_nwis_accepts_countyCd_array" ]
[]
MIT License
2,609
[ "hydrofunctions/charts.py", "hydrofunctions/hydrofunctions.py", "HISTORY.rst", "setup.py", "CONTRIBUTING.rst", "hydrofunctions/__init__.py", ".travis.yml", "tox.ini", "hydrofunctions/typing.py", "hydrofunctions/station.py" ]
[ "hydrofunctions/charts.py", "hydrofunctions/hydrofunctions.py", "HISTORY.rst", "setup.py", "CONTRIBUTING.rst", "hydrofunctions/__init__.py", ".travis.yml", "tox.ini", "hydrofunctions/typing.py", "hydrofunctions/station.py" ]
pika__pika-1057
c0ed61e151c02dc3a84a7c7e4ca5f72ab9d87d9f
2018-05-31 21:02:39
4c904dea651caaf2a54b0fca0b9e908dec18a4f8
diff --git a/pika/heartbeat.py b/pika/heartbeat.py index 4eaaa59..3c9f46f 100644 --- a/pika/heartbeat.py +++ b/pika/heartbeat.py @@ -12,21 +12,24 @@ class HeartbeatChecker(object): intervals. """ + DEFAULT_INTERVAL = 60 MAX_IDLE_COUNT = 2 + _STALE_CONNECTION = "Too Many Missed Heartbeats, No reply in %i seconds" - def __init__(self, connection, interval, idle_count=MAX_IDLE_COUNT): + def __init__(self, connection, interval=DEFAULT_INTERVAL, idle_count=MAX_IDLE_COUNT): """Create a heartbeat on connection sending a heartbeat frame every interval seconds. :param pika.connection.Connection: Connection object - :param int interval: Heartbeat check interval - :param int idle_count: Number of heartbeat intervals missed until the - connection is considered idle and disconnects + :param int interval: Heartbeat check interval. Note: heartbeats will + be sent at interval / 2 frequency. """ self._connection = connection - self._interval = interval + # Note: see the following document: + # https://www.rabbitmq.com/heartbeats.html#heartbeats-timeout + self._interval = float(interval / 2) self._max_idle_count = idle_count # Initialize counters
HeartbeatChecker is confused about heartbeat timeouts cc @lukebakken, the fix should probably be back-ported to the 0.12 release candidate. `HeartbeatChecker` constructor presently accepts an interval value and an `idle_count` which defaults to 2. `Connection` class instantiates `HeartbeatChecker` with `interval=hearbeat_timeout` and default `idle_count`. So, if the connection is configured with a heartbeat timeout of 600 (10 minutes), it will pass 600 as the `interval` arg to `HeartbeatChecker`. So, `HearbeatChecker` will emit heartbeats to the broker only once every 600 seconds. And it will detect heartbeat timeout after 1200 seconds. So, in the event that receipt of the heartbeat by the broker is slightly delayed (and in absence of any other AMQP frames from the client), the broker can erroneously conclude that connection with the client is lost and prematurely close the connection. This is clearly not what was intended. `HeartbeatChecker` should be detecting a heartbeat timeout after 600 seconds of inactivity. And it should be sending a heartbeat to the broker more often than just once within the heartbeat timeout window. I see two problems here: 1. Given `HeartbeatChecker`'s present interface, `Connection` should be instantiating it as`HeartbeatChecker(self, interval=float(self.params.heartbeat) / 2, idle_count=2) or something like that (how often does RabbitMQ broker send heartbeats within one heartbeat timeout interval?) 2. `HeartbeatChecker` is not abstracting the internals of heartbeat processing sufficiently. It's constructor should accept the heartbeat timeout value directly (no interval/idle_count business) and encapsulate the frequency of heartbeats internally without bleeding that detail to the `Connection`.
pika/pika
diff --git a/tests/unit/connection_tests.py b/tests/unit/connection_tests.py index 9f40320..438633c 100644 --- a/tests/unit/connection_tests.py +++ b/tests/unit/connection_tests.py @@ -536,7 +536,7 @@ class ConnectionTests(unittest.TestCase): # pylint: disable=R0904 _adapter_emit_data, method, heartbeat_checker): - """make sure on connection tune turns the connection params""" + """make sure _on_connection_tune tunes the connection params""" heartbeat_checker.return_value = 'hearbeat obj' self.connection._flush_outbound = mock.Mock() marshal = mock.Mock(return_value='ab') diff --git a/tests/unit/heartbeat_tests.py b/tests/unit/heartbeat_tests.py index c5a7ca5..eaf339f 100644 --- a/tests/unit/heartbeat_tests.py +++ b/tests/unit/heartbeat_tests.py @@ -55,27 +55,31 @@ class ConstructableConnection(connection.Connection): class HeartbeatTests(unittest.TestCase): - INTERVAL = 5 + INTERVAL = 60 + HALF_INTERVAL = INTERVAL / 2 def setUp(self): self.mock_conn = mock.Mock(spec_set=ConstructableConnection()) self.mock_conn.bytes_received = 100 self.mock_conn.bytes_sent = 100 self.mock_conn._heartbeat_checker = mock.Mock(spec=heartbeat.HeartbeatChecker) - self.obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL) + self.obj = heartbeat.HeartbeatChecker(self.mock_conn) def tearDown(self): del self.obj del self.mock_conn + def test_default_initialization_interval(self): + self.assertEqual(self.obj._interval, self.HALF_INTERVAL) + def test_default_initialization_max_idle_count(self): self.assertEqual(self.obj._max_idle_count, self.obj.MAX_IDLE_COUNT) def test_constructor_assignment_connection(self): - self.assertEqual(self.obj._connection, self.mock_conn) + self.assertIs(self.obj._connection, self.mock_conn) def test_constructor_assignment_heartbeat_interval(self): - self.assertEqual(self.obj._interval, self.INTERVAL) + self.assertEqual(self.obj._interval, self.HALF_INTERVAL) def test_constructor_initial_bytes_received(self): self.assertEqual(self.obj._bytes_received, 0) @@ -94,7 +98,7 @@ class HeartbeatTests(unittest.TestCase): @mock.patch('pika.heartbeat.HeartbeatChecker._setup_timer') def test_constructor_called_setup_timer(self, timer): - heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL) + heartbeat.HeartbeatChecker(self.mock_conn) timer.assert_called_once_with() def test_active_true(self): @@ -122,13 +126,13 @@ class HeartbeatTests(unittest.TestCase): @mock.patch('pika.heartbeat.HeartbeatChecker._close_connection') def test_send_and_check_not_closed(self, close_connection): - obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL) + obj = heartbeat.HeartbeatChecker(self.mock_conn) obj.send_and_check() close_connection.assert_not_called() @mock.patch('pika.heartbeat.HeartbeatChecker._close_connection') def test_send_and_check_missed_bytes(self, close_connection): - obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL) + obj = heartbeat.HeartbeatChecker(self.mock_conn) obj._idle_byte_intervals = self.INTERVAL obj.send_and_check() close_connection.assert_called_once_with() @@ -147,19 +151,19 @@ class HeartbeatTests(unittest.TestCase): @mock.patch('pika.heartbeat.HeartbeatChecker._update_counters') def test_send_and_check_update_counters(self, update_counters): - obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL) + obj = heartbeat.HeartbeatChecker(self.mock_conn) obj.send_and_check() update_counters.assert_called_once_with() @mock.patch('pika.heartbeat.HeartbeatChecker._send_heartbeat_frame') def test_send_and_check_send_heartbeat_frame(self, send_heartbeat_frame): - obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL) + obj = heartbeat.HeartbeatChecker(self.mock_conn) obj.send_and_check() send_heartbeat_frame.assert_called_once_with() @mock.patch('pika.heartbeat.HeartbeatChecker._start_timer') def test_send_and_check_start_timer(self, start_timer): - obj = heartbeat.HeartbeatChecker(self.mock_conn, self.INTERVAL) + obj = heartbeat.HeartbeatChecker(self.mock_conn) obj.send_and_check() start_timer.assert_called_once_with() @@ -202,7 +206,7 @@ class HeartbeatTests(unittest.TestCase): def test_setup_timer_called(self): self.mock_conn._adapter_add_timeout.assert_called_once_with( - self.INTERVAL, self.obj.send_and_check) + self.HALF_INTERVAL, self.obj.send_and_check) @mock.patch('pika.heartbeat.HeartbeatChecker._setup_timer') def test_start_timer_not_active(self, setup_timer):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "test-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 Automat==24.8.1 certifi==2025.1.31 charset-normalizer==3.4.1 codecov==2.1.13 constantly==23.10.4 coverage==7.8.0 exceptiongroup==1.2.2 hyperlink==21.0.0 idna==3.10 incremental==24.7.2 iniconfig==2.1.0 mock==5.2.0 nose==1.3.7 packaging==24.2 -e git+https://github.com/pika/pika.git@c0ed61e151c02dc3a84a7c7e4ca5f72ab9d87d9f#egg=pika pluggy==1.5.0 pytest==8.3.5 requests==2.32.3 tomli==2.2.1 tornado==6.4.2 Twisted==24.11.0 typing_extensions==4.13.0 urllib3==2.3.0 zope.interface==7.2
name: pika channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - automat==24.8.1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - codecov==2.1.13 - constantly==23.10.4 - coverage==7.8.0 - exceptiongroup==1.2.2 - hyperlink==21.0.0 - idna==3.10 - incremental==24.7.2 - iniconfig==2.1.0 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - requests==2.32.3 - tomli==2.2.1 - tornado==6.4.2 - twisted==24.11.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - zope-interface==7.2 prefix: /opt/conda/envs/pika
[ "tests/unit/heartbeat_tests.py::HeartbeatTests::test_active_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_active_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_bytes_received_on_connection", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_close", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_is_idle_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_is_idle_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_assignment_connection", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_assignment_heartbeat_interval", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_called_setup_timer", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_bytes_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_bytes_sent", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_heartbeat_frames_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_heartbeat_frames_sent", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_idle_byte_intervals", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_default_initialization_interval", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_default_initialization_max_idle_count", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_has_received_data_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_has_received_data_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_new_heartbeat_frame", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_increment_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_increment_no_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_missed_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_not_closed", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_send_heartbeat_frame", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_start_timer", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_update_counters", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_heartbeat_counter_incremented", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_heartbeat_send_frame_called", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_setup_timer_called", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_start_timer_active", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_start_timer_not_active", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_update_counters_bytes_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_update_counters_bytes_sent" ]
[]
[ "tests/unit/connection_tests.py::ConnectionTests::test_add_callbacks", "tests/unit/connection_tests.py::ConnectionTests::test_add_on_close_callback", "tests/unit/connection_tests.py::ConnectionTests::test_add_on_connection_blocked_callback", "tests/unit/connection_tests.py::ConnectionTests::test_add_on_connection_unblocked_callback", "tests/unit/connection_tests.py::ConnectionTests::test_add_on_open_error_callback", "tests/unit/connection_tests.py::ConnectionTests::test_blocked_connection_multiple_blocked_in_a_row_sets_timer_once", "tests/unit/connection_tests.py::ConnectionTests::test_blocked_connection_multiple_unblocked_in_a_row_removes_timer_once", "tests/unit/connection_tests.py::ConnectionTests::test_blocked_connection_on_stream_terminated_removes_timer", "tests/unit/connection_tests.py::ConnectionTests::test_blocked_connection_timeout_terminates_connection", "tests/unit/connection_tests.py::ConnectionTests::test_blocked_connection_unblocked_removes_timer", "tests/unit/connection_tests.py::ConnectionTests::test_channel", "tests/unit/connection_tests.py::ConnectionTests::test_channel_on_closed_connection_raises_connection_closed", "tests/unit/connection_tests.py::ConnectionTests::test_channel_on_closing_connection_raises_connection_closed", "tests/unit/connection_tests.py::ConnectionTests::test_channel_on_init_connection_raises_connection_closed", "tests/unit/connection_tests.py::ConnectionTests::test_channel_on_protocol_connection_raises_connection_closed", "tests/unit/connection_tests.py::ConnectionTests::test_channel_on_start_connection_raises_connection_closed", "tests/unit/connection_tests.py::ConnectionTests::test_channel_on_tune_connection_raises_connection_closed", "tests/unit/connection_tests.py::ConnectionTests::test_client_properties", "tests/unit/connection_tests.py::ConnectionTests::test_client_properties_default", "tests/unit/connection_tests.py::ConnectionTests::test_client_properties_override", "tests/unit/connection_tests.py::ConnectionTests::test_close_calls_on_close_ready_when_no_channels", "tests/unit/connection_tests.py::ConnectionTests::test_close_channels", "tests/unit/connection_tests.py::ConnectionTests::test_close_closes_open_channels", "tests/unit/connection_tests.py::ConnectionTests::test_close_closes_opening_channels", "tests/unit/connection_tests.py::ConnectionTests::test_close_does_not_close_closing_channels", "tests/unit/connection_tests.py::ConnectionTests::test_close_raises_wrong_state_when_already_closed_or_closing", "tests/unit/connection_tests.py::ConnectionTests::test_connect_no_adapter_connect_from_constructor_with_external_workflow", "tests/unit/connection_tests.py::ConnectionTests::test_connection_blocked_sets_timer", "tests/unit/connection_tests.py::ConnectionTests::test_create_with_blocked_connection_timeout_config", "tests/unit/connection_tests.py::ConnectionTests::test_deliver_frame_to_channel_with_frame_for_unknown_channel", "tests/unit/connection_tests.py::ConnectionTests::test_new_conn_should_use_first_channel", "tests/unit/connection_tests.py::ConnectionTests::test_next_channel_number_returns_lowest_unused", "tests/unit/connection_tests.py::ConnectionTests::test_no_side_effects_from_message_marshal_error", "tests/unit/connection_tests.py::ConnectionTests::test_on_channel_cleanup_closing_state_last_channel_calls_on_close_ready", "tests/unit/connection_tests.py::ConnectionTests::test_on_channel_cleanup_closing_state_more_channels_no_on_close_ready", "tests/unit/connection_tests.py::ConnectionTests::test_on_channel_cleanup_non_closing_state", "tests/unit/connection_tests.py::ConnectionTests::test_on_channel_cleanup_with_closing_channels", "tests/unit/connection_tests.py::ConnectionTests::test_on_connection_close_from_broker_passes_correct_exception", "tests/unit/connection_tests.py::ConnectionTests::test_on_connection_close_ok", "tests/unit/connection_tests.py::ConnectionTests::test_on_connection_start", "tests/unit/connection_tests.py::ConnectionTests::test_on_connection_tune", "tests/unit/connection_tests.py::ConnectionTests::test_on_data_available", "tests/unit/connection_tests.py::ConnectionTests::test_on_stream_connected", "tests/unit/connection_tests.py::ConnectionTests::test_on_stream_terminated_cleans_up", "tests/unit/connection_tests.py::ConnectionTests::test_on_stream_terminated_invokes_access_denied_on_connection_error_and_closed", "tests/unit/connection_tests.py::ConnectionTests::test_on_stream_terminated_invokes_auth_on_connection_error_and_closed", "tests/unit/connection_tests.py::ConnectionTests::test_on_stream_terminated_invokes_connection_closed_callback", "tests/unit/connection_tests.py::ConnectionTests::test_on_stream_terminated_invokes_protocol_on_connection_error_and_closed", "tests/unit/connection_tests.py::ConnectionTests::test_send_message_updates_frames_sent_and_bytes_sent", "tests/unit/connection_tests.py::ConnectionTests::test_set_backpressure_multiplier" ]
[]
BSD 3-Clause "New" or "Revised" License
2,610
[ "pika/heartbeat.py" ]
[ "pika/heartbeat.py" ]
streamlink__streamlink-1721
4924b8a15a45de36b459cf1ed20296d414a85c15
2018-05-31 22:40:28
060d38d3f0acc2c4f3b463ea988361622a9b6544
codecov[bot]: # [Codecov](https://codecov.io/gh/streamlink/streamlink/pull/1721?src=pr&el=h1) Report > Merging [#1721](https://codecov.io/gh/streamlink/streamlink/pull/1721?src=pr&el=desc) into [master](https://codecov.io/gh/streamlink/streamlink/commit/ec7e427d6b3f6024018b9d2116eadd918f1a57c8?src=pr&el=desc) will **decrease** coverage by `0.03%`. > The diff coverage is `25.71%`. ```diff @@ Coverage Diff @@ ## master #1721 +/- ## ========================================== - Coverage 36.95% 36.92% -0.04% ========================================== Files 237 237 Lines 13784 13838 +54 ========================================== + Hits 5094 5109 +15 - Misses 8690 8729 +39 ``` beardypig: The incapsula cookies are saved between sessions now :)
diff --git a/src/streamlink/plugins/facebook.py b/src/streamlink/plugins/facebook.py index ee6e4885..2f7776ff 100644 --- a/src/streamlink/plugins/facebook.py +++ b/src/streamlink/plugins/facebook.py @@ -8,7 +8,7 @@ from streamlink.utils import parse_json class Facebook(Plugin): _url_re = re.compile(r"https?://(?:www\.)?facebook\.com/[^/]+/videos") - _mpd_re = re.compile(r'''(sd|hd)_src["']?\s*:\s*(?P<quote>["'])(?P<url>.+?)(?P=quote)''') + _src_re = re.compile(r'''(sd|hd)_src["']?\s*:\s*(?P<quote>["'])(?P<url>.+?)(?P=quote)''') _playlist_re = re.compile(r'''video:\[({url:".+?}\])''') _plurl_re = re.compile(r'''url:"(.*?)"''') @@ -19,19 +19,35 @@ class Facebook(Plugin): def _get_streams(self): res = http.get(self.url, headers={"User-Agent": useragents.CHROME}) - for match in self._mpd_re.finditer(res.text): - manifest_url = match.group("url") - if "\\/" in manifest_url: + streams = {} + vod_urls = set([]) + + for match in self._src_re.finditer(res.text): + stream_url = match.group("url") + if "\\/" in stream_url: # if the URL is json encoded, decode it - manifest_url = parse_json("\"{}\"".format(manifest_url)) - for s in DASHStream.parse_manifest(self.session, manifest_url).items(): - yield s - else: - match = self._playlist_re.search(res.text) - playlist = match and match.group(1) - if playlist: - for url in {url.group(1) for url in self._plurl_re.finditer(playlist)}: - yield "live", HTTPStream(self.session, url) + stream_url = parse_json("\"{}\"".format(stream_url)) + if ".mpd" in stream_url: + streams.update(DASHStream.parse_manifest(self.session, stream_url)) + elif ".mp4" in stream_url: + streams[match.group(1)] = HTTPStream(self.session, stream_url) + vod_urls.add(stream_url) + else: + self.logger.debug("Non-dash/mp4 stream: {0}".format(stream_url)) + + if streams: + return streams + + # fallback on to playlist + self.logger.debug("Falling back to playlist regex") + match = self._playlist_re.search(res.text) + playlist = match and match.group(1) + if playlist: + for url in {url.group(1) for url in self._plurl_re.finditer(playlist)}: + if url not in vod_urls: + streams["sd"] = HTTPStream(self.session, url) + + return streams __plugin__ = Facebook diff --git a/src/streamlink/plugins/funimationnow.py b/src/streamlink/plugins/funimationnow.py index 24cd150f..b3c003cc 100644 --- a/src/streamlink/plugins/funimationnow.py +++ b/src/streamlink/plugins/funimationnow.py @@ -1,23 +1,39 @@ from __future__ import print_function +import logging import random import re +from streamlink.compat import urljoin from streamlink.plugin import Plugin, PluginArguments, PluginArgument from streamlink.plugin.api import http from streamlink.plugin.api import useragents +from streamlink.plugin.api import validate +from streamlink.plugin.api.utils import itertags from streamlink.stream import HLSStream from streamlink.stream import HTTPStream from streamlink.stream.ffmpegmux import MuxedStream +log = logging.getLogger(__name__) + class Experience(object): - api_base = "https://prod-api-funimationnow.dadcdigital.com/api" - show_api_url = api_base + "/source/catalog/title/experience/{experience_id}/" - sources_api_url = api_base + "/source/catalog/video/{experience_id}/signed/" + CSRF_NAME = "csrfmiddlewaretoken" + login_url = "https://www.funimation.com/log-in/" + api_base = "https://www.funimation.com/api" + login_api_url = "https://prod-api-funimationnow.dadcdigital.com/api/auth/login/" + show_api_url = api_base + "/experience/{experience_id}/" + sources_api_url = api_base + "/showexperience/{experience_id}/" languages = ["english", "japanese"] alphas = ["uncut", "simulcast"] + login_schema = validate.Schema(validate.any( + {"success": False, + "error": validate.text}, + {"token": validate.text, + "user": {"id": int}} + )) + def __init__(self, experience_id): """ :param experience_id: starting experience_id, may be changed later @@ -25,6 +41,23 @@ class Experience(object): self.experience_id = experience_id self._language = None self.cache = {} + self.token = None + + def request(self, method, url, *args, **kwargs): + headers = kwargs.pop("headers", {}) + if self.token: + headers.update({"Authorization": "Token {0}".format(self.token)}) + http.cookies.update({"src_token": self.token}) + + log.debug("Making {0}request to {1}".format("authorized " if self.token else "", url)) + + return http.request(method, url, *args, headers=headers, **kwargs) + + def get(self, *args, **kwargs): + return self.request("GET", *args, **kwargs) + + def post(self, *args, **kwargs): + return self.request("POST", *args, **kwargs) @property def pinst_id(self): @@ -34,7 +67,8 @@ class Experience(object): def _update(self): api_url = self.show_api_url.format(experience_id=self.experience_id) - res = http.get(api_url) + log.debug("Requesting experience data: {0}".format(api_url)) + res = self.get(api_url) data = http.json(res) self.cache[self.experience_id] = data @@ -91,19 +125,47 @@ class Experience(object): :return: sources dict """ api_url = self.sources_api_url.format(experience_id=self.experience_id) - res = http.get(api_url, params=dict(pinstId=self.pinst_id)) + res = self.get(api_url, params={"pinst_id": self.pinst_id}) return http.json(res) + def login_csrf(self): + r = http.get(self.login_url) + for input in itertags(r.text, "input"): + if input.attributes.get("name") == self.CSRF_NAME: + return input.attributes.get("value") + + def login(self, email, password): + log.debug("Attempting to login as {0}".format(email)) + r = self.post(self.login_api_url, + data={'username': email, 'password': password, self.CSRF_NAME: self.login_csrf()}, + raise_for_status=False, + headers={"Referer": "https://www.funimation.com/log-in/"}) + d = http.json(r, schema=self.login_schema) + self.token = d.get("token", None) + return self.token is not None + class FunimationNow(Plugin): arguments = PluginArguments( + PluginArgument( + "email", + argument_name="funimation-email", + requires=["password"], + help="Email address for your Funimation account." + ), + PluginArgument( + "password", + argument_name="funimation-password", + sensitive=True, + help="Password for your Funimation account." + ), PluginArgument( "language", argument_name="funimation-language", choices=["en", "ja", "english", "japanese"], default="english", help=""" - The audio language to use for Funimation streams; japanese or english. + The audio language to use for the stream; japanese or english. Default is "english". """ @@ -135,31 +197,39 @@ class FunimationNow(Plugin): # remap en to english, and ja to japanese rlanguage = {"en": "english", "ja": "japanese"}.get(self.get_option("language").lower(), self.get_option("language").lower()) + if "_Incapsula_Resource" in res.text: + self.bypass_incapsula(res) + res = http.get(self.url) id_m = self.experience_id_re.search(res.text) experience_id = id_m and int(id_m.group(1)) if experience_id: - self.logger.debug("Found experience ID: {0}", experience_id) + log.debug("Found experience ID: {0}", experience_id) exp = Experience(experience_id) + if self.get_option("email") and self.get_option("password"): + if exp.login(self.get_option("email"), self.get_option("password")): + log.info("Logged in to Funimation as {0}", self.get_option("email")) + else: + log.warning("Failed to login") - self.logger.debug("Found episode: {0}", exp.episode_info["episodeTitle"]) - self.logger.debug(" has languages: {0}", ", ".join(exp.episode_info["languages"].keys())) - self.logger.debug(" requested language: {0}", rlanguage) - self.logger.debug(" current language: {0}", exp.language) + log.debug("Found episode: {0}", exp.episode_info["episodeTitle"]) + log.debug(" has languages: {0}", ", ".join(exp.episode_info["languages"].keys())) + log.debug(" requested language: {0}", rlanguage) + log.debug(" current language: {0}", exp.language) if rlanguage != exp.language: - self.logger.debug("switching language to: {0}", rlanguage) + log.debug("switching language to: {0}", rlanguage) exp.set_language(rlanguage) if exp.language != rlanguage: - self.logger.warning("Requested language {0} is not available, continuing with {1}", - rlanguage, exp.language) + log.warning("Requested language {0} is not available, continuing with {1}", + rlanguage, exp.language) else: - self.logger.debug("New experience ID: {0}", exp.experience_id) + log.debug("New experience ID: {0}", exp.experience_id) subtitles = None stream_metadata = {} disposition = {} for subtitle in exp.subtitles(): - self.logger.info("Subtitles: {0}", subtitle["src"]) + log.debug("Subtitles: {0}", subtitle["src"]) if subtitle["src"].endswith(".vtt") or subtitle["src"].endswith(".srt"): sub_lang = {"en": "eng", "ja": "jpn"}[subtitle["language"]] # pick the first suitable subtitle stream @@ -167,7 +237,13 @@ class FunimationNow(Plugin): stream_metadata["s:s:0"] = ["language={0}".format(sub_lang)] stream_metadata["s:a:0"] = ["language={0}".format(exp.language_code)] - for item in exp.sources()["items"]: + sources = exp.sources() + if 'errors' in sources: + for error in sources['errors']: + log.error("{0} : {1}".format(error['title'], error['detail'])) + return + + for item in sources["items"]: url = item["src"] if ".m3u8" in url: for q, s in HLSStream.parse_variant_playlist(self.session, url).items(): @@ -186,7 +262,24 @@ class FunimationNow(Plugin): yield self.mp4_quality, s else: - self.logger.error("Could not find experience ID?!") + log.error("Could not find experience ID?!") + + def bypass_incapsula(self, res): + log.info("Attempting to by-pass Incapsula...") + self.clear_cookies(lambda c: "incap" in c.name) + for m in re.finditer(r'''"([A-Z0-9]+)"''', res.text): + d = m.group(1) + # decode the encoded blob to text + js = "".join(map(lambda i: chr(int(i, 16)), [d[x:x + 2] for x in range(0, len(d), 2)])) + jsm = re.search(r'''"GET","([^"]+)''', js) + url = jsm and jsm.group(1) + if url: + log.debug("Found Incapsula auth URL: {0}", url) + res = http.get(urljoin(self.url, url)) + success = res.status_code == 200 + if success: + self.save_cookies(lambda c: "incap" in c.name) + return success __plugin__ = FunimationNow
Funimation Login - [X] This is a feature request. ### Description Is it possible to add a login feature for funimation, like in the crunchyroll plugin?
streamlink/streamlink
diff --git a/tests/test_plugin_funimationnow.py b/tests/test_plugin_funimationnow.py index ca59eed2..7786204a 100644 --- a/tests/test_plugin_funimationnow.py +++ b/tests/test_plugin_funimationnow.py @@ -38,9 +38,11 @@ class TestPluginFunimationNow(unittest.TestCase): } setup_plugin_args(session, parser) - self.assertSequenceEqual(plugin_parser.add_argument.mock_calls, - [call('--funimation-language', + [call('--funimation-email', help=ANY), + call('--funimation-password', help=ANY), + call('--funimation-language', choices=["en", "ja", "english", "japanese"], default="english", help=ANY), call('--funimation-mux-subtitles', action="store_true", help=ANY)]) +
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 codecov==2.1.13 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 freezegun==1.5.1 idna==3.10 iniconfig==2.1.0 iso-639==0.4.5 iso3166==2.1.1 isodate==0.7.2 Jinja2==3.1.6 MarkupSafe==3.0.2 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pycryptodome==3.22.0 pynsist==2.8 PySocks==1.7.1 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 requests==2.32.3 requests-mock==1.12.1 requests_download==0.1.2 six==1.17.0 -e git+https://github.com/streamlink/streamlink.git@4924b8a15a45de36b459cf1ed20296d414a85c15#egg=streamlink tomli==2.2.1 urllib3==2.3.0 websocket-client==1.8.0 yarg==0.1.10
name: streamlink channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - codecov==2.1.13 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - freezegun==1.5.1 - idna==3.10 - iniconfig==2.1.0 - iso-639==0.4.5 - iso3166==2.1.1 - isodate==0.7.2 - jinja2==3.1.6 - markupsafe==3.0.2 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pycryptodome==3.22.0 - pynsist==2.8 - pysocks==1.7.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - requests==2.32.3 - requests-download==0.1.2 - requests-mock==1.12.1 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 - websocket-client==1.8.0 - yarg==0.1.10 prefix: /opt/conda/envs/streamlink
[ "tests/test_plugin_funimationnow.py::TestPluginFunimationNow::test_arguments" ]
[]
[ "tests/test_plugin_funimationnow.py::TestPluginFunimationNow::test_can_handle_url" ]
[]
BSD 2-Clause "Simplified" License
2,611
[ "src/streamlink/plugins/funimationnow.py", "src/streamlink/plugins/facebook.py" ]
[ "src/streamlink/plugins/funimationnow.py", "src/streamlink/plugins/facebook.py" ]
graphql-python__graphene-752
332214ba9c545b6d899e181a34666540f02848fe
2018-06-01 01:53:33
f039af2810806ab42521426777b3a0d061b02802
diff --git a/graphene/types/inputobjecttype.py b/graphene/types/inputobjecttype.py index dbfccc4..b84fc0f 100644 --- a/graphene/types/inputobjecttype.py +++ b/graphene/types/inputobjecttype.py @@ -50,7 +50,10 @@ class InputObjectType(UnmountedType, BaseType): yank_fields_from_attrs(base.__dict__, _as=InputField) ) - _meta.fields = fields + if _meta.fields: + _meta.fields.update(fields) + else: + _meta.fields = fields if container is None: container = type(cls.__name__, (InputObjectTypeContainer, cls), {}) _meta.container = container
InputObjectType.__init_sublcass_with_meta__ overwrites passed _meta.fields In `InputObjectType.__init_subclass_with_meta__`, the`fields` of the `_meta` arg are overwritten, which can cause complications for subclassing. @classmethod def __init_subclass_with_meta__(cls, container=None, _meta=None, **options): if not _meta: _meta = InputObjectTypeOptions(cls) fields = OrderedDict() for base in reversed(cls.__mro__): fields.update( yank_fields_from_attrs(base.__dict__, _as=InputField) ) _meta.fields = fields # should this be: # if _meta.fields: # _meta.fields.update(fields) # else: # _meta.fields = fields
graphql-python/graphene
diff --git a/graphene/tests/issues/test_720.py b/graphene/tests/issues/test_720.py new file mode 100644 index 0000000..8cd99bd --- /dev/null +++ b/graphene/tests/issues/test_720.py @@ -0,0 +1,44 @@ +# https://github.com/graphql-python/graphene/issues/720 +# InputObjectTypes overwrite the "fields" attribute of the provided +# _meta object, so even if dynamic fields are provided with a standard +# InputObjectTypeOptions, they are ignored. + +import graphene + + +class MyInputClass(graphene.InputObjectType): + + @classmethod + def __init_subclass_with_meta__( + cls, container=None, _meta=None, fields=None, **options): + if _meta is None: + _meta = graphene.types.inputobjecttype.InputObjectTypeOptions(cls) + _meta.fields = fields + super(MyInputClass, cls).__init_subclass_with_meta__( + container=container, _meta=_meta, **options) + + +class MyInput(MyInputClass): + + class Meta: + fields = dict(x=graphene.Field(graphene.Int)) + + +class Query(graphene.ObjectType): + myField = graphene.Field(graphene.String, input=graphene.Argument(MyInput)) + + def resolve_myField(parent, info, input): + return 'ok' + + +def test_issue(): + query_string = ''' + query myQuery { + myField(input: {x: 1}) + } + ''' + + schema = graphene.Schema(query=Query) + result = schema.execute(query_string) + + assert not result.errors
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aniso8601==3.0.2 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 coveralls==3.3.1 docopt==0.6.2 fastdiff==0.3.0 -e git+https://github.com/graphql-python/graphene.git@332214ba9c545b6d899e181a34666540f02848fe#egg=graphene graphql-core==2.3.2 graphql-relay==0.4.5 idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work iso8601==1.1.0 mock==5.2.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work promise==2.3 py @ file:///opt/conda/conda-bld/py_1644396412707/work py-cpuinfo==9.0.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-benchmark==3.4.1 pytest-cov==4.0.0 pytest-mock==3.6.1 pytz==2025.2 requests==2.27.1 Rx==1.6.3 six==1.17.0 snapshottest==0.6.0 termcolor==1.1.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work tomli==1.2.3 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 wasmer==1.1.0 wasmer-compiler-cranelift==1.1.0 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: graphene channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - aniso8601==3.0.2 - charset-normalizer==2.0.12 - coverage==6.2 - coveralls==3.3.1 - docopt==0.6.2 - fastdiff==0.3.0 - graphql-core==2.3.2 - graphql-relay==0.4.5 - idna==3.10 - iso8601==1.1.0 - mock==5.2.0 - promise==2.3 - py-cpuinfo==9.0.0 - pytest-benchmark==3.4.1 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytz==2025.2 - requests==2.27.1 - rx==1.6.3 - six==1.17.0 - snapshottest==0.6.0 - termcolor==1.1.0 - tomli==1.2.3 - urllib3==1.26.20 - wasmer==1.1.0 - wasmer-compiler-cranelift==1.1.0 prefix: /opt/conda/envs/graphene
[ "graphene/tests/issues/test_720.py::test_issue" ]
[]
[]
[]
MIT License
2,612
[ "graphene/types/inputobjecttype.py" ]
[ "graphene/types/inputobjecttype.py" ]
oasis-open__cti-python-stix2-185
d67f2da0ea839db464197f7da0f7991bdd774d1f
2018-06-01 12:52:37
3084c9f51fcd00cf6b0ed76827af90d0e86746d5
diff --git a/stix2/base.py b/stix2/base.py index 2afba16..0ba6f56 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -236,6 +236,21 @@ class _STIXBase(collections.Mapping): optional properties set to the default value defined in the spec. **kwargs: The arguments for a json.dumps() call. + Examples: + >>> import stix2 + >>> identity = stix2.Identity(name='Example Corp.', identity_class='organization') + >>> print(identity.serialize(sort_keys=True)) + {"created": "2018-06-08T19:03:54.066Z", ... "name": "Example Corp.", "type": "identity"} + >>> print(identity.serialize(sort_keys=True, indent=4)) + { + "created": "2018-06-08T19:03:54.066Z", + "id": "identity--d7f3e25a-ba1c-447a-ab71-6434b092b05e", + "identity_class": "organization", + "modified": "2018-06-08T19:03:54.066Z", + "name": "Example Corp.", + "type": "identity" + } + Returns: str: The serialized JSON object. diff --git a/stix2/utils.py b/stix2/utils.py index 619652a..137ea01 100644 --- a/stix2/utils.py +++ b/stix2/utils.py @@ -165,44 +165,87 @@ def _get_dict(data): raise ValueError("Cannot convert '%s' to dictionary." % str(data)) +def _iterate_over_values(dict_values, tuple_to_find): + """Loop recursively over dictionary values""" + from .base import _STIXBase + for pv in dict_values: + if isinstance(pv, list): + for item in pv: + if isinstance(item, _STIXBase): + index = find_property_index( + item, + item.object_properties(), + tuple_to_find + ) + if index is not None: + return index + elif isinstance(item, dict): + for idx, val in enumerate(sorted(item)): + if (tuple_to_find[0] == val and + item.get(val) == tuple_to_find[1]): + return idx + elif isinstance(pv, dict): + if pv.get(tuple_to_find[0]) is not None: + for idx, item in enumerate(sorted(pv.keys())): + if ((item == tuple_to_find[0] and str.isdigit(item)) and + (pv[item] == tuple_to_find[1])): + return int(tuple_to_find[0]) + elif pv[item] == tuple_to_find[1]: + return idx + for item in pv.values(): + if isinstance(item, _STIXBase): + index = find_property_index( + item, + item.object_properties(), + tuple_to_find + ) + if index is not None: + return index + elif isinstance(item, dict): + index = find_property_index( + item, + item.keys(), + tuple_to_find + ) + if index is not None: + return index + + def find_property_index(obj, properties, tuple_to_find): """Recursively find the property in the object model, return the index - according to the _properties OrderedDict. If it's a list look for - individual objects. Returns and integer indicating its location + according to the ``properties`` OrderedDict when working with `stix2` + objects. If it's a list look for individual objects. Returns and integer + indicating its location. + + Notes: + This method is intended to pretty print `stix2` properties for better + visual feedback when working with the library. + + Warnings: + This method may not be able to produce the same output if called + multiple times and makes a best effort attempt to print the properties + according to the STIX technical specification. + + See Also: + py:meth:`stix2.base._STIXBase.serialize` for more information. + """ from .base import _STIXBase try: - if tuple_to_find[1] in obj._inner.values(): - return properties.index(tuple_to_find[0]) + if isinstance(obj, _STIXBase): + if tuple_to_find[1] in obj._inner.values(): + return properties.index(tuple_to_find[0]) + elif isinstance(obj, dict): + for idx, val in enumerate(sorted(obj)): + if (tuple_to_find[0] == val and + obj.get(val) == tuple_to_find[1]): + return idx raise ValueError except ValueError: - for pv in obj._inner.values(): - if isinstance(pv, list): - for item in pv: - if isinstance(item, _STIXBase): - val = find_property_index(item, - item.object_properties(), - tuple_to_find) - if val is not None: - return val - elif isinstance(item, dict): - for idx, val in enumerate(sorted(item)): - if (tuple_to_find[0] == val and - item.get(val) == tuple_to_find[1]): - return idx - elif isinstance(pv, dict): - if pv.get(tuple_to_find[0]) is not None: - try: - return int(tuple_to_find[0]) - except ValueError: - return len(tuple_to_find[0]) - for item in pv.values(): - if isinstance(item, _STIXBase): - val = find_property_index(item, - item.object_properties(), - tuple_to_find) - if val is not None: - return val + if isinstance(obj, _STIXBase): + return _iterate_over_values(obj._inner.values(), tuple_to_find) + elif isinstance(obj, dict): + return _iterate_over_values(obj.values(), tuple_to_find) def new_version(data, **kwargs):
Custom STIX objects with nested dictionary error A custom STIX object with a nested dictionary created using the following example: ``` python #!/usr/bin/env python3.6 from stix2 import CustomObject, properties @CustomObject('x-example', [ ('dictionary', properties.DictionaryProperty()), ]) class Example(object): def __init__(self, **kwargs): pass example = Example(dictionary={'key':{'key_one':'value', 'key_two':'value'}}) print(example) ``` throws the following error when calling the `__str__()` method: ``` bash Traceback (most recent call last): File "./example.py", line 16, in <module> print(example) File "/home/lib64/python3.6/site-packages/stix2/base.py", line 199, in __str__ return self.serialize(pretty=True) File "/home/lib64/python3.6/site-packages/stix2/base.py", line 262, in serialize return json.dumps(self, cls=STIXJSONEncoder, **kwargs) File "/home/lib64/python3.6/site-packages/simplejson/__init__.py", line 399, in dumps **kw).encode(obj) File "home/lib64/python3.6/site-packages/simplejson/encoder.py", line 298, in encode chunks = list(chunks) File "/home/lib64/python3.6/site-packages/simplejson/encoder.py", line 717, in _iterencode for chunk in _iterencode(o, _current_indent_level): File "home/lib64/python3.6/site-packages/simplejson/encoder.py", line 696, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "home/lib64/python3.6/site-packages/simplejson/encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "/home/lib64/python3.6/site-packages/simplejson/encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "/home/lib64/python3.6/site-packages/simplejson/encoder.py", line 602, in _iterencode_dict items.sort(key=_item_sort_key) TypeError: '<' not supported between instances of 'NoneType' and 'NoneType' ``` the work around is to call: ``` python print(example.serialize(pretty=False)) ``` I'm assuming its something do with how `simplejson` is trying to sort the keys and struggles with the nested dictionary. Is there a reason why the `__str__()` method defaults to `pretty=True`?
oasis-open/cti-python-stix2
diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 7f91d79..6fb24d2 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -860,3 +860,33 @@ def test_register_custom_object(): def test_extension_property_location(): assert 'extensions' in stix2.v20.observables.OBJ_MAP_OBSERVABLE['x-new-observable']._properties assert 'extensions' not in stix2.v20.observables.EXT_MAP['domain-name']['x-new-ext']._properties + + [email protected]("data", [ + """{ + "type": "x-example", + "id": "x-example--336d8a9f-91f1-46c5-b142-6441bb9f8b8d", + "created": "2018-06-12T16:20:58.059Z", + "modified": "2018-06-12T16:20:58.059Z", + "dictionary": { + "key": { + "key_a": "value", + "key_b": "value" + } + } +}""", +]) +def test_custom_object_nested_dictionary(data): + @stix2.sdo.CustomObject('x-example', [ + ('dictionary', stix2.properties.DictionaryProperty()), + ]) + class Example(object): + def __init__(self, **kwargs): + pass + + example = Example(id='x-example--336d8a9f-91f1-46c5-b142-6441bb9f8b8d', + created='2018-06-12T16:20:58.059Z', + modified='2018-06-12T16:20:58.059Z', + dictionary={'key': {'key_b': 'value', 'key_a': 'value'}}) + + assert data == str(example) diff --git a/stix2/test/test_utils.py b/stix2/test/test_utils.py index 655cd61..fb63ff7 100644 --- a/stix2/test/test_utils.py +++ b/stix2/test/test_utils.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + import datetime as dt from io import StringIO @@ -10,7 +12,7 @@ amsterdam = pytz.timezone('Europe/Amsterdam') eastern = pytz.timezone('US/Eastern') [email protected]('dttm,timestamp', [ [email protected]('dttm, timestamp', [ (dt.datetime(2017, 1, 1, tzinfo=pytz.utc), '2017-01-01T00:00:00Z'), (amsterdam.localize(dt.datetime(2017, 1, 1)), '2016-12-31T23:00:00Z'), (eastern.localize(dt.datetime(2017, 1, 1, 12, 34, 56)), '2017-01-01T17:34:56Z'), @@ -76,12 +78,12 @@ def test_get_dict_invalid(data): stix2.utils._get_dict(data) [email protected]('stix_id, typ', [ [email protected]('stix_id, type', [ ('malware--d69c8146-ab35-4d50-8382-6fc80e641d43', 'malware'), ('intrusion-set--899ce53f-13a0-479b-a0e4-67d46e241542', 'intrusion-set') ]) -def test_get_type_from_id(stix_id, typ): - assert stix2.utils.get_type_from_id(stix_id) == typ +def test_get_type_from_id(stix_id, type): + assert stix2.utils.get_type_from_id(stix_id) == type def test_deduplicate(stix_objs1): @@ -100,3 +102,110 @@ def test_deduplicate(stix_objs1): assert "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f" in ids assert "2017-01-27T13:49:53.935Z" in mods assert "2017-01-27T13:49:53.936Z" in mods + + [email protected]('object, tuple_to_find, expected_index', [ + (stix2.ObservedData( + id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", + created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", + created="2016-04-06T19:58:16.000Z", + modified="2016-04-06T19:58:16.000Z", + first_observed="2015-12-21T19:00:00Z", + last_observed="2015-12-21T19:00:00Z", + number_observed=50, + objects={ + "0": { + "name": "foo.exe", + "type": "file" + }, + "1": { + "type": "ipv4-addr", + "value": "198.51.100.3" + }, + "2": { + "type": "network-traffic", + "src_ref": "1", + "protocols": [ + "tcp", + "http" + ], + "extensions": { + "http-request-ext": { + "request_method": "get", + "request_value": "/download.html", + "request_version": "http/1.1", + "request_header": { + "Accept-Encoding": "gzip,deflate", + "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.6) Gecko/20040113", + "Host": "www.example.com" + } + } + } + } + }, + ), ('1', {"type": "ipv4-addr", "value": "198.51.100.3"}), 1), + ({ + "type": "x-example", + "id": "x-example--d5413db2-c26c-42e0-b0e0-ec800a310bfb", + "created": "2018-06-11T01:25:22.063Z", + "modified": "2018-06-11T01:25:22.063Z", + "dictionary": { + "key": { + "key_one": "value", + "key_two": "value" + } + } + }, ('key', {'key_one': 'value', 'key_two': 'value'}), 0), + ({ + "type": "language-content", + "id": "language-content--b86bd89f-98bb-4fa9-8cb2-9ad421da981d", + "created": "2017-02-08T21:31:22.007Z", + "modified": "2017-02-08T21:31:22.007Z", + "object_ref": "campaign--12a111f0-b824-4baf-a224-83b80237a094", + "object_modified": "2017-02-08T21:31:22.007Z", + "contents": { + "de": { + "name": "Bank Angriff 1", + "description": "Weitere Informationen über Banküberfall" + }, + "fr": { + "name": "Attaque Bank 1", + "description": "Plus d'informations sur la crise bancaire" + } + } + }, ('fr', {"name": "Attaque Bank 1", "description": "Plus d'informations sur la crise bancaire"}), 1) +]) +def test_find_property_index(object, tuple_to_find, expected_index): + assert stix2.utils.find_property_index( + object, + [], + tuple_to_find + ) == expected_index + + [email protected]('dict_value, tuple_to_find, expected_index', [ + ({ + "contents": { + "de": { + "name": "Bank Angriff 1", + "description": "Weitere Informationen über Banküberfall" + }, + "fr": { + "name": "Attaque Bank 1", + "description": "Plus d'informations sur la crise bancaire" + }, + "es": { + "name": "Ataque al Banco", + "description": "Mas informacion sobre el ataque al banco" + } + } + }, ('es', {"name": "Ataque al Banco", "description": "Mas informacion sobre el ataque al banco"}), 1), # Sorted alphabetically + ({ + 'my_list': [ + {"key_one": 1}, + {"key_two": 2} + ] + }, ('key_one', 1), 0) +]) +def test_iterate_over_values(dict_value, tuple_to_find, expected_index): + assert stix2.utils._iterate_over_values(dict_value.values(), tuple_to_find) == expected_index
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 antlr4-python3-runtime==4.9.3 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 backcall==0.2.0 bleach==4.1.0 bump2version==1.0.1 bumpversion==0.6.0 certifi==2021.5.30 cfgv==3.3.1 charset-normalizer==2.0.12 coverage==6.2 decorator==5.1.1 defusedxml==0.7.1 distlib==0.3.9 docutils==0.18.1 entrypoints==0.4 filelock==3.4.1 identify==2.4.4 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.2.3 iniconfig==1.1.1 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 jsonschema==3.2.0 jupyter-client==7.1.2 jupyter-core==4.9.2 jupyterlab-pygments==0.1.2 MarkupSafe==2.0.1 mistune==0.8.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nbsphinx==0.3.2 nest-asyncio==1.6.0 nodeenv==1.6.0 packaging==21.3 pandocfilters==1.5.1 parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 platformdirs==2.4.0 pluggy==1.0.0 pre-commit==2.17.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 pyzmq==25.1.2 requests==2.27.1 simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==1.5.6 sphinx-prompt==1.5.0 -e git+https://github.com/oasis-open/cti-python-stix2.git@d67f2da0ea839db464197f7da0f7991bdd774d1f#egg=stix2 stix2-patterns==2.0.0 testpath==0.6.0 toml==0.10.2 tomli==1.2.3 tornado==6.1 tox==3.28.0 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.16.2 wcwidth==0.2.13 webencodings==0.5.1 zipp==3.6.0
name: cti-python-stix2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - antlr4-python3-runtime==4.9.3 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - backcall==0.2.0 - bleach==4.1.0 - bump2version==1.0.1 - bumpversion==0.6.0 - cfgv==3.3.1 - charset-normalizer==2.0.12 - coverage==6.2 - decorator==5.1.1 - defusedxml==0.7.1 - distlib==0.3.9 - docutils==0.18.1 - entrypoints==0.4 - filelock==3.4.1 - identify==2.4.4 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.2.3 - iniconfig==1.1.1 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - jsonschema==3.2.0 - jupyter-client==7.1.2 - jupyter-core==4.9.2 - jupyterlab-pygments==0.1.2 - markupsafe==2.0.1 - mistune==0.8.4 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbsphinx==0.3.2 - nest-asyncio==1.6.0 - nodeenv==1.6.0 - packaging==21.3 - pandocfilters==1.5.1 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - platformdirs==2.4.0 - pluggy==1.0.0 - pre-commit==2.17.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - pyzmq==25.1.2 - requests==2.27.1 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==1.5.6 - sphinx-prompt==1.5.0 - stix2-patterns==2.0.0 - testpath==0.6.0 - toml==0.10.2 - tomli==1.2.3 - tornado==6.1 - tox==3.28.0 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.16.2 - wcwidth==0.2.13 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/cti-python-stix2
[ "stix2/test/test_custom.py::test_custom_object_nested_dictionary[{\\n", "stix2/test/test_utils.py::test_find_property_index[object1-tuple_to_find1-0]", "stix2/test/test_utils.py::test_find_property_index[object2-tuple_to_find2-1]", "stix2/test/test_utils.py::test_iterate_over_values[dict_value0-tuple_to_find0-1]", "stix2/test/test_utils.py::test_iterate_over_values[dict_value1-tuple_to_find1-0]" ]
[]
[ "stix2/test/test_custom.py::test_identity_custom_property", "stix2/test/test_custom.py::test_identity_custom_property_invalid", "stix2/test/test_custom.py::test_identity_custom_property_allowed", "stix2/test/test_custom.py::test_parse_identity_custom_property[{\\n", "stix2/test/test_custom.py::test_custom_property_object_in_bundled_object", "stix2/test/test_custom.py::test_custom_properties_object_in_bundled_object", "stix2/test/test_custom.py::test_custom_property_dict_in_bundled_object", "stix2/test/test_custom.py::test_custom_properties_dict_in_bundled_object", "stix2/test/test_custom.py::test_custom_property_in_observed_data", "stix2/test/test_custom.py::test_custom_property_object_in_observable_extension", "stix2/test/test_custom.py::test_custom_property_dict_in_observable_extension", "stix2/test/test_custom.py::test_identity_custom_property_revoke", "stix2/test/test_custom.py::test_identity_custom_property_edit_markings", "stix2/test/test_custom.py::test_custom_marking_no_init_1", "stix2/test/test_custom.py::test_custom_marking_no_init_2", "stix2/test/test_custom.py::test_custom_object_raises_exception", "stix2/test/test_custom.py::test_custom_object_type", "stix2/test/test_custom.py::test_custom_object_no_init_1", "stix2/test/test_custom.py::test_custom_object_no_init_2", "stix2/test/test_custom.py::test_custom_object_invalid_type_name", "stix2/test/test_custom.py::test_parse_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type", "stix2/test/test_custom.py::test_parse_unregistered_custom_object_type_w_allow_custom", "stix2/test/test_custom.py::test_custom_observable_object_1", "stix2/test/test_custom.py::test_custom_observable_object_2", "stix2/test/test_custom.py::test_custom_observable_object_3", "stix2/test/test_custom.py::test_custom_observable_raises_exception", "stix2/test/test_custom.py::test_custom_observable_object_no_init_1", "stix2/test/test_custom.py::test_custom_observable_object_no_init_2", "stix2/test/test_custom.py::test_custom_observable_object_invalid_type_name", "stix2/test/test_custom.py::test_custom_observable_object_invalid_ref_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_refs_list_property", "stix2/test/test_custom.py::test_custom_observable_object_invalid_valid_refs", "stix2/test/test_custom.py::test_custom_no_properties_raises_exception", "stix2/test/test_custom.py::test_custom_wrong_properties_arg_raises_exception", "stix2/test/test_custom.py::test_parse_custom_observable_object", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object", "stix2/test/test_custom.py::test_parse_unregistered_custom_observable_object_with_no_type", "stix2/test/test_custom.py::test_parse_observed_data_with_custom_observable", "stix2/test/test_custom.py::test_parse_invalid_custom_observable_object", "stix2/test/test_custom.py::test_observable_custom_property", "stix2/test/test_custom.py::test_observable_custom_property_invalid", "stix2/test/test_custom.py::test_observable_custom_property_allowed", "stix2/test/test_custom.py::test_observed_data_with_custom_observable_object", "stix2/test/test_custom.py::test_custom_extension_raises_exception", "stix2/test/test_custom.py::test_custom_extension", "stix2/test/test_custom.py::test_custom_extension_wrong_observable_type", "stix2/test/test_custom.py::test_custom_extension_with_list_and_dict_properties_observable_type[{\\n", "stix2/test/test_custom.py::test_custom_extension_invalid_observable", "stix2/test/test_custom.py::test_custom_extension_invalid_type_name", "stix2/test/test_custom.py::test_custom_extension_no_properties", "stix2/test/test_custom.py::test_custom_extension_empty_properties", "stix2/test/test_custom.py::test_custom_extension_dict_properties", "stix2/test/test_custom.py::test_custom_extension_no_init_1", "stix2/test/test_custom.py::test_custom_extension_no_init_2", "stix2/test/test_custom.py::test_parse_observable_with_custom_extension", "stix2/test/test_custom.py::test_parse_observable_with_unregistered_custom_extension", "stix2/test/test_custom.py::test_register_custom_object", "stix2/test/test_custom.py::test_extension_property_location", "stix2/test/test_utils.py::test_timestamp_formatting[dttm0-2017-01-01T00:00:00Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm1-2016-12-31T23:00:00Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm2-2017-01-01T17:34:56Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm3-2017-07-01T04:00:00Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm4-2017-07-01T00:00:00Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm5-2017-07-01T00:00:00.000001Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm6-2017-07-01T00:00:00.000Z]", "stix2/test/test_utils.py::test_timestamp_formatting[dttm7-2017-07-01T00:00:00Z]", "stix2/test/test_utils.py::test_parse_datetime[timestamp0-dttm0]", "stix2/test/test_utils.py::test_parse_datetime[timestamp1-dttm1]", "stix2/test/test_utils.py::test_parse_datetime[2017-01-01T00:00:00Z-dttm2]", "stix2/test/test_utils.py::test_parse_datetime[2017-01-01T02:00:00+2:00-dttm3]", "stix2/test/test_utils.py::test_parse_datetime[2017-01-01T00:00:00-dttm4]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.000001-dttm0-millisecond]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.001-dttm1-millisecond]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.1-dttm2-millisecond]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.45-dttm3-millisecond]", "stix2/test/test_utils.py::test_parse_datetime_precision[2017-01-01T01:02:03.45-dttm4-second]", "stix2/test/test_utils.py::test_parse_datetime_invalid[foobar]", "stix2/test/test_utils.py::test_parse_datetime_invalid[1]", "stix2/test/test_utils.py::test_get_dict[data0]", "stix2/test/test_utils.py::test_get_dict[{\"a\":", "stix2/test/test_utils.py::test_get_dict[data2]", "stix2/test/test_utils.py::test_get_dict[data3]", "stix2/test/test_utils.py::test_get_dict_invalid[1]", "stix2/test/test_utils.py::test_get_dict_invalid[data1]", "stix2/test/test_utils.py::test_get_dict_invalid[data2]", "stix2/test/test_utils.py::test_get_dict_invalid[foobar]", "stix2/test/test_utils.py::test_get_type_from_id[malware--d69c8146-ab35-4d50-8382-6fc80e641d43-malware]", "stix2/test/test_utils.py::test_get_type_from_id[intrusion-set--899ce53f-13a0-479b-a0e4-67d46e241542-intrusion-set]", "stix2/test/test_utils.py::test_deduplicate", "stix2/test/test_utils.py::test_find_property_index[object0-tuple_to_find0-1]" ]
[]
BSD 3-Clause "New" or "Revised" License
2,613
[ "stix2/base.py", "stix2/utils.py" ]
[ "stix2/base.py", "stix2/utils.py" ]
mapbox__mapbox-sdk-py-239
483297046c4db2ea5defe791f755dc5c6c193ed6
2018-06-01 14:54:44
483297046c4db2ea5defe791f755dc5c6c193ed6
diff --git a/CHANGES b/CHANGES index 23dc89f..f6884e2 100644 --- a/CHANGES +++ b/CHANGES @@ -1,8 +1,9 @@ Changes ======= -Next ----- +0.16.1 +------ +- Python 2/3 bugfixes (#239) - Add support for Maps v4 (#228). 0.16.0 (2018-05-08) diff --git a/mapbox/__init__.py b/mapbox/__init__.py index d07d0ef..aa93a1d 100644 --- a/mapbox/__init__.py +++ b/mapbox/__init__.py @@ -1,5 +1,5 @@ # mapbox -__version__ = "0.16.0" +__version__ = "0.16.1" from .services.datasets import Datasets from .services.directions import Directions diff --git a/mapbox/compat.py b/mapbox/compat.py new file mode 100644 index 0000000..c01ed1b --- /dev/null +++ b/mapbox/compat.py @@ -0,0 +1,6 @@ +import sys + +if sys.version_info[0] >= 3: # pragma: no cover + string_type = str +else: # pragma: no cover + string_type = basestring diff --git a/mapbox/encoding.py b/mapbox/encoding.py index a6e6f96..40530d0 100644 --- a/mapbox/encoding.py +++ b/mapbox/encoding.py @@ -61,7 +61,9 @@ def encode_waypoints(features, min_limit=None, max_limit=None, precision=6): return a string encoded in waypoint-style used by certain mapbox APIs ("lon,lat" pairs separated by ";") """ - coords = ['{lon},{lat}'.format(lon=round(lon, precision), lat=round(lat, precision)) + coords = ['{lon},{lat}'.format( + lon=float(round(lon, precision)), + lat=float(round(lat, precision))) for lon, lat in read_points(features)] if min_limit is not None and len(coords) < min_limit: @@ -88,7 +90,7 @@ def encode_coordinates_json(features): """Given an iterable of features return a JSON string to be used as the request body for the distance API: a JSON object, with a key coordinates, - which has an array of [ Longitude, Latitidue ] pairs + which has an array of [ Longitude, Lattitude ] pairs """ coords = { 'coordinates': list(read_points(features))} diff --git a/mapbox/services/directions.py b/mapbox/services/directions.py index 8df3400..30dd34b 100644 --- a/mapbox/services/directions.py +++ b/mapbox/services/directions.py @@ -6,6 +6,7 @@ from uritemplate import URITemplate from mapbox.encoding import encode_waypoints as encode_coordinates from mapbox.services.base import Service +from mapbox.compat import string_type from mapbox import errors @@ -118,7 +119,7 @@ class Directions(Service): if radius is None: return None - if isinstance(radius, str): + if isinstance(radius, string_type): if radius != 'unlimited': raise errors.InvalidParameterError( '{0} is not a valid radius'.format(radius))
direction validate_snapping behavior differs by Python version Another fun Python 2/3 issue The `_validate_snapping` method returns (bearings, radii) tuples. In Python 3, we get the correct behavior ```python >>> from mapbox.services import directions >>> d = directions.Directions() >>> d._validate_snapping([(1, 1, 1), u'unlimited'], [None, None]) ([(1, 1), None], [1, 'unlimited']) ``` In Python 2, we get an Expection ```python >>> from mapbox.services import directions >>> d = directions.Directions() >>> d._validate_snapping([(1, 1, 1), u'unlimited'], [None, None]) ------------------------------------------------------------------------ InvalidParameterError Traceback (most recent call last) <ipython-input-3-1dc0bc40d399> in <module>() ----> 1 d._validate_snapping([(1, 1, 1), u'unlimited'], [None, None]) /Users/mperry/env/sdk27/lib/python2.7/site-packages/mapbox/services/directions.pyc in _validate_snapping(self, snaps, features) 93 except ValueError: 94 raise errors.InvalidParameterError( ---> 95 'waypoint snapping should contain 3 elements: ' 96 '(bearing, angle, range)') 97 self._validate_radius(radius) InvalidParameterError: waypoint snapping should contain 3 elements: (bearing, angle, range) ```
mapbox/mapbox-sdk-py
diff --git a/tests/test_directions.py b/tests/test_directions.py index d9c4fe4..4c5759b 100644 --- a/tests/test_directions.py +++ b/tests/test_directions.py @@ -239,10 +239,17 @@ def test_validate_radius_none(): assert service._validate_radius(None) is None +def test_validate_radius_unlimited(): + service = mapbox.Directions(access_token='pk.test') + assert service._validate_radius('unlimited') == 'unlimited' + + def test_validate_radius_invalid(): service = mapbox.Directions(access_token='pk.test') with pytest.raises(mapbox.errors.InvalidParameterError) as e: service._validate_radius(-1) + with pytest.raises(mapbox.errors.InvalidParameterError) as e: + service._validate_radius('nothing') def test_invalid_bearing_domain(): @@ -256,3 +263,11 @@ def test_bearings_without_radius(): with pytest.raises(TypeError): mapbox.Directions(access_token='pk.test').directions( waypoint_snapping=[(270, 45), (270, 45)]) + + +def test_validate_snapping(): + service = mapbox.Directions(access_token='pk.test') + snaps = service._validate_snapping( + [(1, 1, 1), u'unlimited'], [None, None]) + + assert snaps == ([(1, 1), None], [1, 'unlimited']) diff --git a/tests/test_encoding.py b/tests/test_encoding.py index 72b5152..8fb4b5e 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -128,3 +128,16 @@ def test_encode_coordinates_json(): assert expected == json.loads(encode_coordinates_json(gj_point_features)) assert expected == json.loads(encode_coordinates_json(gj_multipoint_features)) assert expected == json.loads(encode_coordinates_json(gj_line_features)) + + +def test_encode_waypoints_rounding(): + expected = "1.0,0.0" + int_coord_features = [{ + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [1, 0] + }, + "properties": {}}] + + assert expected == encode_waypoints(int_coord_features)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 4 }
0.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work boto3==1.23.10 botocore==1.26.10 CacheControl==0.12.14 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 coveralls==3.3.1 distlib==0.3.9 docopt==0.6.2 filelock==3.4.1 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work iso3166==2.1.1 jmespath==0.10.0 -e git+https://github.com/mapbox/mapbox-sdk-py.git@483297046c4db2ea5defe791f755dc5c6c193ed6#egg=mapbox more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work msgpack==1.0.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work platformdirs==2.4.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work polyline==1.4.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 requests==2.27.1 responses==0.17.0 s3transfer==0.5.2 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work tomli==1.2.3 tox==3.28.0 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work uritemplate==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: mapbox-sdk-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - boto3==1.23.10 - botocore==1.26.10 - cachecontrol==0.12.14 - charset-normalizer==2.0.12 - coverage==6.2 - coveralls==3.3.1 - distlib==0.3.9 - docopt==0.6.2 - filelock==3.4.1 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iso3166==2.1.1 - jmespath==0.10.0 - msgpack==1.0.5 - platformdirs==2.4.0 - polyline==1.4.0 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - requests==2.27.1 - responses==0.17.0 - s3transfer==0.5.2 - six==1.17.0 - tomli==1.2.3 - tox==3.28.0 - uritemplate==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 prefix: /opt/conda/envs/mapbox-sdk-py
[ "tests/test_encoding.py::test_encode_waypoints_rounding" ]
[]
[ "tests/test_directions.py::test_class_attrs", "tests/test_directions.py::test_directions[None]", "tests/test_directions.py::test_directions[cache1]", "tests/test_directions.py::test_directions_geojson", "tests/test_directions.py::test_directions_geojson_as_geojson", "tests/test_directions.py::test_invalid_profile", "tests/test_directions.py::test_direction_params", "tests/test_directions.py::test_direction_backwards_compat", "tests/test_directions.py::test_direction_bearings", "tests/test_directions.py::test_direction_bearings_none", "tests/test_directions.py::test_invalid_geom_encoding", "tests/test_directions.py::test_v4_profile_aliases", "tests/test_directions.py::test_invalid_annotations", "tests/test_directions.py::test_invalid_geom_overview", "tests/test_directions.py::test_invalid_radiuses", "tests/test_directions.py::test_invalid_number_of_bearings", "tests/test_directions.py::test_invalid_bearing_tuple", "tests/test_directions.py::test_snapping_bearing_none", "tests/test_directions.py::test_snapping_radii_none", "tests/test_directions.py::test_validate_radius_none", "tests/test_directions.py::test_validate_radius_unlimited", "tests/test_directions.py::test_validate_radius_invalid", "tests/test_directions.py::test_invalid_bearing_domain", "tests/test_directions.py::test_bearings_without_radius", "tests/test_directions.py::test_validate_snapping", "tests/test_encoding.py::test_read_geojson_features", "tests/test_encoding.py::test_geo_interface", "tests/test_encoding.py::test_encode_waypoints", "tests/test_encoding.py::test_encode_limits", "tests/test_encoding.py::test_unsupported_geometry", "tests/test_encoding.py::test_unknown_object", "tests/test_encoding.py::test_encode_polyline", "tests/test_encoding.py::test_encode_coordinates_json" ]
[]
MIT License
2,614
[ "mapbox/__init__.py", "mapbox/services/directions.py", "mapbox/encoding.py", "CHANGES", "mapbox/compat.py" ]
[ "mapbox/__init__.py", "mapbox/services/directions.py", "mapbox/encoding.py", "CHANGES", "mapbox/compat.py" ]
algoo__hapic-63
d72385ed5e1321d2216f42f6d6267e30f5dab28a
2018-06-01 15:10:34
d72385ed5e1321d2216f42f6d6267e30f5dab28a
diff --git a/additionals_fields.md b/additionals_fields.md new file mode 100644 index 0000000..5a77965 --- /dev/null +++ b/additionals_fields.md @@ -0,0 +1,44 @@ +## Addtionals fields supported + +Using marshmallow schema, you have the possibility to add extra information in +field in order to add them into auto-generated apispec documentation. + +``` + class MySchema(marshmallow.Schema): + category = marshmallow.fields.String( + required=True, + description='a description', + example='00010', + format='binary', + enum=['01000', '11111'], + maxLength=5, + minLength=5, + ) +``` + +Not all field are fully supported now by Hapic. + +## Supported Additional Fields in Hapic for query/path/body : + +General types: + +- format +- description +- enum +- example (example is converted at the end of description for query/path) + +Number type: + +- maximum +- exclusiveMaximum +- minimum +- exclusiveMinimum +- multipleOf + +String type: + +- maxLength +- minLength + +Theses field are related to OpenApiv2 spec, see this : +https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#definitionsObject diff --git a/hapic/doc.py b/hapic/doc.py index 48aaad9..1c0759a 100644 --- a/hapic/doc.py +++ b/hapic/doc.py @@ -15,6 +15,48 @@ from hapic.decorator import DecoratedController from hapic.description import ControllerDescription +FIELDS_PARAMS_GENERIC_ACCEPTED = [ + 'type', + 'format', + 'required', + 'description', + 'enum', +] + +FIELDS_TYPE_ARRAY = [ + 'array', +] +FIELDS_PARAMS_ARRAY_ACCEPTED = [ + 'items', + 'collectionFormat', + 'pattern', + 'maxitems', + 'minitems', + 'uniqueitems', +] + +FIELDS_TYPE_STRING = [ + 'string', +] +FIELDS_PARAMS_STRING_ACCEPTED = [ + 'maxLength', + 'minLength', + 'pattern', +] + +FIELDS_TYPE_NUMERIC = [ + 'number', + 'integer', +] +FIELDS_PARAMS_NUMERIC_ACCEPTED = [ + 'maximum', + 'exclusiveMaximum', + 'minimum', + 'exclusiveMinimum', + 'multipleOf', +] + + def generate_schema_ref(spec:APISpec, schema: marshmallow.Schema) -> str: schema_class = spec.schema_class_resolver( spec, @@ -33,6 +75,63 @@ def generate_schema_ref(spec:APISpec, schema: marshmallow.Schema) -> str: return ref +def field_accepted_param(type: str, param_name:str) -> bool: + return ( + param_name in FIELDS_PARAMS_GENERIC_ACCEPTED + or (type in FIELDS_TYPE_STRING + and param_name in FIELDS_PARAMS_STRING_ACCEPTED) + or (type in FIELDS_TYPE_ARRAY + and param_name in FIELDS_PARAMS_ARRAY_ACCEPTED) + or (type in FIELDS_TYPE_NUMERIC + and param_name in FIELDS_PARAMS_NUMERIC_ACCEPTED) + ) + + +def generate_fields_description( + schema, + in_: str, + name: str, + required: bool, + type: str=None, +) -> dict: + """ + Generate field OpenApiDescription for + both query and path params + :param schema: field schema + :param in_: in field + :param name: field name + :param required: required field + :param type: type field + :return: File description for OpenApi + """ + description = {} + # INFO - G.M - 01-06-2018 - get field + # type to know which params are accepted + if not type and 'type' in schema: + type = schema['type'] + assert type + + for param_name, value in schema.items(): + if field_accepted_param(type, param_name): + description[param_name] = value + description['type'] = type + description['in'] = in_ + description['name'] = name + description['required'] = required + + + # INFO - G.M - 01-06-2018 - example is not allowed in query/path params, + # in OpenApi2, remove it and set it as string in field description. + if 'example' in schema: + if 'description' not in description: + description['description'] = "" + description['description'] = '{description}\n\n*example value: {example}*'.format( # nopep8 + description=description['description'], + example=schema['example'] + ) + return description + + def bottle_generate_operations( spec, route: RouteRepresentation, @@ -90,12 +189,14 @@ def bottle_generate_operations( # TODO: look schema2parameters ? jsonschema = schema2jsonschema(schema_class, spec=spec) for name, schema in jsonschema.get('properties', {}).items(): - method_operations.setdefault('parameters', []).append({ - 'in': 'path', - 'name': name, - 'required': name in jsonschema.get('required', []), - 'type': schema['type'] - }) + method_operations.setdefault('parameters', []).append( + generate_fields_description( + schema=schema, + in_='path', + name=name, + required=name in jsonschema.get('required', []), + ) + ) if description.input_query: schema_class = spec.schema_class_resolver( @@ -104,16 +205,20 @@ def bottle_generate_operations( ) jsonschema = schema2jsonschema(schema_class, spec=spec) for name, schema in jsonschema.get('properties', {}).items(): - method_operations.setdefault('parameters', []).append({ - 'in': 'query', - 'name': name, - 'required': name in jsonschema.get('required', []), - 'type': schema['type'] - }) + method_operations.setdefault('parameters', []).append( + generate_fields_description( + schema=schema, + in_='query', + name=name, + required=name in jsonschema.get('required', []), + ) + ) if description.input_files: method_operations.setdefault('consumes', []).append('multipart/form-data') for field_name, field in description.input_files.wrapper.processor.schema.fields.items(): + # TODO - G.M - 01-06-2018 - Check if other fields can be used + # see generate_fields_description method_operations.setdefault('parameters', []).append({ 'in': 'formData', 'name': field_name, diff --git a/setup.py b/setup.py index 99c4f13..0819989 100644 --- a/setup.py +++ b/setup.py @@ -46,7 +46,6 @@ setup( # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version=version, - description='HTTP api input/output manager', # long_description=long_description, long_description='',
Support for description/example/etc... from schema in query/path parameter Hapic should create query/path parameter with description and example when available.
algoo/hapic
diff --git a/tests/func/fake_api/common.py b/tests/func/fake_api/common.py index 1417c2b..b1c4024 100644 --- a/tests/func/fake_api/common.py +++ b/tests/func/fake_api/common.py @@ -81,7 +81,9 @@ SWAGGER_DOC_API = { ('/users/{id}', { 'delete': { 'description': 'delete user', - 'parameters': [{'in': 'path', + 'parameters': [{'format': 'int32', + 'minimum': 1, + 'in': 'path', 'name': 'id', 'required': True, 'type': 'integer'}], @@ -90,7 +92,9 @@ SWAGGER_DOC_API = { 'schema': {'$ref': '#/definitions/NoContentSchema'}}}}, 'get': { 'description': 'Obtain one user', - 'parameters': [{'in': 'path', + 'parameters': [{'format': 'int32', + 'in': 'path', + 'minimum': 1, 'name': 'id', 'required': True, 'type': 'integer'}], diff --git a/tests/func/test_doc.py b/tests/func/test_doc.py index dfbc9b9..2680fe4 100644 --- a/tests/func/test_doc.py +++ b/tests/func/test_doc.py @@ -372,3 +372,217 @@ class TestDocGeneration(Base): 'items': {'$ref': '#/definitions/{}'.format(schema_name)}, 'type': 'array' } + + def test_func_schema_in_doc__ok__additionals_fields__query__string(self): + hapic = Hapic() + # TODO BS 20171113: Make this test non-bottle + app = bottle.Bottle() + hapic.set_context(MyContext(app=app)) + + class MySchema(marshmallow.Schema): + category = marshmallow.fields.String( + required=True, + description='a description', + example='00010', + format='binary', + enum=['01000', '11111'], + maxLength=5, + minLength=5, + # Theses none string specific parameters should disappear + # in query/path + maximum=400, + # exclusiveMaximun=False, + # minimum=0, + # exclusiveMinimum=True, + # multipleOf=1, + ) + + @hapic.with_api_doc() + @hapic.input_query(MySchema()) + def my_controller(): + return + + app.route('/paper', method='POST', callback=my_controller) + doc = hapic.generate_doc() + assert doc.get('paths').get('/paper').get('post').get('parameters')[0] + field = doc.get('paths').get('/paper').get('post').get('parameters')[0] + assert field['description'] == 'a description\n\n*example value: 00010*' + # INFO - G.M - 01-06-2018 - Field example not allowed here, + # added in description instead + assert 'example' not in field + assert field['format'] == 'binary' + assert field['in'] == 'query' + assert field['type'] == 'string' + assert field['maxLength'] == 5 + assert field['minLength'] == 5 + assert field['required'] == True + assert field['enum'] == ['01000', '11111'] + assert 'maximum' not in field + + def test_func_schema_in_doc__ok__additionals_fields__path__string(self): + hapic = Hapic() + # TODO BS 20171113: Make this test non-bottle + app = bottle.Bottle() + hapic.set_context(MyContext(app=app)) + + class MySchema(marshmallow.Schema): + category = marshmallow.fields.String( + required=True, + description='a description', + example='00010', + format='binary', + enum=['01000', '11111'], + maxLength=5, + minLength=5, + # Theses none string specific parameters should disappear + # in query/path + maximum=400, + # exclusiveMaximun=False, + # minimum=0, + # exclusiveMinimum=True, + # multipleOf=1, + ) + + @hapic.with_api_doc() + @hapic.input_path(MySchema()) + def my_controller(): + return + + app.route('/paper', method='POST', callback=my_controller) + doc = hapic.generate_doc() + assert doc.get('paths').get('/paper').get('post').get('parameters')[0] + field = doc.get('paths').get('/paper').get('post').get('parameters')[0] + assert field['description'] == 'a description\n\n*example value: 00010*' + # INFO - G.M - 01-06-2018 - Field example not allowed here, + # added in description instead + assert 'example' not in field + assert field['format'] == 'binary' + assert field['in'] == 'path' + assert field['type'] == 'string' + assert field['maxLength'] == 5 + assert field['minLength'] == 5 + assert field['required'] == True + assert field['enum'] == ['01000', '11111'] + assert 'maximum' not in field + + def test_func_schema_in_doc__ok__additionals_fields__path__number(self): + hapic = Hapic() + # TODO BS 20171113: Make this test non-bottle + app = bottle.Bottle() + hapic.set_context(MyContext(app=app)) + + class MySchema(marshmallow.Schema): + category = marshmallow.fields.Integer( + required=True, + description='a number', + example='12', + format='int64', + enum=[4, 6], + # Theses none string specific parameters should disappear + # in query/path + maximum=14, + exclusiveMaximun=False, + minimum=0, + exclusiveMinimum=True, + multipleOf=2, + ) + + @hapic.with_api_doc() + @hapic.input_path(MySchema()) + def my_controller(): + return + + app.route('/paper', method='POST', callback=my_controller) + doc = hapic.generate_doc() + assert doc.get('paths').get('/paper').get('post').get('parameters')[0] + field = doc.get('paths').get('/paper').get('post').get('parameters')[0] + assert field['description'] == 'a number\n\n*example value: 12*' + # INFO - G.M - 01-06-2018 - Field example not allowed here, + # added in description instead + assert 'example' not in field + assert field['format'] == 'int64' + assert field['in'] == 'path' + assert field['type'] == 'integer' + assert field['maximum'] == 14 + assert field['minimum'] == 0 + assert field['exclusiveMinimum'] == True + assert field['required'] == True + assert field['enum'] == [4, 6] + assert field['multipleOf'] == 2 + + def test_func_schema_in_doc__ok__additionals_fields__body__number(self): + hapic = Hapic() + # TODO BS 20171113: Make this test non-bottle + app = bottle.Bottle() + hapic.set_context(MyContext(app=app)) + + class MySchema(marshmallow.Schema): + category = marshmallow.fields.Integer( + required=True, + description='a number', + example='12', + format='int64', + enum=[4, 6], + # Theses none string specific parameters should disappear + # in query/path + maximum=14, + exclusiveMaximun=False, + minimum=0, + exclusiveMinimum=True, + multipleOf=2, + ) + + @hapic.with_api_doc() + @hapic.input_body(MySchema()) + def my_controller(): + return + + app.route('/paper', method='POST', callback=my_controller) + doc = hapic.generate_doc() + + schema_field = doc.get('definitions', {}).get('MySchema', {}).get('properties', {}).get('category', {}) # nopep8 + assert schema_field + assert schema_field['description'] == 'a number' + assert schema_field['example'] == '12' + assert schema_field['format'] == 'int64' + assert schema_field['type'] == 'integer' + assert schema_field['maximum'] == 14 + assert schema_field['minimum'] == 0 + assert schema_field['exclusiveMinimum'] == True + assert schema_field['enum'] == [4, 6] + assert schema_field['multipleOf'] == 2 + + def test_func_schema_in_doc__ok__additionals_fields__body__string(self): + hapic = Hapic() + # TODO BS 20171113: Make this test non-bottle + app = bottle.Bottle() + hapic.set_context(MyContext(app=app)) + + class MySchema(marshmallow.Schema): + category = marshmallow.fields.String( + required=True, + description='a description', + example='00010', + format='binary', + enum=['01000', '11111'], + maxLength=5, + minLength=5, + ) + + @hapic.with_api_doc() + @hapic.input_body(MySchema()) + def my_controller(): + return + + app.route('/paper', method='POST', callback=my_controller) + doc = hapic.generate_doc() + + schema_field = doc.get('definitions', {}).get('MySchema', {}).get('properties', {}).get('category', {}) # nopep8 + assert schema_field + assert schema_field['description'] == 'a description' + assert schema_field['example'] == '00010' + assert schema_field['format'] == 'binary' + assert schema_field['type'] == 'string' + assert schema_field['maxLength'] == 5 + assert schema_field['minLength'] == 5 + assert schema_field['enum'] == ['01000', '11111']
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
0.38
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov" ], "pre_install": [], "python": "3.6", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.13.2 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 dataclasses==0.8 Flask==2.0.3 -e git+https://github.com/algoo/hapic.git@d72385ed5e1321d2216f42f6d6267e30f5dab28a#egg=hapic hapic-apispec==0.37.0 hupper==1.10.3 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 MarkupSafe==2.0.1 marshmallow==2.21.0 multidict==5.2.0 packaging==21.3 PasteDeploy==2.1.1 plaster==1.0 plaster-pastedeploy==0.7 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pyramid==2.0.2 pytest==7.0.1 pytest-cov==4.0.0 PyYAML==6.0.1 requests==2.27.1 soupsieve==2.3.2.post1 tomli==1.2.3 translationstring==1.4 typing_extensions==4.1.1 urllib3==1.26.20 venusian==3.0.0 waitress==2.0.0 WebOb==1.8.9 WebTest==3.0.0 Werkzeug==2.0.3 zipp==3.6.0 zope.deprecation==4.4.0 zope.interface==5.5.2
name: hapic channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.13.2 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - dataclasses==0.8 - flask==2.0.3 - hapic-apispec==0.37.0 - hupper==1.10.3 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - markupsafe==2.0.1 - marshmallow==2.21.0 - multidict==5.2.0 - packaging==21.3 - pastedeploy==2.1.1 - plaster==1.0 - plaster-pastedeploy==0.7 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pyramid==2.0.2 - pytest==7.0.1 - pytest-cov==4.0.0 - pyyaml==6.0.1 - requests==2.27.1 - soupsieve==2.3.2.post1 - tomli==1.2.3 - translationstring==1.4 - typing-extensions==4.1.1 - urllib3==1.26.20 - venusian==3.0.0 - waitress==2.0.0 - webob==1.8.9 - webtest==3.0.0 - werkzeug==2.0.3 - zipp==3.6.0 - zope-deprecation==4.4.0 - zope-interface==5.5.2 prefix: /opt/conda/envs/hapic
[ "tests/func/test_doc.py::TestDocGeneration::test_func_schema_in_doc__ok__additionals_fields__query__string", "tests/func/test_doc.py::TestDocGeneration::test_func_schema_in_doc__ok__additionals_fields__path__string", "tests/func/test_doc.py::TestDocGeneration::test_func_schema_in_doc__ok__additionals_fields__path__number" ]
[]
[ "tests/func/test_doc.py::TestDocGeneration::test_func__input_files_doc__ok__one_file", "tests/func/test_doc.py::TestDocGeneration::test_func__input_files_doc__ok__two_file", "tests/func/test_doc.py::TestDocGeneration::test_func__output_file_doc__ok__nominal_case", "tests/func/test_doc.py::TestDocGeneration::test_func__input_files_doc__ok__one_file_and_text", "tests/func/test_doc.py::TestDocGeneration::test_func__docstring__ok__simple_case", "tests/func/test_doc.py::TestDocGeneration::test_func__tags__ok__nominal_case", "tests/func/test_doc.py::TestDocGeneration::test_func__errors__nominal_case", "tests/func/test_doc.py::TestDocGeneration::test_func__enum__nominal_case", "tests/func/test_doc.py::TestDocGeneration::test_func__schema_in_doc__ok__nominal_case", "tests/func/test_doc.py::TestDocGeneration::test_func__schema_in_doc__ok__many_case", "tests/func/test_doc.py::TestDocGeneration::test_func__schema_in_doc__ok__exclude_case", "tests/func/test_doc.py::TestDocGeneration::test_func__schema_in_doc__ok__many_and_exclude_case", "tests/func/test_doc.py::TestDocGeneration::test_func_schema_in_doc__ok__additionals_fields__body__number", "tests/func/test_doc.py::TestDocGeneration::test_func_schema_in_doc__ok__additionals_fields__body__string" ]
[]
MIT License
2,615
[ "setup.py", "hapic/doc.py", "additionals_fields.md" ]
[ "setup.py", "hapic/doc.py", "additionals_fields.md" ]
EdinburghGenomics__EGCG-Core-82
4b8ccd933f689a9d0c5a0c98e59ddbfa697124aa
2018-06-01 15:48:26
4dba72a40487a2341a4be255af8366644300f53b
diff --git a/.travis.yml b/.travis.yml index 68e56d7..0292bb1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,7 @@ install: - "pip install -r requirements.txt" - "pip install python-coveralls pytest-cov" - "python setup.py install" -script: py.test tests/ --doctest-modules -v --cov egcg_core --cov-report term-missing +script: py.test tests/ --cov egcg_core --cov-report term-missing after_success: - coveralls # branches: diff --git a/CHANGELOG.md b/CHANGELOG.md index a6601ec..9adf174 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,10 @@ Changelog for EGCG-Core 0.9 (unreleased) ---------------- -- Nothing changed yet. +- Breaking change: removed `clarity.get_expected_yield_for_sample` +- Catching notification failures +- Added retries to `rest_communication` +- Added log warnings to `util.find_file` 0.8.2 (2018-05-28) diff --git a/egcg_core/clarity.py b/egcg_core/clarity.py index c3e9b86..0068e9d 100644 --- a/egcg_core/clarity.py +++ b/egcg_core/clarity.py @@ -206,19 +206,6 @@ def get_sample_genotype(sample_name, output_file_name): app_logger.warning('Cannot download genotype results for %s', sample_name) -def get_expected_yield_for_sample(sample_name): - """ - Query the LIMS and return the number of bases expected for a sample - :param sample_name: the sample name - :return: number of bases - """ - sample = get_sample(sample_name) - if sample: - nb_gb = sample.udf.get('Yield for Quoted Coverage (Gb)') - if nb_gb: - return nb_gb * 1000000000 - - def get_plate_id_and_well(sample_name): sample = get_sample(sample_name) if sample: diff --git a/egcg_core/ncbi.py b/egcg_core/ncbi.py index b6c26b0..840b8e5 100644 --- a/egcg_core/ncbi.py +++ b/egcg_core/ncbi.py @@ -36,6 +36,9 @@ def get_species_name(query_species): q, taxid, scientific_name, common_name = local_query else: taxid, scientific_name, common_name = _fetch_from_eutils(query_species) + if taxid is None: + return None + _cache_species(query_species, taxid, scientific_name, common_name) return scientific_name diff --git a/egcg_core/notifications/__init__.py b/egcg_core/notifications/__init__.py index 17282da..10b1ae4 100644 --- a/egcg_core/notifications/__init__.py +++ b/egcg_core/notifications/__init__.py @@ -1,5 +1,8 @@ +import sys +import traceback from egcg_core.app_logging import AppLogger from egcg_core.config import cfg +from egcg_core.exceptions import EGCGError from .asana import AsanaNotification from .email import EmailNotification, EmailSender, send_email, send_html_email, send_plain_text_email from .log import LogNotification @@ -16,21 +19,32 @@ class NotificationCentre(AppLogger): self.name = name self.subscribers = {} - for s in cfg.get('notifications', {}): - if s in self.ntf_aliases: - self.debug('Configuring notification for: ' + s) - config = cfg['notifications'][s] - self.subscribers[s] = self.ntf_aliases[s](name=self.name, **config) + for k, v in cfg.get('notifications', {}).items(): + if k in self.ntf_aliases: + self.debug('Configuring notification for: ' + k) + self.subscribers[k] = self.ntf_aliases[k](name=self.name, **v) else: - self.warning("Bad notification config '%s' - this will be ignored", s) + self.warning("Bad notification config '%s' - this will be ignored", k) def notify(self, msg, subs): + exceptions = [] for s in subs: if s in self.subscribers: - self.subscribers[s].notify(msg) + try: + self.subscribers[s].notify(msg) + except Exception as e: + etype, value, tb = sys.exc_info() + stacktrace = ''.join(traceback.format_exception(etype, value, tb)) + self.critical(stacktrace) + exceptions.append(e) else: self.debug('Tried to notify by %s, but no configuration present', s) + if exceptions: + raise EGCGError( + 'Encountered the following errors during notification: %s' % ', '.join( + '%s: %s' % (e.__class__.__name__, str(e)) for e in exceptions) + ) + def notify_all(self, msg): - for s in self.subscribers.values(): - s.notify(msg) + self.notify(msg, self.subscribers.keys()) diff --git a/egcg_core/rest_communication.py b/egcg_core/rest_communication.py index 61dcdbf..0a9e0cc 100644 --- a/egcg_core/rest_communication.py +++ b/egcg_core/rest_communication.py @@ -1,7 +1,10 @@ import json import mimetypes -import requests from urllib.parse import urljoin +import requests +from multiprocessing import Lock +from requests.packages.urllib3.util.retry import Retry +from requests.adapters import HTTPAdapter from egcg_core.config import cfg from egcg_core.app_logging import AppLogger from egcg_core.exceptions import RestCommunicationError @@ -11,9 +14,31 @@ from egcg_core.util import check_if_nested class Communicator(AppLogger): successful_statuses = (200, 201, 202, 204) - def __init__(self, auth=None, baseurl=None): + def __init__(self, auth=None, baseurl=None, retries=5): self._baseurl = baseurl self._auth = auth + self.retries = retries + self._session = None + self.lock = Lock() + + def begin_session(self): + s = requests.Session() + adapter = HTTPAdapter(max_retries=Retry(self.retries, self.retries, self.retries, backoff_factor=0.2)) + s.mount('http://', adapter) + s.mount('https://', adapter) + + if isinstance(self.auth, tuple): + s.auth = self.auth + elif isinstance(self.auth, str): + s.headers.update({'Authorization': 'Token %s' % self.auth}) + + return s + + @property + def session(self): + if self._session is None: + self._session = self.begin_session() + return self._session @staticmethod def serialise(queries): @@ -103,11 +128,6 @@ class Communicator(AppLogger): return query def _req(self, method, url, quiet=False, **kwargs): - if isinstance(self.auth, tuple): - kwargs['auth'] = self.auth - elif isinstance(self.auth, str): - kwargs['headers'] = dict(kwargs.get('headers', {}), Authorization='Token %s' % self.auth) - # can't upload json and files at the same time, so we need to move the json parameter to data # data can't upload complex structures that would require json encoding. # this means we can't upload data with nested lists/dicts at the same time as files @@ -116,22 +136,25 @@ class Communicator(AppLogger): raise RestCommunicationError('Cannot upload files and nested json in one query') kwargs['data'] = kwargs.pop('json') - r = requests.request(method, url, **kwargs) + self.lock.acquire() + r = self.session.request(method, url, **kwargs) - kwargs.pop('auth', None) - kwargs.pop('headers', None) kwargs.pop('files', None) # e.g: 'POST <url> ({"some": "args"}) -> {"some": "content"}. Status code 201. Reason: CREATED report = '%s %s (%s) -> %s. Status code %s. Reason: %s' % ( r.request.method, r.request.path_url, kwargs, r.content.decode('utf-8'), r.status_code, r.reason ) + if r.status_code in self.successful_statuses: if not quiet: self.debug(report) + + self.lock.release() + return r else: self.error(report) + self.lock.release() raise RestCommunicationError('Encountered a %s status code: %s' % (r.status_code, r.reason)) - return r def get_content(self, endpoint, paginate=True, quiet=False, **query_args): if paginate: diff --git a/egcg_core/util.py b/egcg_core/util.py index 6d8b08c..f8e9d1a 100644 --- a/egcg_core/util.py +++ b/egcg_core/util.py @@ -26,7 +26,10 @@ def find_files(*path_parts): def find_file(*path_parts): files = find_files(*path_parts) - if files: + nfiles = len(files) + if nfiles > 1: + app_logger.warning('Searched pattern %s for one file, but got %s', path_parts, nfiles) + elif nfiles == 1: return files[0] @@ -102,20 +105,20 @@ def move_dir(src_dir, dest_dir): return 0 -def query_dict(data, query_string): +def query_dict(data, query_string, ret_default=None): """ Drill down into a dict using dot notation, e.g. query_dict({'this': {'that': 'other'}}, 'this.that'}). :param dict data: :param str query_string: + :param ret_default: """ _data = data.copy() for q in query_string.split('.'): d = _data.get(q) - if d is None: - return None - - else: + if d is not None: _data = d + else: + return ret_default return _data
Deprecate get_expected_yield_for_sample function `get_expected_yield_for_sample` in `clarity` returns the Expected yield Q30. This function should be deprecated and a more explicitly named one should be used. It is mainly used in Analysis-Driver (https://github.com/EdinburghGenomics/Analysis-Driver)
EdinburghGenomics/EGCG-Core
diff --git a/tests/test_clarity.py b/tests/test_clarity.py index 6b4fc43..c4446fb 100644 --- a/tests/test_clarity.py +++ b/tests/test_clarity.py @@ -178,11 +178,6 @@ class TestClarity(TestEGCG): assert open(genotype_vcf).read() == 'some test content' os.remove(genotype_vcf) - @patched_clarity('get_sample', Mock(udf={'Yield for Quoted Coverage (Gb)': 3})) - def test_get_expected_yield_for_sample(self, mocked_get_sample): - assert clarity.get_expected_yield_for_sample('a_sample_id') == 3000000000 - mocked_get_sample.assert_called_with('a_sample_id') - @patched_lims('get_processes', ['a_run']) def test_get_run(self, mocked_lims): assert clarity.get_run('a_run_id') == 'a_run' diff --git a/tests/test_ncbi.py b/tests/test_ncbi.py index a448117..287bc57 100644 --- a/tests/test_ncbi.py +++ b/tests/test_ncbi.py @@ -71,14 +71,20 @@ def test_cache(): reset_cache() -def test_get_species_name(): - fetch = 'egcg_core.ncbi._fetch_from_eutils' - assert fetch_from_cache('a species') is None - with patch(fetch, return_value=(None, None, None)): - assert ncbi.get_species_name('a species') is None - assert fetch_from_cache('a species') is None +@patch('egcg_core.ncbi._fetch_from_eutils') +def test_get_species_name(mocked_fetch): + for table in ('species', 'aliases'): + ncbi.cursor.execute('SELECT * FROM ' + table) + assert ncbi.cursor.fetchall() == [] + + mocked_fetch.return_value = (None, None, None) + assert ncbi.get_species_name('a species') is None + for table in ('species', 'aliases'): + ncbi.cursor.execute('SELECT * FROM ' + table) + assert ncbi.cursor.fetchall() == [] + reset_cache() - with patch(fetch, return_value=('1337', 'Scientific name', 'a species')): - assert ncbi.get_species_name('a species') == 'Scientific name' - assert fetch_from_cache('a species') == ('a species', '1337', 'Scientific name', 'a species') + mocked_fetch.return_value = ('1337', 'Scientific name', 'a species') + assert ncbi.get_species_name('a species') == 'Scientific name' + assert fetch_from_cache('a species') == ('a species', '1337', 'Scientific name', 'a species') reset_cache() diff --git a/tests/test_notifications.py b/tests/test_notifications.py index a843958..99c7c76 100644 --- a/tests/test_notifications.py +++ b/tests/test_notifications.py @@ -52,6 +52,22 @@ class TestNotificationCentre(TestEGCG): for name, s in self.notification_centre.subscribers.items(): s.notify.assert_called_with('a message') + @patch.object(n.NotificationCentre, 'critical') + def test_notify_failure(self, mocked_log): + self.notification_centre.subscribers = { + 'asana': Mock(notify=Mock(side_effect=EGCGError('Something broke'))), + 'email': Mock(notify=Mock(side_effect=ValueError('Something else broke'))) + } + with self.assertRaises(EGCGError) as e: + self.notification_centre.notify('a message', ('asana', 'email')) + + mocked_log.assert_called() + assert str(e.exception) == ( + 'Encountered the following errors during notification: ' + 'EGCGError: Something broke, ' + 'ValueError: Something else broke' + ) + class TestLogNotification(TestEGCG): def setUp(self): diff --git a/tests/test_rest_communication.py b/tests/test_rest_communication.py index 5fabb35..ddb3fdb 100644 --- a/tests/test_rest_communication.py +++ b/tests/test_rest_communication.py @@ -1,7 +1,7 @@ import os import json -import pytest -from unittest.mock import patch +from requests import Session +from unittest.mock import Mock, patch, call from tests import FakeRestResponse, TestEGCG from egcg_core import rest_communication from egcg_core.util import check_if_nested @@ -12,10 +12,6 @@ def rest_url(endpoint): return 'http://localhost:4999/api/0.1/' + endpoint + '/' -def ppath(extension): - return 'egcg_core.rest_communication.Communicator.' + extension - - test_endpoint = 'an_endpoint' test_nested_request_content = {'data': ['some', {'test': 'content'}]} test_flat_request_content = {'key1': 'value1', 'key2': 'value2'} @@ -33,7 +29,7 @@ def fake_request(method, url, **kwargs): return FakeRestResponse(test_nested_request_content) -patched_response = patch('requests.request', side_effect=fake_request) +patched_request = patch.object(Session, 'request', side_effect=fake_request) auth = ('a_user', 'a_password') @@ -41,6 +37,17 @@ class TestRestCommunication(TestEGCG): def setUp(self): self.comm = rest_communication.Communicator(auth=auth, baseurl='http://localhost:4999/api/0.1') + def test_begin_session(self): + s = self.comm.begin_session() + assert s.adapters['http://'] is s.adapters['https://'] + assert s.auth == auth + assert s.params == {} + + hashed_token = '{"some": "hashed"}.tokenauthentication' + self.comm._auth = hashed_token + s = self.comm.begin_session() + assert s.headers['Authorization'] == 'Token ' + hashed_token + def test_api_url(self): assert self.comm.api_url('an_endpoint') == rest_url('an_endpoint') @@ -53,13 +60,13 @@ class TestRestCommunication(TestEGCG): 'this': 'that', 'other': '{"another":"more"}', 'things': '1' } - with pytest.raises(RestCommunicationError) as e: + with self.assertRaises(RestCommunicationError) as e: self.comm._parse_query_string(dodgy_query_string) - assert str(e) == 'Bad query string: ' + dodgy_query_string + assert str(e.exception) == 'Bad query string: ' + dodgy_query_string - with pytest.raises(RestCommunicationError) as e2: + with self.assertRaises(RestCommunicationError) as e2: self.comm._parse_query_string(query_string, requires=['thangs']) - assert str(e2) == query_string + " did not contain all required fields: ['thangs']" + assert str(e2.exception) == query_string + " did not contain all required fields: ['thangs']" def test_detect_files_in_json(self): json_no_files = {'k1': 'v1', 'k2': 'v2'} @@ -81,32 +88,70 @@ class TestRestCommunication(TestEGCG): ] assert obs_json == [{'k1': 'v1'}, {'k1': 'v1'}] - @patched_response - def test_req(self, mocked_response): + @patched_request + def test_req(self, mocked_request): json_content = ['some', {'test': 'json'}] - response = self.comm._req('METHOD', rest_url(test_endpoint), json=json_content) - assert response.status_code == 200 - assert json.loads(response.content.decode('utf-8')) == response.json() == test_nested_request_content - mocked_response.assert_called_with('METHOD', rest_url(test_endpoint), auth=auth, json=json_content) - - def test_get_documents_depaginate(self): - docs = ( + for i in range(4): + response = self.comm._req('METHOD', rest_url(test_endpoint), json=json_content) + assert response.status_code == 200 + assert json.loads(response.content.decode('utf-8')) == response.json() == test_nested_request_content + mocked_request.assert_called_with('METHOD', rest_url(test_endpoint), json=json_content) + + @patch.object(Session, '__exit__') + @patch.object(Session, '__enter__') + @patched_request + def test_context_manager(self, mocked_request, mocked_enter, mocked_exit): + json_content = ['some', {'test': 'json'}] + with self.comm.session: + mocked_enter.assert_called_once() + mocked_exit.assert_not_called() + for i in range(4): # multiple calls + response = self.comm._req('METHOD', rest_url(test_endpoint), json=json_content) + assert response.status_code == 200 + assert response.json() == test_nested_request_content + mocked_request.assert_called_with('METHOD', rest_url(test_endpoint), json=json_content) + + assert mocked_request.call_count == 4 + mocked_exit.assert_called_once() + + @patch.object(rest_communication.Communicator, 'error') + @patch.object(Session, 'request') + def test_communication_error(self, mocked_req, mocked_log): + response = FakeRestResponse({}) + response.status_code = 500 + mocked_req.return_value = response + self.comm.lock = Mock() + self.comm.lock.acquire.assert_not_called() + self.comm.lock.release.assert_not_called() + + with self.assertRaises(RestCommunicationError) as e: + self.comm.get_document('an_endpoint') + + assert mocked_log.call_args[0][0].endswith('Status code 500. Reason: a reason') + assert str(e.exception) == 'Encountered a 500 status code: a reason' + self.comm.lock.acquire.assert_called_once() + self.comm.lock.release.assert_called_once() # exception raised, but lock still released + + @patch.object(rest_communication.Communicator, '_req') + def test_get_documents_depaginate(self, mocked_req): + mocked_req.side_effect = ( FakeRestResponse({'data': ['this', 'that'], '_links': {'next': {'href': 'an_endpoint?max_results=101&page=2'}}}), FakeRestResponse({'data': ['other', 'another'], '_links': {'next': {'href': 'an_endpoint?max_results=101&page=3'}}}), FakeRestResponse({'data': ['more', 'things'], '_links': {}}) ) - with patch(ppath('_req'), side_effect=docs) as mocked_req: - assert self.comm.get_documents('an_endpoint', all_pages=True, max_results=101) == [ - 'this', 'that', 'other', 'another', 'more', 'things' - ] - assert all([a[0][1].startswith(rest_url('an_endpoint')) for a in mocked_req.call_args_list]) - assert [a[1] for a in mocked_req.call_args_list] == [ + + assert self.comm.get_documents('an_endpoint', all_pages=True, max_results=101) == [ + 'this', 'that', 'other', 'another', 'more', 'things' + ] + mocked_req.assert_has_calls( + ( # Communicator.get_content passes ints - {'params': {'page': 1, 'max_results': 101}, 'quiet': False}, + call('GET', rest_url('an_endpoint'), params={'page': 1, 'max_results': 101}, quiet=False), # url parsing passes strings, but requests removes the quotes anyway - {'params': {'page': '2', 'max_results': '101'}, 'quiet': False}, - {'params': {'page': '3', 'max_results': '101'}, 'quiet': False} - ] + call('GET', rest_url('an_endpoint'), params={'page': '2', 'max_results': '101'}, quiet=False), + call('GET', rest_url('an_endpoint'), params={'page': '3', 'max_results': '101'}, quiet=False) + ) + ) docs = [ FakeRestResponse( @@ -119,38 +164,37 @@ class TestRestCommunication(TestEGCG): ] docs.append(FakeRestResponse({'data': ['last piece'], '_links': {}})) - with patch(ppath('_req'), side_effect=docs): - ret = self.comm.get_documents('an_endpoint', all_pages=True, max_results=101) - assert len(ret) == 1200 + mocked_req.side_effect = docs + ret = self.comm.get_documents('an_endpoint', all_pages=True, max_results=101) + assert len(ret) == 1200 - @patched_response - def test_get_content(self, mocked_response): + @patched_request + def test_get_content(self, mocked_request): data = self.comm.get_content(test_endpoint, max_results=100, where={'a_field': 'thing'}) assert data == test_nested_request_content - assert mocked_response.call_args[0][1].startswith(rest_url(test_endpoint)) - assert mocked_response.call_args[1] == { - 'auth': ('a_user', 'a_password'), - 'params': {'max_results': 100, 'where': '{"a_field": "thing"}', 'page': 1} - } + mocked_request.assert_called_with( + 'GET', + rest_url(test_endpoint), + params={'max_results': 100, 'where': '{"a_field": "thing"}', 'page': 1} + ) def test_get_documents(self): - with patched_response: + with patched_request: data = self.comm.get_documents(test_endpoint, max_results=100, where={'a_field': 'thing'}) assert data == test_nested_request_content['data'] def test_get_document(self): expected = test_nested_request_content['data'][0] - with patched_response: + with patched_request: observed = self.comm.get_document(test_endpoint, max_results=100, where={'a_field': 'thing'}) assert observed == expected - @patched_response - def test_post_entry(self, mocked_response): + @patched_request + def test_post_entry(self, mocked_request): self.comm.post_entry(test_endpoint, payload=test_nested_request_content) - mocked_response.assert_called_with( + mocked_request.assert_called_with( 'POST', rest_url(test_endpoint), - auth=auth, json=test_nested_request_content, files=None ) @@ -158,39 +202,35 @@ class TestRestCommunication(TestEGCG): test_request_content_plus_files = dict(test_flat_request_content) test_request_content_plus_files['f'] = ('file', file_path) self.comm.post_entry(test_endpoint, payload=test_request_content_plus_files) - mocked_response.assert_called_with( + mocked_request.assert_called_with( 'POST', rest_url(test_endpoint), - auth=auth, data=test_flat_request_content, files={'f': (file_path, b'test content', 'text/plain')} ) self.comm.post_entry(test_endpoint, payload=test_flat_request_content, use_data=True) - mocked_response.assert_called_with( + mocked_request.assert_called_with( 'POST', rest_url(test_endpoint), - auth=auth, data=test_flat_request_content, files=None ) self.comm.post_entry(test_endpoint, payload=test_request_content_plus_files, use_data=True) - mocked_response.assert_called_with( + mocked_request.assert_called_with( 'POST', rest_url(test_endpoint), - auth=auth, data=test_flat_request_content, files={'f': (file_path, b'test content', 'text/plain')} ) - @patched_response - def test_put_entry(self, mocked_response): + @patched_request + def test_put_entry(self, mocked_request): self.comm.put_entry(test_endpoint, 'an_element_id', payload=test_nested_request_content) - mocked_response.assert_called_with( + mocked_request.assert_called_with( 'PUT', rest_url(test_endpoint) + 'an_element_id', - auth=auth, json=test_nested_request_content, files=None ) @@ -199,17 +239,16 @@ class TestRestCommunication(TestEGCG): test_request_content_plus_files = dict(test_flat_request_content) test_request_content_plus_files['f'] = ('file', file_path) self.comm.put_entry(test_endpoint, 'an_element_id', payload=test_request_content_plus_files) - mocked_response.assert_called_with( + mocked_request.assert_called_with( 'PUT', rest_url(test_endpoint) + 'an_element_id', - auth=auth, data=test_flat_request_content, files={'f': (file_path, b'test content', 'text/plain')} ) - @patch(ppath('get_document'), return_value=test_patch_document) - @patched_response - def test_patch_entry(self, mocked_response, mocked_get_doc): + @patch.object(rest_communication.Communicator, 'get_document', return_value=test_patch_document) + @patched_request + def test_patch_entry(self, mocked_request, mocked_get_doc): patching_payload = {'list_to_update': ['another']} self.comm.patch_entry( test_endpoint, @@ -220,72 +259,58 @@ class TestRestCommunication(TestEGCG): ) mocked_get_doc.assert_called_with(test_endpoint, where={'uid': 'a_unique_id'}) - mocked_response.assert_called_with( + mocked_request.assert_called_with( 'PATCH', rest_url(test_endpoint) + '1337', headers={'If-Match': 1234567}, - auth=auth, json={'list_to_update': ['this', 'that', 'other', 'another']}, files=None ) - @patch(ppath('get_document'), return_value=test_patch_document) - @patched_response - def test_auth_token_and_if_match(self, mocked_response, mocked_get_doc): - self.comm._auth = 'an_auth_token' + @patch.object(rest_communication.Communicator, 'get_document', return_value=test_patch_document) + @patched_request + def test_if_match(self, mocked_request, mocked_get_doc): self.comm.patch_entry(test_endpoint, {'this': 'that'}, 'uid', 'a_unique_id') mocked_get_doc.assert_called_with(test_endpoint, where={'uid': 'a_unique_id'}) - mocked_response.assert_called_with( + mocked_request.assert_called_with( 'PATCH', rest_url(test_endpoint) + '1337', - headers={'If-Match': 1234567, 'Authorization': 'Token an_auth_token'}, + headers={'If-Match': 1234567}, json={'this': 'that'}, files=None ) - def test_post_or_patch(self): + @patch.object(rest_communication.Communicator, 'post_entry', return_value=True) + @patch.object(rest_communication.Communicator, '_patch_entry', return_value=True) + @patch.object(rest_communication.Communicator, 'get_document') + def test_post_or_patch(self, mocked_get, mocked_patch, mocked_post): test_post_or_patch_payload = {'uid': '1337', 'list_to_update': ['more'], 'another_field': 'that'} test_post_or_patch_payload_no_uid = {'list_to_update': ['more'], 'another_field': 'that'} test_post_or_patch_doc = { 'uid': 'a_uid', '_id': '1337', '_etag': 1234567, 'list_to_update': ['things'], 'another_field': 'this' } - patched_post = patch(ppath('post_entry'), return_value=True) - patched_patch = patch(ppath('_patch_entry'), return_value=True) - patched_get = patch(ppath('get_document'), return_value=test_post_or_patch_doc) - patched_get_none = patch(ppath('get_document'), return_value=None) - - with patched_get as mget, patched_patch as mpatch: - self.comm.post_or_patch( - 'an_endpoint', - [test_post_or_patch_payload], - id_field='uid', - update_lists=['list_to_update'] - ) - mget.assert_called_with('an_endpoint', where={'uid': '1337'}) - mpatch.assert_called_with( - 'an_endpoint', - test_post_or_patch_doc, - test_post_or_patch_payload_no_uid, - ['list_to_update'] - ) + mocked_get.return_value = test_post_or_patch_doc - with patched_get_none as mget, patched_post as mpost: - self.comm.post_or_patch( - 'an_endpoint', [test_post_or_patch_payload], id_field='uid', update_lists=['list_to_update'] - ) - mget.assert_called_with('an_endpoint', where={'uid': '1337'}) - mpost.assert_called_with('an_endpoint', test_post_or_patch_payload) + self.comm.post_or_patch( + 'an_endpoint', + [test_post_or_patch_payload], + id_field='uid', + update_lists=['list_to_update'] + ) + mocked_get.assert_called_with('an_endpoint', where={'uid': '1337'}) + mocked_patch.assert_called_with( + 'an_endpoint', + test_post_or_patch_doc, + test_post_or_patch_payload_no_uid, + ['list_to_update'] + ) - def test_token_auth(self): - hashed_token = '{"some": "hashed"}.tokenauthentication' - self.comm._auth = hashed_token - with patched_response as p: - self.comm._req('GET', self.comm.baseurl + 'an_endpoint') - p.assert_called_with( - 'GET', - self.comm.baseurl + 'an_endpoint', - headers={'Authorization': 'Token ' + hashed_token} - ) + mocked_get.return_value = None + self.comm.post_or_patch( + 'an_endpoint', [test_post_or_patch_payload], id_field='uid', update_lists=['list_to_update'] + ) + mocked_get.assert_called_with('an_endpoint', where={'uid': '1337'}) + mocked_post.assert_called_with('an_endpoint', test_post_or_patch_payload) def test_default(): diff --git a/tests/test_util.py b/tests/test_util.py index fe703e8..dd2348c 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -2,8 +2,9 @@ import hashlib from os import makedirs, symlink from shutil import rmtree from os.path import join, basename -from tests import TestEGCG +from unittest.mock import patch from egcg_core import util +from tests import TestEGCG fastq_dir = join(TestEGCG.assets_path, 'fastqs') @@ -13,8 +14,14 @@ def test_find_files(): assert util.find_files(TestEGCG.assets_path, 'ftest*.txt') == expected -def test_find_file(): +@patch('logging.Logger.warning') +def test_find_file(mocked_log): assert util.find_file(TestEGCG.assets_path, 'ftest.txt') == join(TestEGCG.assets_path, 'ftest.txt') + assert util.find_file(TestEGCG.assets_path, 'ftest_.txt') is None + assert util.find_file(TestEGCG.assets_path, 'ftest*.txt') is None + mocked_log.assert_called_with( + 'Searched pattern %s for one file, but got %s', (TestEGCG.assets_path, 'ftest*.txt'), 2 + ) def test_str_join(): @@ -87,10 +94,10 @@ class TestMoveDir(TestEGCG): self._create_test_file(join(self.test_dir, 'exists', 'ftest.txt'), 'another file') def tearDown(self): - rmtree(util.find_file(self.test_dir, 'to')) - rmtree(util.find_file(self.test_dir, 'from')) - rmtree(util.find_file(self.test_dir, 'exists')) - rmtree(util.find_file(self.test_dir, 'external')) + for base in ('to', 'from', 'exists', 'external'): + f = util.find_file(self.test_dir, base) + if f: + rmtree(f) def test_move_dir(self): frm = join(self.test_dir, 'from') @@ -108,7 +115,7 @@ class TestMoveDir(TestEGCG): assert util.find_file(to, 'external_renamed.txt') - def _move_dir_exists(self): + def test_move_dir_exists(self): frm = join(self.test_dir, 'from') to = join(self.test_dir, 'exists') md5_from1 = self._md5(join(frm, 'ftest.txt')) @@ -132,3 +139,4 @@ def test_query_dict(): assert util.query_dict(data, 'this') == {'that': 'other'} assert util.query_dict(data, 'this.that') == 'other' assert util.query_dict(data, 'nonexistent') is None + assert util.query_dict(data, 'nonexistent', ret_default='things') == 'things'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 7 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asana==0.6.7 attrs==22.2.0 cached-property==1.5.2 certifi==2021.5.30 coverage==6.2 -e git+https://github.com/EdinburghGenomics/EGCG-Core.git@4b8ccd933f689a9d0c5a0c98e59ddbfa697124aa#egg=EGCG_Core execnet==1.9.0 importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==2.8 MarkupSafe==2.0.1 oauthlib==3.2.2 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyclarity-lims==0.4.8 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-xdist==3.0.2 PyYAML==6.0.1 requests==2.14.2 requests-oauthlib==0.8.0 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: EGCG-Core channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asana==0.6.7 - attrs==22.2.0 - cached-property==1.5.2 - coverage==6.2 - execnet==1.9.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==2.8 - markupsafe==2.0.1 - oauthlib==3.2.2 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyclarity-lims==0.4.8 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-xdist==3.0.2 - pyyaml==6.0.1 - requests==2.14.2 - requests-oauthlib==0.8.0 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/EGCG-Core
[ "tests/test_ncbi.py::test_get_species_name", "tests/test_notifications.py::TestNotificationCentre::test_notify_failure", "tests/test_rest_communication.py::TestRestCommunication::test_begin_session", "tests/test_rest_communication.py::TestRestCommunication::test_communication_error", "tests/test_rest_communication.py::TestRestCommunication::test_context_manager", "tests/test_rest_communication.py::TestRestCommunication::test_get_content", "tests/test_rest_communication.py::TestRestCommunication::test_if_match", "tests/test_rest_communication.py::TestRestCommunication::test_patch_entry", "tests/test_rest_communication.py::TestRestCommunication::test_post_entry", "tests/test_rest_communication.py::TestRestCommunication::test_put_entry", "tests/test_rest_communication.py::TestRestCommunication::test_req", "tests/test_util.py::test_find_file", "tests/test_util.py::test_query_dict" ]
[]
[ "tests/test_clarity.py::TestClarity::test_connection", "tests/test_clarity.py::TestClarity::test_find_project_from_sample", "tests/test_clarity.py::TestClarity::test_find_run_elements_from_sample", "tests/test_clarity.py::TestClarity::test_get_genotype_information_from_lims", "tests/test_clarity.py::TestClarity::test_get_list_of_samples", "tests/test_clarity.py::TestClarity::test_get_list_of_samples_broken", "tests/test_clarity.py::TestClarity::test_get_output_containers_from_sample_and_step_name", "tests/test_clarity.py::TestClarity::test_get_plate_id_and_well_from_lims", "tests/test_clarity.py::TestClarity::test_get_released_samples", "tests/test_clarity.py::TestClarity::test_get_run", "tests/test_clarity.py::TestClarity::test_get_sample", "tests/test_clarity.py::TestClarity::test_get_sample_gender", "tests/test_clarity.py::TestClarity::test_get_sample_names_from_plate_from_lims", "tests/test_clarity.py::TestClarity::test_get_sample_names_from_project_from_lims", "tests/test_clarity.py::TestClarity::test_get_sample_release_date", "tests/test_clarity.py::TestClarity::test_get_samples", "tests/test_clarity.py::TestClarity::test_get_samples_arrived_with", "tests/test_clarity.py::TestClarity::test_get_samples_genotyped_with", "tests/test_clarity.py::TestClarity::test_get_samples_sequenced_with", "tests/test_clarity.py::TestClarity::test_get_species_from_sample", "tests/test_clarity.py::TestClarity::test_get_user_sample_name", "tests/test_clarity.py::TestClarity::test_get_valid_lanes", "tests/test_clarity.py::TestClarity::test_route_samples_to_delivery_workflow_no_name", "tests/test_clarity.py::TestClarity::test_route_samples_to_delivery_workflow_with_name", "tests/test_clarity.py::TestClarity::test_sanitize_user_id", "tests/test_ncbi.py::test_fetch_from_eutils", "tests/test_ncbi.py::test_cache", "tests/test_notifications.py::TestNotificationCentre::test_config_init", "tests/test_notifications.py::TestNotificationCentre::test_notify", "tests/test_notifications.py::TestLogNotification::test_notify", "tests/test_notifications.py::TestLogNotification::test_notify_with_attachment", "tests/test_notifications.py::TestLogNotification::test_notify_with_attachments", "tests/test_notifications.py::TestEmailSender::test_build_email", "tests/test_notifications.py::TestEmailSender::test_build_email_attachment", "tests/test_notifications.py::TestEmailSender::test_build_email_attachments", "tests/test_notifications.py::TestEmailSender::test_build_email_plain_text", "tests/test_notifications.py::TestEmailSender::test_retries", "tests/test_notifications.py::TestEmailNotification::test_notify", "tests/test_notifications.py::TestEmailNotification::test_notify_fail", "tests/test_notifications.py::test_send_plain_text_email", "tests/test_notifications.py::test_send_html_email", "tests/test_notifications.py::test_send_email", "tests/test_notifications.py::TestAsanaNotification::test_add_comment", "tests/test_notifications.py::TestAsanaNotification::test_add_comment_with_attachments", "tests/test_notifications.py::TestAsanaNotification::test_add_comment_with_one_attachment", "tests/test_notifications.py::TestAsanaNotification::test_create_task", "tests/test_notifications.py::TestAsanaNotification::test_get_entity", "tests/test_notifications.py::TestAsanaNotification::test_task", "tests/test_rest_communication.py::TestRestCommunication::test_api_url", "tests/test_rest_communication.py::TestRestCommunication::test_detect_files_in_json", "tests/test_rest_communication.py::TestRestCommunication::test_get_document", "tests/test_rest_communication.py::TestRestCommunication::test_get_documents", "tests/test_rest_communication.py::TestRestCommunication::test_get_documents_depaginate", "tests/test_rest_communication.py::TestRestCommunication::test_parse_query_string", "tests/test_rest_communication.py::TestRestCommunication::test_post_or_patch", "tests/test_rest_communication.py::test_default", "tests/test_util.py::test_find_files", "tests/test_util.py::test_str_join", "tests/test_util.py::test_find_fastqs", "tests/test_util.py::test_find_fastqs_with_lane", "tests/test_util.py::test_find_all_fastqs", "tests/test_util.py::test_find_all_fastq_pairs", "tests/test_util.py::test_same_fs", "tests/test_util.py::TestMoveDir::test_move_dir", "tests/test_util.py::TestMoveDir::test_move_dir_exists" ]
[]
MIT License
2,616
[ "egcg_core/notifications/__init__.py", "egcg_core/util.py", "CHANGELOG.md", ".travis.yml", "egcg_core/rest_communication.py", "egcg_core/clarity.py", "egcg_core/ncbi.py" ]
[ "egcg_core/notifications/__init__.py", "egcg_core/util.py", "CHANGELOG.md", ".travis.yml", "egcg_core/rest_communication.py", "egcg_core/clarity.py", "egcg_core/ncbi.py" ]
spulec__freezegun-245
07790f5b552a4933eeecf15490a8d3263e638e5b
2018-06-01 17:50:40
181f7ac7f909e561e26f5b293d2d40e82eb99f7a
diff --git a/freezegun/api.py b/freezegun/api.py index 04ed37d..358fa29 100644 --- a/freezegun/api.py +++ b/freezegun/api.py @@ -11,6 +11,7 @@ import platform import warnings import types import numbers +import inspect from dateutil import parser from dateutil.tz import tzlocal @@ -125,59 +126,99 @@ _is_cpython = ( ) -class FakeTime(object): +class BaseFakeTime(object): + call_stack_inspection_limit = 5 + + def _should_use_real_time(self, call_stack, modules_to_ignore): + if not self.call_stack_inspection_limit: + return False + + if not modules_to_ignore: + return False + + stack_limit = min(len(call_stack), self.call_stack_inspection_limit) + # Start at 1 to ignore the current frame (index 0) + for i in range(1, stack_limit): + mod = inspect.getmodule(call_stack[i][0]) + if mod.__name__.startswith(modules_to_ignore): + return True + return False - def __init__(self, time_to_freeze, previous_time_function): + +class FakeTime(BaseFakeTime): + + def __init__(self, time_to_freeze, previous_time_function, ignore=None): self.time_to_freeze = time_to_freeze self.previous_time_function = previous_time_function + self.ignore = ignore def __call__(self): + call_stack = inspect.stack() + if self._should_use_real_time(call_stack, self.ignore): + return real_time() current_time = self.time_to_freeze() return calendar.timegm(current_time.timetuple()) + current_time.microsecond / 1000000.0 -class FakeLocalTime(object): - def __init__(self, time_to_freeze, previous_localtime_function=None): +class FakeLocalTime(BaseFakeTime): + def __init__(self, time_to_freeze, previous_localtime_function=None, ignore=None): self.time_to_freeze = time_to_freeze self.previous_localtime_function = previous_localtime_function + self.ignore = ignore def __call__(self, t=None): if t is not None: return real_localtime(t) + call_stack = inspect.stack() + if self._should_use_real_time(call_stack, self.ignore): + return real_localtime() shifted_time = self.time_to_freeze() - datetime.timedelta(seconds=time.timezone) return shifted_time.timetuple() -class FakeGMTTime(object): - def __init__(self, time_to_freeze, previous_gmtime_function): +class FakeGMTTime(BaseFakeTime): + def __init__(self, time_to_freeze, previous_gmtime_function, ignore=None): self.time_to_freeze = time_to_freeze self.previous_gmtime_function = previous_gmtime_function + self.ignore = ignore def __call__(self, t=None): if t is not None: return real_gmtime(t) + call_stack = inspect.stack() + if self._should_use_real_time(call_stack, self.ignore): + return real_gmtime() return self.time_to_freeze().timetuple() -class FakeStrfTime(object): - def __init__(self, time_to_freeze, previous_strftime_function): +class FakeStrfTime(BaseFakeTime): + def __init__(self, time_to_freeze, previous_strftime_function, ignore=None): self.time_to_freeze = time_to_freeze self.previous_strftime_function = previous_strftime_function + self.ignore = ignore def __call__(self, format, time_to_format=None): if time_to_format is None: - time_to_format = FakeLocalTime(self.time_to_freeze)() + call_stack = inspect.stack() + if not self._should_use_real_time(call_stack, self.ignore): + time_to_format = FakeLocalTime(self.time_to_freeze)() + return real_strftime(format, time_to_format) -class FakeClock(object): +class FakeClock(BaseFakeTime): times_to_freeze = [] - def __init__(self, previous_clock_function, tick=False): + def __init__(self, previous_clock_function, tick=False, ignore=None): self.previous_clock_function = previous_clock_function self.tick = tick + self.ignore = ignore def __call__(self, *args, **kwargs): + call_stack = inspect.stack() + if self._should_use_real_time(call_stack, self.ignore): + return self.previous_clock_function() + if len(self.times_to_freeze) == 1: return 0.0 if not self.tick else self.previous_clock_function() @@ -499,11 +540,11 @@ class _freeze_time(object): datetime.date.dates_to_freeze.append(time_to_freeze) datetime.date.tz_offsets.append(self.tz_offset) - fake_time = FakeTime(time_to_freeze, time.time) - fake_localtime = FakeLocalTime(time_to_freeze, time.localtime) - fake_gmtime = FakeGMTTime(time_to_freeze, time.gmtime) - fake_strftime = FakeStrfTime(time_to_freeze, time.strftime) - fake_clock = FakeClock(time.clock, tick=self.tick) + fake_time = FakeTime(time_to_freeze, time.time, ignore=self.ignore) + fake_localtime = FakeLocalTime(time_to_freeze, time.localtime, ignore=self.ignore) + fake_gmtime = FakeGMTTime(time_to_freeze, time.gmtime, ignore=self.ignore) + fake_strftime = FakeStrfTime(time_to_freeze, time.strftime, ignore=self.ignore) + fake_clock = FakeClock(time.clock, tick=self.tick, ignore=self.ignore) fake_clock.times_to_freeze.append(time_to_freeze) time.time = fake_time time.localtime = fake_localtime
Why doesn't `ignore` work for email.utils.formatdate? Example: ```python def test_foo(self): from email.utils import formatdate import ipdb ipdb.set_trace() print(formatdate()) with freeze_time('2012-10-15', ignore=['email']): print(formatdate()) assert 0 ``` What's the expected behavior of the above usage of `ignore`? I'm expecting that it will not replace `time.time` inside `formatdate`, yet that appears to be what happens: ```python > test.py(509)test_foo() 508 ipdb.set_trace() --> 509 print(formatdate()) 510 with freeze_time('2012-10-15', ignore=['email']): ipdb> s --Call-- > /usr/lib/python2.7/email/utils.py(124)formatdate() 123 --> 124 def formatdate(timeval=None, localtime=False, usegmt=False): 125 """Returns a date string as specified by RFC 2822, e.g.: ipdb> n > /usr/lib/python2.7/email/utils.py(142)formatdate() 141 # 2822 requires that day and month names be the English abbreviations. --> 142 if timeval is None: 143 timeval = time.time() ipdb> n > /usr/lib/python2.7/email/utils.py(143)formatdate() 142 if timeval is None: --> 143 timeval = time.time() 144 if localtime: ipdb> b 143 Breakpoint 1 at /usr/lib/python2.7/email/utils.py:143 ipdb> print time.time <built-in function time> ipdb> print time.time() 1527821322.89 ipdb> c Fri, 01 Jun 2018 02:48:46 -0000 > /usr/lib/python2.7/email/utils.py(143)formatdate() 142 if timeval is None: 1-> 143 timeval = time.time() 144 if localtime: ipdb> print time.time <freezegun.api.FakeTime object at 0x7f1e2e624890> ipdb> print time.time() 1350259200.0 ipdb> c Mon, 15 Oct 2012 00:00:00 -0000 ```
spulec/freezegun
diff --git a/tests/test_class_import.py b/tests/test_class_import.py index 278899d..8810e48 100644 --- a/tests/test_class_import.py +++ b/tests/test_class_import.py @@ -70,6 +70,28 @@ def test_isinstance_works(): freezer.stop() +def test_fake_uses_real_when_ignored(): + real_time_before = time.time() + with freeze_time('2012-01-14', ignore=['tests.fake_module']): + real_time = fake_time_function() + real_time_after = time.time() + assert real_time_before <= real_time <= real_time_after + + +def test_can_ignore_email_module(): + from email.utils import formatdate + with freeze_time('2012-01-14'): + faked_date_str = formatdate() + + before_date_str = formatdate() + with freeze_time('2012-01-14', ignore=['email']): + date_str = formatdate() + + after_date_str = formatdate() + assert date_str != faked_date_str + assert before_date_str <= date_str <= after_date_str + + @freeze_time('2011-01-01') def test_avoid_replacing_equal_to_anything(): assert fake_module.equal_to_anything.description == 'This is the equal_to_anything object'
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backports.zoneinfo==0.2.1 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==3.7.1 coveralls==1.11.1 dateparser==1.1.3 docopt==0.6.2 -e git+https://github.com/spulec/freezegun.git@07790f5b552a4933eeecf15490a8d3263e638e5b#egg=freezegun humanize==3.14.0 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 maya==0.6.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pendulum==2.1.2 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 pytz-deprecation-shim==0.1.0.post0 pytzdata==2020.1 regex==2022.3.2 requests==2.27.1 six==1.17.0 snaptime==0.2.4 tomli==1.2.3 typing_extensions==4.1.1 tzdata==2025.2 tzlocal==4.2 urllib3==1.26.20 zipp==3.6.0
name: freezegun channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backports-zoneinfo==0.2.1 - charset-normalizer==2.0.12 - coverage==3.7.1 - coveralls==1.11.1 - dateparser==1.1.3 - docopt==0.6.2 - humanize==3.14.0 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - maya==0.6.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pendulum==2.1.2 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pytz-deprecation-shim==0.1.0.post0 - pytzdata==2020.1 - regex==2022.3.2 - requests==2.27.1 - six==1.17.0 - snaptime==0.2.4 - tomli==1.2.3 - typing-extensions==4.1.1 - tzdata==2025.2 - tzlocal==4.2 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/freezegun
[ "tests/test_class_import.py::test_can_ignore_email_module" ]
[]
[ "tests/test_class_import.py::test_import_datetime_works", "tests/test_class_import.py::test_import_date_works", "tests/test_class_import.py::test_import_time", "tests/test_class_import.py::test_start_and_stop_works", "tests/test_class_import.py::test_isinstance_works", "tests/test_class_import.py::test_fake_uses_real_when_ignored", "tests/test_class_import.py::test_avoid_replacing_equal_to_anything", "tests/test_class_import.py::test_import_localtime", "tests/test_class_import.py::test_fake_gmtime_function", "tests/test_class_import.py::test_fake_strftime_function", "tests/test_class_import.py::test_import_after_start", "tests/test_class_import.py::test_none_as_initial" ]
[]
Apache License 2.0
2,617
[ "freezegun/api.py" ]
[ "freezegun/api.py" ]
fniessink__next-action-93
4af7c956d738e25f879ceb9da77bfb393fcb9713
2018-06-01 21:51:44
4af7c956d738e25f879ceb9da77bfb393fcb9713
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4622239..c5192b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- The due date argument to `--due` is now optional. Closes #92. + ## [0.14.1] - 2018-06-01 ### Fixed diff --git a/README.md b/README.md index 42a13a2..ad017f2 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,8 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the ```console $ next-action --help -usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d <due date>] -[-o] [-p [<priority>]] [-s [<style>]] [<context|project> ...] +usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d [<due date>] | +-o] [-p [<priority>]] [-s [<style>]] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task properties such as priority, due date, and creation date. Limit the tasks from which the next action @@ -60,8 +60,9 @@ optional arguments: -n <number>, --number <number> number of next actions to show (default: 1) -a, --all show all next actions - -d <due date>, --due <due date> - show only next actions due on or before the date + -d [<due date>], --due [<due date>] + show only next actions with a due date; if a date is given, show only next actions + due on or before that date -o, --overdue show only overdue next actions -p [<priority>], --priority [<priority>] minimum priority (A-Z) of next actions to show (default: None) @@ -91,6 +92,8 @@ Completed tasks (~~`x This is a completed task`~~) and tasks with a creation dat ### Limiting the tasks from which next actions are selected +#### By contexts and/or projects + You can limit the tasks from which *Next-action* picks the next action by passing contexts and/or projects: ```console @@ -123,11 +126,20 @@ $ next-action -+PaintHouse @store (G) Buy wood for new +DogHouse @store ``` -To limit the the tasks from which the next action is selected to actions with a due date, specify a due date: +#### By due date + +To limit the the tasks from which the next action is selected to actions with a due date, use the `--due` option: ```console -$ next-action @home --due june -Pay invoice @home due:2018-06-28 +$ next-action @home --due +(K) Pay July invoice @home due:2018-07-28 +``` + +Add a due date to select a next action from tasks due on or before that date: + +```console +$ next-action @home --due "june 2018" +(L) Pay June invoice @home due:2018-06-28 ``` To make sure you have no overdue actions, or work on overdue actions first, limit the tasks from which the next action is selected to overdue actions: @@ -137,6 +149,8 @@ $ next-action --overdue Buy flowers due:2018-02-14 ``` +#### By priority + To make sure you work on important tasks rather than urgent tasks, you can make sure the tasks from which the next action is selected have at least a minimum priority: ```console @@ -271,9 +285,9 @@ To run the unit tests: ```console $ python -m unittest -....................................................................................................................................................... +......................................................................................................................................................... ---------------------------------------------------------------------- -Ran 151 tests in 0.587s +Ran 153 tests in 0.548s OK ``` diff --git a/docs/todo.txt b/docs/todo.txt index 9e3f99c..06842c9 100644 --- a/docs/todo.txt +++ b/docs/todo.txt @@ -5,6 +5,7 @@ Get rid of old +DogHouse @home Borrow ladder from the neighbors +PaintHouse @home Buy flowers due:2018-02-14 -Pay invoice @home due:2018-06-28 +(L) Pay June invoice @home due:2018-06-28 +(K) Pay July invoice @home due:2018-07-28 x This is a completed task 9999-01-01 Start preparing for five-digit years diff --git a/docs/update_readme.py b/docs/update_readme.py index 591c40a..6d5d826 100644 --- a/docs/update_readme.py +++ b/docs/update_readme.py @@ -1,12 +1,13 @@ """ Insert the output of console commands into the README.md file. """ import os +import shlex import subprocess # nosec def do_command(line): """ Run the command on the line and return its stdout and stderr. """ - command = line[2:].split(" ") + command = shlex.split(line[2:]) if command[0] == "next-action" and "--write-config-file" not in command: command.extend(["--config", "docs/.next-action.cfg"]) command_output = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index cd6fec0..953b952 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -25,7 +25,7 @@ class NextActionArgumentParser(argparse.ArgumentParser): "the tasks from which the next action is selected by specifying contexts the tasks must have " "and/or projects the tasks must belong to.", usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] " - "[-n <number> | -a] [-d <due date>] [-o] [-p [<priority>]] [-s [<style>]] " + "[-n <number> | -a] [-d [<due date>] | -o] [-p [<priority>]] [-s [<style>]] " "[<context|project> ...]", width=shutil.get_terminal_size().columns - len("usage: "))) self.__default_filenames = ["~/todo.txt"] @@ -55,8 +55,9 @@ class NextActionArgumentParser(argparse.ArgumentParser): "-a", "--all", help="show all next actions", action="store_const", dest="number", const=sys.maxsize) date = self.add_mutually_exclusive_group() date.add_argument( - "-d", "--due", metavar="<due date>", type=date_type, - help="show only next actions due on or before the date") + "-d", "--due", metavar="<due date>", type=date_type, nargs="?", const=datetime.date.max, + help="show only next actions with a due date; if a date is given, show only next actions due on or " + "before that date") date.add_argument("-o", "--overdue", help="show only overdue next actions", action="store_true") self.add_argument( "-p", "--priority", metavar="<priority>", choices=string.ascii_uppercase, nargs="?",
Make --due argument optional to pick next action from tasks with any due date
fniessink/next-action
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py index aa5dfc4..403c66e 100644 --- a/tests/unittests/arguments/test_parser.py +++ b/tests/unittests/arguments/test_parser.py @@ -11,7 +11,7 @@ from next_action.arguments import config, parse_arguments USAGE_MESSAGE = textwrap.fill( - "usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d <due date>] [-o] " + "usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d [<due date>] | -o] " "[-p [<priority>]] [-s [<style>]] [<context|project> ...]", 120) + "\n" @@ -221,6 +221,11 @@ class DueDateTest(ParserTestCase): """ Test that the default value for due date is None. """ self.assertEqual(None, parse_arguments()[1].due) + @patch.object(sys, "argv", ["next-action", "--due"]) + def test_no_due_date(self): + """ Test that the due date is the max date if the user doesn't specify a date. """ + self.assertEqual(datetime.date.max, parse_arguments()[1].due) + @patch.object(sys, "argv", ["next-action", "--due", "2018-01-01"]) def test_due_date(self): """ Test that the default value for due date is None. """ diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index 388ff6f..8148d29 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -65,7 +65,7 @@ class CLITest(unittest.TestCase): os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough. self.assertRaises(SystemExit, next_action) self.assertEqual(call("""\ -usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d <due date>] [-o] [-p +usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d [<due date>] | -o] [-p [<priority>]] [-s [<style>]] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task @@ -85,8 +85,9 @@ optional arguments: -n <number>, --number <number> number of next actions to show (default: 1) -a, --all show all next actions - -d <due date>, --due <due date> - show only next actions due on or before the date + -d [<due date>], --due [<due date>] + show only next actions with a due date; if a date is given, show only next actions due on or + before that date -o, --overdue show only overdue next actions -p [<priority>], --priority [<priority>] minimum priority (A-Z) of next actions to show (default: None) diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py index 5874fb8..05d4db5 100644 --- a/tests/unittests/test_pick_action.py +++ b/tests/unittests/test_pick_action.py @@ -205,6 +205,15 @@ class DueTasks(PickActionTestCase): self.namespace.due = datetime.date(2000, 1, 1) self.assertEqual([overdue], pick_action.next_actions([no_duedate, future_duedate, overdue], self.namespace)) + def test_any_due_tasks(self): + """ Test that tasks that are not due are filtered. """ + no_duedate = todotxt.Task("Task") + future_duedate = todotxt.Task("Task due:9999-01-01") + overdue = todotxt.Task("Task due:2000-01-01") + self.namespace.due = datetime.date.max + self.assertEqual([overdue, future_duedate], + pick_action.next_actions([no_duedate, future_duedate, overdue], self.namespace)) + class MinimimPriorityTest(PickActionTest): """ Unit test for the mininum priority filter. """
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 5 }
0.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pylint", "pycodestyle", "coverage" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 Cerberus==1.2 coverage==7.8.0 dateparser==0.7.0 dill==0.3.9 exceptiongroup==1.2.2 iniconfig==2.1.0 isort==6.0.1 mccabe==0.7.0 -e git+https://github.com/fniessink/next-action.git@4af7c956d738e25f879ceb9da77bfb393fcb9713#egg=next_action packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 pycodestyle==2.13.0 Pygments==2.2.0 pylint==3.3.6 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==3.12 regex==2024.11.6 six==1.17.0 tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0 tzlocal==5.3.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.3.9 - cerberus==1.2 - coverage==7.8.0 - dateparser==0.7.0 - dill==0.3.9 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - isort==6.0.1 - mccabe==0.7.0 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pycodestyle==2.13.0 - pygments==2.2.0 - pylint==3.3.6 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==3.12 - regex==2024.11.6 - six==1.17.0 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 - tzlocal==5.3.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number", "tests/unittests/arguments/test_parser.py::DueDateTest::test_faulty_date", "tests/unittests/arguments/test_parser.py::DueDateTest::test_no_due_date", "tests/unittests/test_cli.py::CLITest::test_help", "tests/unittests/test_cli.py::CLITest::test_missing_file" ]
[ "tests/unittests/arguments/test_parser.py::DueDateTest::test_due_date", "tests/unittests/arguments/test_parser.py::DueDateTest::test_invalid_date", "tests/unittests/arguments/test_parser.py::DueDateTest::test_too_long" ]
[ "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style", "tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice", "tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename", "tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default", "tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument", "tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions", "tests/unittests/arguments/test_parser.py::NumberTest::test_default_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_number", "tests/unittests/arguments/test_parser.py::DueDateTest::test_default", "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_show_all_actions", "tests/unittests/test_cli.py::CLITest::test_version", "tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_due_dates", "tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first", "tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks", "tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks", "tests/unittests/test_pick_action.py::PickActionTest::test_one_task", "tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date", "tests/unittests/test_pick_action.py::PickActionTest::test_project", "tests/unittests/test_pick_action.py::PickActionTest::test_projects", "tests/unittests/test_pick_action.py::FilterTasksTest::test_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_contexts", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_contexts", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_projects", "tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_context", "tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_project", "tests/unittests/test_pick_action.py::FilterTasksTest::test_project_and_context", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_completed_task", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_future_task", "tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_these_tasks", "tests/unittests/test_pick_action.py::OverdueTasks::test_overdue_tasks", "tests/unittests/test_pick_action.py::DueTasks::test_any_due_tasks", "tests/unittests/test_pick_action.py::DueTasks::test_due_tasks", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_creation_dates", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_due_and_creation_dates", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_due_dates", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_higher_prio_goes_first", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_multiple_tasks", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_no_tasks", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_one_task", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_priority", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_priority_and_creation_date", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_project", "tests/unittests/test_pick_action.py::MinimimPriorityTest::test_projects" ]
[]
Apache License 2.0
2,618
[ "docs/todo.txt", "docs/update_readme.py", "next_action/arguments/parser.py", "CHANGELOG.md", "README.md" ]
[ "docs/todo.txt", "docs/update_readme.py", "next_action/arguments/parser.py", "CHANGELOG.md", "README.md" ]
fniessink__next-action-99
ccfac4290ac360ea795bdc5b71d8574152af99aa
2018-06-03 21:52:07
cc56f793b0e7f8b9bce0a11aeb5749f77126619d
diff --git a/CHANGELOG.md b/CHANGELOG.md index 7db5eed..d3ce3c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unrelease] + +### Fixed + +- Include reference parameter into standard configuration file. Fixes #98. + ## [0.16.0] - 2018-06-03 ### Added diff --git a/next_action/arguments/config.py b/next_action/arguments/config.py index 243e787..6c6acdc 100644 --- a/next_action/arguments/config.py +++ b/next_action/arguments/config.py @@ -29,7 +29,8 @@ def read_config_file(filename: str, default_filename: str, error: Callable[[str] def write_config_file() -> None: """ Generate a configuration file on standard out. """ intro = "# Configuration file for Next-action. Edit the settings below as you like.\n" - config = yaml.dump(dict(file="~/todo.txt", number=1, style="default"), default_flow_style=False) + config = yaml.dump(dict(file="~/todo.txt", number=1, reference="multiple", style="default"), + default_flow_style=False) sys.stdout.write(intro + config)
Add `--reference` to standard configuration file
fniessink/next-action
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py index fcdf588..8eb5728 100644 --- a/tests/unittests/arguments/test_config.py +++ b/tests/unittests/arguments/test_config.py @@ -99,7 +99,7 @@ class ConfigFileTest(ConfigTestCase): """ Test that a config file can be written to stdout. """ self.assertRaises(SystemExit, parse_arguments) expected = "# Configuration file for Next-action. Edit the settings below as you like.\n" - expected += "file: ~/todo.txt\nnumber: 1\nstyle: default\n" + expected += "file: ~/todo.txt\nnumber: 1\nreference: multiple\nstyle: default\n" self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 2 }
0.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
Cerberus==1.2 dateparser==0.7.0 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@ccfac4290ac360ea795bdc5b71d8574152af99aa#egg=next_action packaging==24.2 pluggy==1.5.0 Pygments==2.2.0 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==3.12 regex==2024.11.6 six==1.17.0 tomli==2.2.1 tzlocal==5.3.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cerberus==1.2 - dateparser==0.7.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pygments==2.2.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==3.12 - regex==2024.11.6 - six==1.17.0 - tomli==2.2.1 - tzlocal==5.3.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config" ]
[]
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config", "tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files", "tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_config.py::NumberTest::test_all_false", "tests/unittests/arguments/test_config.py::NumberTest::test_all_true", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_valid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_zero", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style", "tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority", "tests/unittests/arguments/test_config.py::ReferenceTest::test_invalid_priority", "tests/unittests/arguments/test_config.py::ReferenceTest::test_override", "tests/unittests/arguments/test_config.py::ReferenceTest::test_valid_reference" ]
[]
Apache License 2.0
2,619
[ "next_action/arguments/config.py", "CHANGELOG.md" ]
[ "next_action/arguments/config.py", "CHANGELOG.md" ]
Yelp__swagger_spec_validator-95
40e1cc926775777ff2d56e271fd61697c6235579
2018-06-05 10:37:03
40e1cc926775777ff2d56e271fd61697c6235579
diff --git a/swagger_spec_validator/validator20.py b/swagger_spec_validator/validator20.py index fe17ded..002eb44 100644 --- a/swagger_spec_validator/validator20.py +++ b/swagger_spec_validator/validator20.py @@ -268,6 +268,15 @@ def validate_defaults_in_definition(definition_spec, deref): validate_property_default(property_spec, deref) +def validate_arrays_in_definition(definition_spec, def_name=None): + if definition_spec.get('type') == 'array' and 'items' not in definition_spec: + raise SwaggerValidationError( + 'Definition of type array must define `items` property{}.'.format( + '' if not def_name else ' (definition {})'.format(def_name), + ), + ) + + def validate_definition(definition, deref, def_name=None): definition = deref(definition) @@ -286,6 +295,7 @@ def validate_definition(definition, deref, def_name=None): ) validate_defaults_in_definition(definition, deref) + validate_arrays_in_definition(definition, def_name=def_name) if 'discriminator' in definition: required_props, not_required_props = get_collapsed_properties_type_mappings(definition, deref)
Spec validation will not fail if items is not present and type is array The following specs are not valid according to [Swagger 2.0 Specs](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object), editor.swagger.io and according to `swagger-tools` npm package. ```yaml swagger: '2.0' info: title: Example produces: - application/json paths: /test: get: responses: '200': description: HTTP200 schema: type: array ``` Error reported by editor.swagger.io ![https://image.ibb.co/ghkioJ/5186391944200192.png](https://image.ibb.co/ghkioJ/5186391944200192.png) Error reported by npm ``` API Errors: #/paths/~1test/get/responses/200/schema: Missing required property: items 1 error and 0 warnings ```
Yelp/swagger_spec_validator
diff --git a/tests/validator20/validate_definitions_test.py b/tests/validator20/validate_definitions_test.py index 0b61dc0..6c2b6aa 100644 --- a/tests/validator20/validate_definitions_test.py +++ b/tests/validator20/validate_definitions_test.py @@ -95,3 +95,30 @@ def test_api_check_default_fails(property_spec, validator, instance): validation_error = excinfo.value.args[1] assert validation_error.instance == instance assert validation_error.validator == validator + + +def test_type_array_with_items_succeed_validation(): + definitions = { + 'definition_1': { + 'type': 'array', + 'items': { + 'type': 'string', + }, + }, + } + + # Success if no exception are raised + validate_definitions(definitions, lambda x: x) + + +def test_type_array_without_items_succeed_fails(): + definitions = { + 'definition_1': { + 'type': 'array', + }, + } + + with pytest.raises(SwaggerValidationError) as excinfo: + validate_definitions(definitions, lambda x: x) + + assert str(excinfo.value) == 'Definition of type array must define `items` property (definition definition_1).' diff --git a/tests/validator20/validate_spec_test.py b/tests/validator20/validate_spec_test.py index 5bc9e53..981255c 100644 --- a/tests/validator20/validate_spec_test.py +++ b/tests/validator20/validate_spec_test.py @@ -341,3 +341,37 @@ def test_failure_because_references_in_operation_responses(): validate_spec(invalid_spec) assert 'GET /endpoint does not have a valid responses section. ' \ 'That section cannot be just a reference to another object.' in str(excinfo.value) + + +def test_type_array_with_items_succeed_validation(minimal_swagger_dict): + minimal_swagger_dict['definitions'] = { + 'definition_1': { + 'type': 'array', + 'items': { + 'type': 'string', + }, + }, + } + + # Success if no exception are raised + validate_spec(minimal_swagger_dict) + + [email protected]( + 'swagger_dict_override', + ( + { + 'definitions': { + 'definition_1': { + 'type': 'array', + }, + }, + }, + ) +) +def test_type_array_without_items_succeed_fails(minimal_swagger_dict, swagger_dict_override): + minimal_swagger_dict.update(swagger_dict_override) + with pytest.raises(SwaggerValidationError) as excinfo: + validate_spec(minimal_swagger_dict) + + assert str(excinfo.value) == 'Definition of type array must define `items` property (definition definition_1).'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 httpretty==1.1.4 importlib-metadata==4.8.3 iniconfig==1.1.1 jsonschema==3.2.0 mock==5.2.0 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 -e git+https://github.com/Yelp/swagger_spec_validator.git@40e1cc926775777ff2d56e271fd61697c6235579#egg=swagger_spec_validator tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: swagger_spec_validator channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - httpretty==1.1.4 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jsonschema==3.2.0 - mock==5.2.0 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/swagger_spec_validator
[ "tests/validator20/validate_definitions_test.py::test_type_array_without_items_succeed_fails" ]
[ "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec0]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec1]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec2]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec3]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec4]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec5]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec6]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec7]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec8]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec9]", "tests/validator20/validate_definitions_test.py::test_api_check_default_succeed[property_spec10]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec0-type-wrong_type]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec1-type-wrong_type]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec2-type-wrong_type]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec3-type-wrong_type]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec4-type-wrong_type]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec5-type-wrong_type]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec6-type--1]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec7-minLength-short_string]", "tests/validator20/validate_definitions_test.py::test_api_check_default_fails[property_spec8-type-not_a_number_or_boolean]", "tests/validator20/validate_spec_test.py::test_success", "tests/validator20/validate_spec_test.py::test_definitons_not_present_success", "tests/validator20/validate_spec_test.py::test_empty_definitions_success", "tests/validator20/validate_spec_test.py::test_api_parameters_as_refs", "tests/validator20/validate_spec_test.py::test_fails_on_invalid_external_ref_in_dict", "tests/validator20/validate_spec_test.py::test_fails_on_invalid_external_ref_in_list", "tests/validator20/validate_spec_test.py::test_recursive_ref", "tests/validator20/validate_spec_test.py::test_recursive_ref_failure", "tests/validator20/validate_spec_test.py::test_complicated_refs", "tests/validator20/validate_spec_test.py::test_specs_with_discriminator", "tests/validator20/validate_spec_test.py::test_specs_with_discriminator_fail_because_not_required", "tests/validator20/validate_spec_test.py::test_specs_with_discriminator_fail_because_not_string", "tests/validator20/validate_spec_test.py::test_specs_with_discriminator_fail_because_not_in_properties", "tests/validator20/validate_spec_test.py::test_specs_with_discriminator_in_allOf", "tests/validator20/validate_spec_test.py::test_specs_with_discriminator_in_allOf_fail_because_not_required", "tests/validator20/validate_spec_test.py::test_specs_with_discriminator_in_allOf_fail_because_not_string", "tests/validator20/validate_spec_test.py::test_specs_with_discriminator_in_allOf_fail_because_not_in_properties", "tests/validator20/validate_spec_test.py::test_read_yaml_specs", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec0]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec1]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec2]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec3]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec4]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec5]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec6]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec7]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec8]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec9]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec10]", "tests/validator20/validate_spec_test.py::test_valid_specs_with_check_of_default_types[property_spec11]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec0-type-wrong_type]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec1-type-wrong_type]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec2-type-wrong_type]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec3-type-wrong_type]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec4-type-wrong_type]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec5-type-wrong_type]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec6-type--1]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec7-minLength-short_string]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec8-type-not_a_number_or_boolean]", "tests/validator20/validate_spec_test.py::test_failure_due_to_wrong_default_type[property_spec9-enum-not_valid]", "tests/validator20/validate_spec_test.py::test_ref_without_str_argument", "tests/validator20/validate_spec_test.py::test_failure_because_references_in_operation_responses", "tests/validator20/validate_spec_test.py::test_type_array_with_items_succeed_validation", "tests/validator20/validate_spec_test.py::test_type_array_without_items_succeed_fails[swagger_dict_override0]" ]
[ "tests/validator20/validate_definitions_test.py::test_type_array_with_items_succeed_validation" ]
[]
Apache License 2.0
2,620
[ "swagger_spec_validator/validator20.py" ]
[ "swagger_spec_validator/validator20.py" ]
fniessink__next-action-103
1a1278fb1e5854ea7291f385307ae9e8f8eb67d1
2018-06-05 17:42:32
cc56f793b0e7f8b9bce0a11aeb5749f77126619d
diff --git a/CHANGELOG.md b/CHANGELOG.md index bbdd695..eb96b4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- Short options immediately followed by a value weren't parsed correctly. Fixes #84. + ## [0.16.1] - 2018-06-04 ### Fixed diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index 725d787..0d7a4b1 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -153,7 +153,8 @@ class NextActionArgumentParser(argparse.ArgumentParser): @staticmethod def arguments_not_specified(*arguments: str) -> bool: """ Return whether any of the arguments was specified on the command line. """ - return all([argument not in sys.argv for argument in arguments]) + return not any([command_line_arg.startswith(argument) for argument in arguments + for command_line_arg in sys.argv]) def fix_filenames(self, namespace: argparse.Namespace) -> None: """ Fix the filenames. """
next-action -pA isn't interpreted as next-action -p A
fniessink/next-action
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py index 8eb5728..12e9a15 100644 --- a/tests/unittests/arguments/test_config.py +++ b/tests/unittests/arguments/test_config.py @@ -270,13 +270,19 @@ class PriorityTest(ConfigTestCase): @patch.object(sys, "argv", ["next-action", "--priority", "M"]) @patch.object(config, "open", mock_open(read_data="priority: Z")) def test_override_priority(self): - """ Test that a command line style overrides the priority in the config file. """ + """ Test that a command line option overrides the priority in the config file. """ + self.assertEqual("M", parse_arguments()[1].priority) + + @patch.object(sys, "argv", ["next-action", "-pM"]) + @patch.object(config, "open", mock_open(read_data="priority: Z")) + def test_override_short(self): + """ Test that a short command line option overrides the priority in the config file. """ self.assertEqual("M", parse_arguments()[1].priority) @patch.object(sys, "argv", ["next-action", "--priority"]) @patch.object(config, "open", mock_open(read_data="priority: Z")) def test_cancel_priority(self): - """ Test that a command line style overrides the priority in the config file. """ + """ Test that a command line option overrides the priority in the config file. """ self.assertEqual(None, parse_arguments()[1].priority) @patch.object(sys, "argv", ["next-action"])
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 2 }
0.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage", "codacy-coverage", "pylint", "pycodestyle", "bandit" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 bandit==1.8.3 Cerberus==1.2 certifi==2025.1.31 charset-normalizer==3.4.1 codacy-coverage==1.3.11 coverage==7.8.0 dateparser==0.7.0 dill==0.3.9 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 isort==6.0.1 markdown-it-py==3.0.0 mccabe==0.7.0 mdurl==0.1.2 -e git+https://github.com/fniessink/next-action.git@1a1278fb1e5854ea7291f385307ae9e8f8eb67d1#egg=next_action packaging==24.2 pbr==6.1.1 platformdirs==4.3.7 pluggy==1.5.0 pycodestyle==2.13.0 Pygments==2.19.1 pylint==3.3.6 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 regex==2024.11.6 requests==2.32.3 rich==14.0.0 six==1.17.0 stevedore==5.4.1 tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0 tzlocal==5.3.1 urllib3==2.3.0
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.3.9 - bandit==1.8.3 - cerberus==1.2 - certifi==2025.1.31 - charset-normalizer==3.4.1 - codacy-coverage==1.3.11 - coverage==7.8.0 - dateparser==0.7.0 - dill==0.3.9 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - isort==6.0.1 - markdown-it-py==3.0.0 - mccabe==0.7.0 - mdurl==0.1.2 - packaging==24.2 - pbr==6.1.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pycodestyle==2.13.0 - pygments==2.19.1 - pylint==3.3.6 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - regex==2024.11.6 - requests==2.32.3 - rich==14.0.0 - six==1.17.0 - stevedore==5.4.1 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 - tzlocal==5.3.1 - urllib3==2.3.0 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_config.py::PriorityTest::test_override_short" ]
[]
[ "tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config", "tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config", "tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file", "tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files", "tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_config.py::NumberTest::test_all_false", "tests/unittests/arguments/test_config.py::NumberTest::test_all_true", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides", "tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence", "tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_valid_number", "tests/unittests/arguments/test_config.py::NumberTest::test_zero", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style", "tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style", "tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority", "tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority", "tests/unittests/arguments/test_config.py::ReferenceTest::test_invalid_priority", "tests/unittests/arguments/test_config.py::ReferenceTest::test_override", "tests/unittests/arguments/test_config.py::ReferenceTest::test_valid_reference" ]
[]
Apache License 2.0
2,621
[ "next_action/arguments/parser.py", "CHANGELOG.md" ]
[ "next_action/arguments/parser.py", "CHANGELOG.md" ]
fniessink__next-action-104
db664ba1c1b642acedf768c9283a1ebf19e2bc35
2018-06-05 19:09:06
cc56f793b0e7f8b9bce0a11aeb5749f77126619d
diff --git a/CHANGELOG.md b/CHANGELOG.md index eb96b4e..ee37b1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Fixed +- Mention how to deal with options with optional arguments followed by positional arguments in the help information and README. Closes #100. - Short options immediately followed by a value weren't parsed correctly. Fixes #84. ## [0.16.1] - 2018-06-04 diff --git a/README.md b/README.md index f0a5712..f225b7f 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,9 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the - [Usage](#usage) - [Limiting the tasks from which next actions are selected](#limiting-the-tasks-from-which-next-actions-are-selected) - [Showing more than one next action](#showing-more-than-one-next-action) - - [Output options](#output-options) + - [Styling the output](#styling-the-output) - [Configuring *Next-action*](#configuring-next-action) + - [Option details](#option-details) - [Recent changes](#recent-changes) - [Develop](#develop) @@ -41,7 +42,7 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the ```console $ next-action --help usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a -| -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [<context|project> ...] +| -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task properties such as priority, due date, and creation date. Limit the tasks from which the next action @@ -90,6 +91,9 @@ limit the tasks from which the next actions are selected: of at least one of the projects -@<context> ... contexts the next action must not have -+<project> ... projects the next action must not be part of + +Use -- to separate options with optional arguments from contexts and projects, in order to handle cases +where a context or project is mistaken for an argument to an option. ``` Assuming your todo.txt file is your home folder, running *Next-action* without arguments will show the next action you should do. Given this [todo.txt](https://raw.githubusercontent.com/fniessink/next-action/master/docs/todo.txt), calling mom would be the next action: @@ -192,7 +196,7 @@ $ next-action --all @store Note again that completed tasks and task with a future creation date are never shown since they can't be a next action. -### Output options +### Styling the output By default, *Next-action* references the todo.txt file from which actions were read if you read tasks from multiple todo.txt files. The `--reference` option controls this: @@ -298,12 +302,39 @@ style: colorful Run `next-action --help` to see the list of possible styles. -#### Precedence of options +### Option details + +#### Precedence Options in the configuration file override the default options. Command-line options in turn override options in the configuration file. If you have a configuration file with default options that you occasionally want to ignore, you can skip reading the configuration file entirely with the `--no-config-file` option. +#### Optional arguments followed by positional arguments + +When you use an option that takes an optional argument, but have it followed by a positional argument, *Next-action* will interpret the positional argument as the argument to the option and complain, e.g.: + +```console +$ next-action --due @home +usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a +| -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...] +next-action: error: argument -d/--due: invalid date: @home +``` + +There's two ways to help *Next-action* figure out what you mean. Either reverse the order of the arguments: + +```console +$ next-action @home --due +(K) Pay July invoice @home due:2018-07-28 +``` + +Or use `--` to separate the option from the positional argument(s): + +```console +$ next-action --due -- @home +(K) Pay July invoice @home due:2018-07-28 +``` + ## Recent changes See the [change log](https://github.com/fniessink/next-action/blob/master/CHANGELOG.md). @@ -316,9 +347,9 @@ To run the unit tests: ```console $ python -m unittest -................................................................................................................................................................... +.................................................................................................................................................................... ---------------------------------------------------------------------- -Ran 163 tests in 0.614s +Ran 164 tests in 0.592s OK ``` diff --git a/docs/update_readme.py b/docs/update_readme.py index 6d5d826..0c6a123 100644 --- a/docs/update_readme.py +++ b/docs/update_readme.py @@ -9,9 +9,10 @@ def do_command(line): """ Run the command on the line and return its stdout and stderr. """ command = shlex.split(line[2:]) if command[0] == "next-action" and "--write-config-file" not in command: - command.extend(["--config", "docs/.next-action.cfg"]) + command.insert(1, "--config") + command.insert(2, "docs/.next-action.cfg") command_output = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - check=True, universal_newlines=True) + universal_newlines=True) return command_output.stdout.strip(), command_output.stderr.strip() diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index 0d7a4b1..2e2e9e2 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -20,14 +20,16 @@ class NextActionArgumentParser(argparse.ArgumentParser): def __init__(self) -> None: super().__init__( + usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] " + "[-r <ref>] [-s [<style>]] [-a | -n <number>] [-d [<due date>] | -o] " + "[-p [<priority>]] [--] [<context|project> ...]", + width=shutil.get_terminal_size().columns - len("usage: ")), description="Show the next action in your todo.txt. The next action is selected from the tasks in the " "todo.txt file based on task properties such as priority, due date, and creation date. Limit " "the tasks from which the next action is selected by specifying contexts the tasks must have " "and/or projects the tasks must belong to.", - usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] " - "[-r <ref>] [-s [<style>]] [-a | -n <number>] [-d [<due date>] | -o] " - "[-p [<priority>]] [<context|project> ...]", - width=shutil.get_terminal_size().columns - len("usage: "))) + epilog="Use -- to separate options with optional arguments from contexts and projects, in order to handle " + "cases where a context or project is mistaken for an argument to an option.") self.__default_filenames = ["~/todo.txt"] self.add_optional_arguments() self.add_filter_arguments()
next-action --due @work gives error message This is because `--due` has an optional argument. Mention in docs that either `next-action @work --due` or `next-action --due -- @work` works.
fniessink/next-action
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py index e0867ee..4e6a5ec 100644 --- a/tests/unittests/arguments/test_parser.py +++ b/tests/unittests/arguments/test_parser.py @@ -12,7 +12,7 @@ from next_action.arguments import config, parse_arguments USAGE_MESSAGE = textwrap.fill( "usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] " - "[-a | -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [<context|project> ...]", 120) + "\n" + "[-a | -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]", 120) + "\n" class ParserTestCase(unittest.TestCase): diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index ec2d8cc..8c8978b 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -66,7 +66,7 @@ class CLITest(unittest.TestCase): self.assertRaises(SystemExit, next_action) self.assertEqual(call("""\ usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a | -n -<number>] [-d [<due date>] | -o] [-p [<priority>]] [<context|project> ...] +<number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by @@ -115,6 +115,9 @@ limit the tasks from which the next actions are selected: one of the projects -@<context> ... contexts the next action must not have -+<project> ... projects the next action must not be part of + +Use -- to separate options with optional arguments from contexts and projects, in order to handle cases where a +context or project is mistaken for an argument to an option. """), mock_stdout_write.call_args_list[0])
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 4 }
0.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
Cerberus==1.2 dateparser==0.7.0 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@db664ba1c1b642acedf768c9283a1ebf19e2bc35#egg=next_action packaging==24.2 pluggy==1.5.0 Pygments==2.2.0 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==3.12 regex==2024.11.6 six==1.17.0 tomli==2.2.1 tzlocal==5.3.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cerberus==1.2 - dateparser==0.7.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pygments==2.2.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==3.12 - regex==2024.11.6 - six==1.17.0 - tomli==2.2.1 - tzlocal==5.3.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number", "tests/unittests/arguments/test_parser.py::DueDateTest::test_faulty_date", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_faulty_date", "tests/unittests/test_cli.py::CLITest::test_help", "tests/unittests/test_cli.py::CLITest::test_missing_file" ]
[ "tests/unittests/arguments/test_parser.py::DueDateTest::test_due_date", "tests/unittests/arguments/test_parser.py::DueDateTest::test_invalid_date", "tests/unittests/arguments/test_parser.py::DueDateTest::test_too_long" ]
[ "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style", "tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice", "tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename", "tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default", "tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument", "tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions", "tests/unittests/arguments/test_parser.py::NumberTest::test_default_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_number", "tests/unittests/arguments/test_parser.py::DueDateTest::test_default", "tests/unittests/arguments/test_parser.py::DueDateTest::test_no_due_date", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_always", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_default", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_multiple", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_never", "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_reference_filename", "tests/unittests/test_cli.py::CLITest::test_show_all_actions", "tests/unittests/test_cli.py::CLITest::test_version" ]
[]
Apache License 2.0
2,622
[ "docs/update_readme.py", "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
[ "docs/update_readme.py", "next_action/arguments/parser.py", "README.md", "CHANGELOG.md" ]
fniessink__next-action-106
7fb68d17949d8bf901bd29963d427aeb8aaf600e
2018-06-05 20:30:53
cc56f793b0e7f8b9bce0a11aeb5749f77126619d
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a6d5a5..8a3b394 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- Capitalise the help information. Fixes #105. + ## [0.16.2] - 2018-06-05 ### Fixed diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py index 2e2e9e2..6f6fd37 100644 --- a/next_action/arguments/parser.py +++ b/next_action/arguments/parser.py @@ -29,16 +29,25 @@ class NextActionArgumentParser(argparse.ArgumentParser): "the tasks from which the next action is selected by specifying contexts the tasks must have " "and/or projects the tasks must belong to.", epilog="Use -- to separate options with optional arguments from contexts and projects, in order to handle " - "cases where a context or project is mistaken for an argument to an option.") + "cases where a context or project is mistaken for an argument to an option.", + formatter_class=CapitalisedHelpFormatter) self.__default_filenames = ["~/todo.txt"] self.add_optional_arguments() + self.add_configuration_options() + self.add_input_options() + self.add_output_options() + self.add_number_options() self.add_filter_arguments() def add_optional_arguments(self) -> None: """ Add the optional arguments to the parser. """ + self._optionals.title = self._optionals.title.capitalize() self.add_argument( "--version", action="version", version="%(prog)s {0}".format(next_action.__version__)) - config_group = self.add_argument_group("configuration options") + + def add_configuration_options(self) -> None: + """ Add the configuration options to the parser. """ + config_group = self.add_argument_group("Configuration options") config_file = config_group.add_mutually_exclusive_group() config_file.add_argument( "-c", "--config-file", metavar="<config.cfg>", type=str, default="~/.next-action.cfg", nargs="?", @@ -46,12 +55,18 @@ class NextActionArgumentParser(argparse.ArgumentParser): "configuration file") config_file.add_argument( "-w", "--write-config-file", help="generate a sample configuration file and exit", action="store_true") - input_group = self.add_argument_group("input options") + + def add_input_options(self) -> None: + """ Add the input options to the parser. """ + input_group = self.add_argument_group("Input options") input_group.add_argument( "-f", "--file", action="append", metavar="<todo.txt>", default=self.__default_filenames[:], type=str, help="filename of todo.txt file to read; can be '-' to read from standard input; argument can be " "repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)") - output_group = self.add_argument_group("output options") + + def add_output_options(self) -> None: + """ Add the output/styling options to the parser. """ + output_group = self.add_argument_group("Output options") output_group.add_argument( "-r", "--reference", choices=["always", "never", "multiple"], default="multiple", help="reference next actions with the name of their todo.txt file (default: when reading multiple " @@ -60,7 +75,10 @@ class NextActionArgumentParser(argparse.ArgumentParser): output_group.add_argument( "-s", "--style", metavar="<style>", choices=styles, default=None, nargs="?", help="colorize the output; available styles: {0} (default: %(default)s)".format(", ".join(styles))) - number_group = self.add_argument_group("show multiple next actions") + + def add_number_options(self) -> None: + """ Add the number options to the parser. """ + number_group = self.add_argument_group("Show multiple next actions") number = number_group.add_mutually_exclusive_group() number.add_argument( "-a", "--all", default=1, action="store_const", dest="number", const=sys.maxsize, @@ -71,7 +89,7 @@ class NextActionArgumentParser(argparse.ArgumentParser): def add_filter_arguments(self) -> None: """ Add the filter arguments to the parser. """ - filters = self.add_argument_group("limit the tasks from which the next actions are selected") + filters = self.add_argument_group("Limit the tasks from which the next actions are selected") date = filters.add_mutually_exclusive_group() date.add_argument( "-d", "--due", metavar="<due date>", type=date_type, nargs="?", const=datetime.date.max, @@ -171,6 +189,13 @@ class NextActionArgumentParser(argparse.ArgumentParser): namespace.file = list(dict.fromkeys(filenames)) +class CapitalisedHelpFormatter(argparse.HelpFormatter): + """ Capitalise the usage string. """ + def add_usage(self, usage, actions, groups, prefix=None): + prefix = prefix or 'Usage: ' + return super(CapitalisedHelpFormatter, self).add_usage(usage, actions, groups, prefix or "Usage: ") + + def filter_type(value: str) -> str: """ Return the filter if it's valid, else raise an error. """ if value.startswith("@") or value.startswith("+"):
Capitalise the sections in the help information
fniessink/next-action
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py index 4e6a5ec..7a085f1 100644 --- a/tests/unittests/arguments/test_parser.py +++ b/tests/unittests/arguments/test_parser.py @@ -11,7 +11,7 @@ from next_action.arguments import config, parse_arguments USAGE_MESSAGE = textwrap.fill( - "usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] " + "Usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] " "[-a | -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]", 120) + "\n" diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py index 8c8978b..23c4ee7 100644 --- a/tests/unittests/test_cli.py +++ b/tests/unittests/test_cli.py @@ -65,30 +65,30 @@ class CLITest(unittest.TestCase): os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough. self.assertRaises(SystemExit, next_action) self.assertEqual(call("""\ -usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a | -n +Usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a | -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...] Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by specifying contexts the tasks must have and/or projects the tasks must belong to. -optional arguments: +Optional arguments: -h, --help show this help message and exit --version show program's version number and exit -configuration options: +Configuration options: -c [<config.cfg>], --config-file [<config.cfg>] filename of configuration file to read (default: ~/.next-action.cfg); omit filename to not read any configuration file -w, --write-config-file generate a sample configuration file and exit -input options: +Input options: -f <todo.txt>, --file <todo.txt> filename of todo.txt file to read; can be '-' to read from standard input; argument can be repeated to read tasks from multiple todo.txt files (default: ~/todo.txt) -output options: +Output options: -r {always,never,multiple}, --reference {always,never,multiple} reference next actions with the name of their todo.txt file (default: when reading multiple todo.txt files) @@ -98,12 +98,12 @@ output options: paraiso-dark, paraiso-light, pastie, perldoc, rainbow_dash, rrt, tango, trac, vim, vs, xcode (default: None) -show multiple next actions: +Show multiple next actions: -a, --all show all next actions -n <number>, --number <number> number of next actions to show (default: 1) -limit the tasks from which the next actions are selected: +Limit the tasks from which the next actions are selected: -d [<due date>], --due [<due date>] show only next actions with a due date; if a date is given, show only next actions due on or before that date
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 2 }
0.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
Cerberus==1.2 dateparser==0.7.0 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@7fb68d17949d8bf901bd29963d427aeb8aaf600e#egg=next_action packaging==24.2 pluggy==1.5.0 Pygments==2.2.0 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==3.12 regex==2024.11.6 six==1.17.0 tomli==2.2.1 tzlocal==5.3.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cerberus==1.2 - dateparser==0.7.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pygments==2.2.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==3.12 - regex==2024.11.6 - six==1.17.0 - tomli==2.2.1 - tzlocal==5.3.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number", "tests/unittests/arguments/test_parser.py::DueDateTest::test_faulty_date", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_faulty_date", "tests/unittests/test_cli.py::CLITest::test_help", "tests/unittests/test_cli.py::CLITest::test_missing_file" ]
[ "tests/unittests/arguments/test_parser.py::DueDateTest::test_due_date", "tests/unittests/arguments/test_parser.py::DueDateTest::test_invalid_date", "tests/unittests/arguments/test_parser.py::DueDateTest::test_too_long" ]
[ "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters", "tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style", "tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice", "tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename", "tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default", "tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument", "tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context", "tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project", "tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions", "tests/unittests/arguments/test_parser.py::NumberTest::test_default_number", "tests/unittests/arguments/test_parser.py::NumberTest::test_number", "tests/unittests/arguments/test_parser.py::DueDateTest::test_default", "tests/unittests/arguments/test_parser.py::DueDateTest::test_no_due_date", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_always", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_default", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_multiple", "tests/unittests/arguments/test_parser.py::ReferenceTest::test_never", "tests/unittests/test_cli.py::CLITest::test_context", "tests/unittests/test_cli.py::CLITest::test_empty_task_file", "tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines", "tests/unittests/test_cli.py::CLITest::test_number", "tests/unittests/test_cli.py::CLITest::test_one_task", "tests/unittests/test_cli.py::CLITest::test_project", "tests/unittests/test_cli.py::CLITest::test_reading_stdin", "tests/unittests/test_cli.py::CLITest::test_reference_filename", "tests/unittests/test_cli.py::CLITest::test_show_all_actions", "tests/unittests/test_cli.py::CLITest::test_version" ]
[]
Apache License 2.0
2,623
[ "next_action/arguments/parser.py", "CHANGELOG.md" ]
[ "next_action/arguments/parser.py", "CHANGELOG.md" ]
iterative__dvc-745
5d169916de9360ce368ee96012addcf672b84993
2018-06-05 22:42:34
6e82c6c748d14ae1e5238ea3716595fcaec1b72b
diff --git a/.gitignore b/.gitignore index 3f25a701e..92077daad 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,5 @@ innosetup/config.ini .coverage dvc/version.py + +*.swp diff --git a/dvc/cli.py b/dvc/cli.py index 075aff008..2ba52bb3f 100644 --- a/dvc/cli.py +++ b/dvc/cli.py @@ -215,6 +215,10 @@ def parse_args(argv=None): action='store_true', default=False, help='Reproduce only single data item without recursive dependencies check.') + repro_parser.add_argument('-c', + '--cwd', + default=os.path.curdir, + help='Directory to reproduce from.') repro_parser.set_defaults(func=CmdRepro) # Remove diff --git a/dvc/command/repro.py b/dvc/command/repro.py index 4125ddb33..681df032e 100644 --- a/dvc/command/repro.py +++ b/dvc/command/repro.py @@ -8,6 +8,11 @@ from dvc.stage import Stage class CmdRepro(CmdBase): def run(self): recursive = not self.args.single_item + saved_dir = os.path.realpath(os.curdir) + if self.args.cwd: + os.chdir(self.args.cwd) + + ret = 0 for target in self.args.targets: try: self.project.reproduce(target, @@ -16,7 +21,8 @@ class CmdRepro(CmdBase): except ReproductionError as ex: msg = 'Failed to reproduce \'{}\''.format(target) self.project.logger.error(msg, ex) - return 1 + ret = 1 + break except StageNotFoundError as ex: if os.path.exists(target): msg = '\'{}\' is not a dvc file.'.format(target) @@ -26,9 +32,13 @@ class CmdRepro(CmdBase): else: msg = '\'{}\' does not exist.'.format(target) self.project.logger.error(msg) - return 1 + ret = 1 + break except Exception as ex: msg = 'Failed to reproduce \'{}\' - unexpected error'.format(target) self.project.logger.error(msg, ex) - return 1 - return 0 + ret = 1 + break + + os.chdir(saved_dir) + return ret
dvc repro: change dir The same as `make -C external-lib`. Important: Make sure it works with Git submodules! ``` $ dvc repro -C myproj ``` ``` $ dvc repro -C myproj myproj/Posts.xml.dvc ```
iterative/dvc
diff --git a/tests/test_repro.py b/tests/test_repro.py index 119b58e9a..9ee5d052e 100644 --- a/tests/test_repro.py +++ b/tests/test_repro.py @@ -186,6 +186,37 @@ class TestCmdRepro(TestRepro): self.assertNotEqual(ret, 0) +class TestCmdReproChdir(TestDvc): + def test(self): + dname = 'dir' + os.mkdir(dname) + foo = os.path.join(dname, self.FOO) + bar = os.path.join(dname, self.BAR) + code = os.path.join(dname, self.CODE) + shutil.copyfile(self.FOO, foo) + shutil.copyfile(self.CODE, code) + + ret = main(['run', + '-f', 'Dvcfile', + '-c', dname, + '-d', self.FOO, + '-o', self.BAR, + 'python {} {} {}'.format(self.CODE, self.FOO, self.BAR)]) + self.assertEqual(ret, 0) + self.assertTrue(os.path.isfile(foo)) + self.assertTrue(os.path.isfile(bar)) + self.assertTrue(filecmp.cmp(foo, bar)) + + os.unlink(bar) + + ret = main(['repro', + '-c', dname]) + self.assertEqual(ret, 0) + self.assertTrue(os.path.isfile(foo)) + self.assertTrue(os.path.isfile(bar)) + self.assertTrue(filecmp.cmp(foo, bar)) + + class TestReproExternalBase(TestDvc): def should_test(self): return False
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 3 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
altgraph==0.17.4 bcrypt==4.3.0 binaryornot==0.4.4 boto3==1.7.4 botocore==1.10.84 cachetools==4.2.4 certifi==2025.1.31 cffi==1.17.1 chardet==5.2.0 charset-normalizer==3.4.1 colorama==0.4.6 configobj==5.0.9 configparser==7.2.0 coverage==7.8.0 cryptography==44.0.2 decorator==5.2.1 dill==0.2.9 docutils==0.21.2 -e git+https://github.com/iterative/dvc.git@5d169916de9360ce368ee96012addcf672b84993#egg=dvc exceptiongroup==1.2.2 execnet==2.1.1 future==0.16.0 gapic-google-cloud-datastore-v1==0.15.3 gapic-google-cloud-error-reporting-v1beta1==0.15.3 gapic-google-cloud-logging-v2==0.91.3 gitdb==4.0.12 GitPython==3.1.44 google-api-core==0.1.4 google-auth==1.35.0 google-cloud==0.32.0 google-cloud-bigquery==0.28.0 google-cloud-bigquery-datatransfer==0.1.1 google-cloud-bigtable==0.28.1 google-cloud-container==0.1.1 google-cloud-core==0.28.1 google-cloud-datastore==1.4.0 google-cloud-dns==0.28.0 google-cloud-error-reporting==0.28.0 google-cloud-firestore==0.28.0 google-cloud-language==1.0.2 google-cloud-logging==1.4.0 google-cloud-monitoring==0.28.1 google-cloud-pubsub==0.30.1 google-cloud-resource-manager==0.28.1 google-cloud-runtimeconfig==0.28.1 google-cloud-spanner==0.29.0 google-cloud-speech==0.30.0 google-cloud-storage==1.6.0 google-cloud-trace==0.17.0 google-cloud-translate==1.3.1 google-cloud-videointelligence==1.0.1 google-cloud-vision==0.29.0 google-crc32c==1.7.1 google-gax==0.15.16 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 grpc-google-iam-v1==0.11.4 grpcio==1.71.0 httplib2==0.22.0 idna==3.10 iniconfig==2.1.0 jmespath==0.10.0 jsonpath-rw==1.4.0 macholib==1.16.3 nanotime==0.5.2 networkx==3.2.1 ntfsutils==0.1.5 oauth2client==3.0.0 packaging==24.2 paramiko==3.5.1 pefile==2024.8.26 pluggy==1.5.0 ply==3.8 proto-google-cloud-datastore-v1==0.90.4 proto-google-cloud-error-reporting-v1beta1==0.15.3 proto-google-cloud-logging-v2==0.91.3 protobuf==3.20.3 psutil==5.9.8 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyInstaller==3.3.1 PyNaCl==1.5.0 pyparsing==3.2.3 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 reflink==0.2.0 requests==2.32.3 rsa==4.9 s3transfer==0.1.13 schema==0.7.7 six==1.17.0 smmap==5.0.2 tomli==2.2.1 typing_extensions==4.13.0 urllib3==2.3.0 zc.lockfile==3.0.post1
name: dvc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - altgraph==0.17.4 - bcrypt==4.3.0 - binaryornot==0.4.4 - boto3==1.7.4 - botocore==1.10.84 - cachetools==4.2.4 - certifi==2025.1.31 - cffi==1.17.1 - chardet==5.2.0 - charset-normalizer==3.4.1 - colorama==0.4.6 - configobj==5.0.9 - configparser==7.2.0 - coverage==7.8.0 - cryptography==44.0.2 - decorator==5.2.1 - dill==0.2.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - future==0.16.0 - gapic-google-cloud-datastore-v1==0.15.3 - gapic-google-cloud-error-reporting-v1beta1==0.15.3 - gapic-google-cloud-logging-v2==0.91.3 - gitdb==4.0.12 - gitpython==3.1.44 - google-api-core==0.1.4 - google-auth==1.35.0 - google-cloud==0.32.0 - google-cloud-bigquery==0.28.0 - google-cloud-bigquery-datatransfer==0.1.1 - google-cloud-bigtable==0.28.1 - google-cloud-container==0.1.1 - google-cloud-core==0.28.1 - google-cloud-datastore==1.4.0 - google-cloud-dns==0.28.0 - google-cloud-error-reporting==0.28.0 - google-cloud-firestore==0.28.0 - google-cloud-language==1.0.2 - google-cloud-logging==1.4.0 - google-cloud-monitoring==0.28.1 - google-cloud-pubsub==0.30.1 - google-cloud-resource-manager==0.28.1 - google-cloud-runtimeconfig==0.28.1 - google-cloud-spanner==0.29.0 - google-cloud-speech==0.30.0 - google-cloud-storage==1.6.0 - google-cloud-trace==0.17.0 - google-cloud-translate==1.3.1 - google-cloud-videointelligence==1.0.1 - google-cloud-vision==0.29.0 - google-crc32c==1.7.1 - google-gax==0.15.16 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - grpc-google-iam-v1==0.11.4 - grpcio==1.71.0 - httplib2==0.22.0 - idna==3.10 - iniconfig==2.1.0 - jmespath==0.10.0 - jsonpath-rw==1.4.0 - macholib==1.16.3 - nanotime==0.5.2 - networkx==3.2.1 - ntfsutils==0.1.5 - oauth2client==3.0.0 - packaging==24.2 - paramiko==3.5.1 - pefile==2024.8.26 - pluggy==1.5.0 - ply==3.8 - proto-google-cloud-datastore-v1==0.90.4 - proto-google-cloud-error-reporting-v1beta1==0.15.3 - proto-google-cloud-logging-v2==0.91.3 - protobuf==3.20.3 - psutil==5.9.8 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pyinstaller==3.3.1 - pynacl==1.5.0 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - reflink==0.2.0 - requests==2.32.3 - rsa==4.9 - s3transfer==0.1.13 - schema==0.7.7 - six==1.17.0 - smmap==5.0.2 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 - zc-lockfile==3.0.post1 prefix: /opt/conda/envs/dvc
[ "tests/test_repro.py::TestCmdReproChdir::test" ]
[ "tests/test_repro.py::TestReproMissingMd5InStageFile::test" ]
[ "tests/test_repro.py::TestReproNoDeps::test", "tests/test_repro.py::TestReproForce::test", "tests/test_repro.py::TestReproChangedCode::test", "tests/test_repro.py::TestReproChangedData::test", "tests/test_repro.py::TestReproChangedDeepData::test", "tests/test_repro.py::TestReproPhony::test", "tests/test_repro.py::TestNonExistingOutput::test", "tests/test_repro.py::TestReproDataSource::test", "tests/test_repro.py::TestReproChangedDir::test", "tests/test_repro.py::TestCmdRepro::test", "tests/test_repro.py::TestReproExternalBase::test", "tests/test_repro.py::TestReproExternalS3::test", "tests/test_repro.py::TestReproExternalGS::test" ]
[]
Apache License 2.0
2,624
[ ".gitignore", "dvc/command/repro.py", "dvc/cli.py" ]
[ ".gitignore", "dvc/command/repro.py", "dvc/cli.py" ]
iterative__dvc-746
408f96b31cafa25c5eeced9d721c0a20a2c0a438
2018-06-05 23:38:55
6e82c6c748d14ae1e5238ea3716595fcaec1b72b
diff --git a/dvc/remote/local.py b/dvc/remote/local.py index 75602ae0a..9c98d493a 100644 --- a/dvc/remote/local.py +++ b/dvc/remote/local.py @@ -160,6 +160,11 @@ class RemoteLOCAL(RemoteBase): msg = u'Checking out directory \'{}\' with cache \'{}\'' Logger.debug(msg.format(os.path.relpath(path), os.path.relpath(cache))) + # Create dir separately so that dir is created + # even if there are no files in it + if not os.path.exists(path): + os.makedirs(path) + dir_cache = self.dir_cache(cache) for relpath, c in dir_cache.items(): p = os.path.join(path, relpath)
Dvc checkout for an empty dir should create the dir itself
iterative/dvc
diff --git a/tests/test_checkout.py b/tests/test_checkout.py index f39263ac2..95a0b807b 100644 --- a/tests/test_checkout.py +++ b/tests/test_checkout.py @@ -170,3 +170,20 @@ class TestCheckoutMissingMd5InStageFile(TestRepro): yaml.dump(d, fd) self.dvc.checkout() + + +class TestCheckoutEmptyDir(TestDvc): + def test(self): + dname = 'empty_dir' + os.mkdir(dname) + + stage = self.dvc.add(dname) + self.assertEqual(len(stage.outs), 1) + + stage.outs[0].remove() + self.assertFalse(os.path.exists(dname)) + + self.dvc.checkout() + + self.assertTrue(os.path.isdir(dname)) + self.assertEqual(len(os.listdir(dname)), 0)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "mock", "coverage", "codecov", "xmltodict", "awscli", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
altgraph==0.17.4 awscli==1.38.23 bcrypt==4.3.0 binaryornot==0.4.4 boto3==1.7.4 botocore==1.10.84 cachetools==4.2.4 certifi==2025.1.31 cffi==1.17.1 chardet==5.2.0 charset-normalizer==3.4.1 codecov==2.1.13 colorama==0.4.6 configobj==5.0.9 configparser==7.2.0 coverage==7.8.0 cryptography==44.0.2 decorator==5.2.1 dill==0.2.9 docutils==0.16 -e git+https://github.com/iterative/dvc.git@408f96b31cafa25c5eeced9d721c0a20a2c0a438#egg=dvc exceptiongroup==1.2.2 future==0.16.0 gapic-google-cloud-datastore-v1==0.15.3 gapic-google-cloud-error-reporting-v1beta1==0.15.3 gapic-google-cloud-logging-v2==0.91.3 gitdb==4.0.12 GitPython==3.1.44 google-api-core==0.1.4 google-auth==1.35.0 google-cloud==0.32.0 google-cloud-bigquery==0.28.0 google-cloud-bigquery-datatransfer==0.1.1 google-cloud-bigtable==0.28.1 google-cloud-container==0.1.1 google-cloud-core==0.28.1 google-cloud-datastore==1.4.0 google-cloud-dns==0.28.0 google-cloud-error-reporting==0.28.0 google-cloud-firestore==0.28.0 google-cloud-language==1.0.2 google-cloud-logging==1.4.0 google-cloud-monitoring==0.28.1 google-cloud-pubsub==0.30.1 google-cloud-resource-manager==0.28.1 google-cloud-runtimeconfig==0.28.1 google-cloud-spanner==0.29.0 google-cloud-speech==0.30.0 google-cloud-storage==1.6.0 google-cloud-trace==0.17.0 google-cloud-translate==1.3.1 google-cloud-videointelligence==1.0.1 google-cloud-vision==0.29.0 google-crc32c==1.7.1 google-gax==0.15.16 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 grpc-google-iam-v1==0.11.4 grpcio==1.71.0 httplib2==0.22.0 idna==3.10 iniconfig==2.1.0 jmespath==0.10.0 jsonpath-rw==1.4.0 macholib==1.16.3 mock==5.2.0 nanotime==0.5.2 networkx==3.2.1 nose==1.3.7 ntfsutils==0.1.5 oauth2client==3.0.0 packaging==24.2 paramiko==3.5.1 pefile==2024.8.26 pluggy==1.5.0 ply==3.8 proto-google-cloud-datastore-v1==0.90.4 proto-google-cloud-error-reporting-v1beta1==0.15.3 proto-google-cloud-logging-v2==0.91.3 protobuf==3.20.3 psutil==5.9.8 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyInstaller==3.3.1 PyNaCl==1.5.0 pyparsing==3.2.3 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 reflink==0.2.0 requests==2.32.3 rsa==4.7.2 s3transfer==0.1.13 schema==0.7.7 six==1.17.0 smmap==5.0.2 tomli==2.2.1 urllib3==1.26.20 xmltodict==0.14.2 zc.lockfile==3.0.post1
name: dvc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - altgraph==0.17.4 - awscli==1.38.23 - bcrypt==4.3.0 - binaryornot==0.4.4 - boto3==1.7.4 - botocore==1.10.84 - cachetools==4.2.4 - certifi==2025.1.31 - cffi==1.17.1 - chardet==5.2.0 - charset-normalizer==3.4.1 - codecov==2.1.13 - colorama==0.4.6 - configobj==5.0.9 - configparser==7.2.0 - coverage==7.8.0 - cryptography==44.0.2 - decorator==5.2.1 - dill==0.2.9 - docutils==0.16 - exceptiongroup==1.2.2 - future==0.16.0 - gapic-google-cloud-datastore-v1==0.15.3 - gapic-google-cloud-error-reporting-v1beta1==0.15.3 - gapic-google-cloud-logging-v2==0.91.3 - gitdb==4.0.12 - gitpython==3.1.44 - google-api-core==0.1.4 - google-auth==1.35.0 - google-cloud==0.32.0 - google-cloud-bigquery==0.28.0 - google-cloud-bigquery-datatransfer==0.1.1 - google-cloud-bigtable==0.28.1 - google-cloud-container==0.1.1 - google-cloud-core==0.28.1 - google-cloud-datastore==1.4.0 - google-cloud-dns==0.28.0 - google-cloud-error-reporting==0.28.0 - google-cloud-firestore==0.28.0 - google-cloud-language==1.0.2 - google-cloud-logging==1.4.0 - google-cloud-monitoring==0.28.1 - google-cloud-pubsub==0.30.1 - google-cloud-resource-manager==0.28.1 - google-cloud-runtimeconfig==0.28.1 - google-cloud-spanner==0.29.0 - google-cloud-speech==0.30.0 - google-cloud-storage==1.6.0 - google-cloud-trace==0.17.0 - google-cloud-translate==1.3.1 - google-cloud-videointelligence==1.0.1 - google-cloud-vision==0.29.0 - google-crc32c==1.7.1 - google-gax==0.15.16 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - grpc-google-iam-v1==0.11.4 - grpcio==1.71.0 - httplib2==0.22.0 - idna==3.10 - iniconfig==2.1.0 - jmespath==0.10.0 - jsonpath-rw==1.4.0 - macholib==1.16.3 - mock==5.2.0 - nanotime==0.5.2 - networkx==3.2.1 - nose==1.3.7 - ntfsutils==0.1.5 - oauth2client==3.0.0 - packaging==24.2 - paramiko==3.5.1 - pefile==2024.8.26 - pluggy==1.5.0 - ply==3.8 - proto-google-cloud-datastore-v1==0.90.4 - proto-google-cloud-error-reporting-v1beta1==0.15.3 - proto-google-cloud-logging-v2==0.91.3 - protobuf==3.20.3 - psutil==5.9.8 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pyinstaller==3.3.1 - pynacl==1.5.0 - pyparsing==3.2.3 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - reflink==0.2.0 - requests==2.32.3 - rsa==4.7.2 - s3transfer==0.1.13 - schema==0.7.7 - six==1.17.0 - smmap==5.0.2 - tomli==2.2.1 - urllib3==1.26.20 - xmltodict==0.14.2 - zc-lockfile==3.0.post1 prefix: /opt/conda/envs/dvc
[ "tests/test_checkout.py::TestCheckoutEmptyDir::test" ]
[ "tests/test_checkout.py::TestCheckoutMissingMd5InStageFile::test" ]
[ "tests/test_checkout.py::TestCheckout::test", "tests/test_checkout.py::TestCheckoutSingleStage::test", "tests/test_checkout.py::TestCheckoutCorruptedCacheFile::test", "tests/test_checkout.py::TestCmdCheckout::test", "tests/test_checkout.py::TestRemoveFilesWhenCheckout::test", "tests/test_checkout.py::TestGitIgnoreBasic::test", "tests/test_checkout.py::TestGitIgnoreWhenCheckout::test" ]
[]
Apache License 2.0
2,625
[ "dvc/remote/local.py" ]
[ "dvc/remote/local.py" ]
zalando-incubator__kubernetes-log-watcher-61
c13fd091c4bf2965eea26d4a9840c7669fbf2978
2018-06-06 11:30:20
c13fd091c4bf2965eea26d4a9840c7669fbf2978
codecov-io: # [Codecov](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61?src=pr&el=h1) Report > Merging [#61](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61?src=pr&el=desc) into [master](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/commit/c13fd091c4bf2965eea26d4a9840c7669fbf2978?src=pr&el=desc) will **increase** coverage by `0.35%`. > The diff coverage is `100%`. [![Impacted file tree graph](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61/graphs/tree.svg?height=150&width=650&token=2NLvIPFi70&src=pr)](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #61 +/- ## ========================================== + Coverage 84.68% 85.04% +0.35% ========================================== Files 9 9 Lines 418 428 +10 ========================================== + Hits 354 364 +10 Misses 64 64 ``` | [Impacted Files](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [kube\_log\_watcher/kube.py](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61/diff?src=pr&el=tree#diff-a3ViZV9sb2dfd2F0Y2hlci9rdWJlLnB5) | `83.72% <100%> (+0.38%)` | :arrow_up: | | [kube\_log\_watcher/main.py](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61/diff?src=pr&el=tree#diff-a3ViZV9sb2dfd2F0Y2hlci9tYWluLnB5) | `77.52% <100%> (+1.19%)` | :arrow_up: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61?src=pr&el=footer). Last update [c13fd09...19b7fe6](https://codecov.io/gh/zalando-incubator/kubernetes-log-watcher/pull/61?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments). vetinari: :+1: vetinari: :+1: mohabusama: 👍
diff --git a/delivery.yaml b/delivery.yaml index 26e68f7..bb7cad7 100644 --- a/delivery.yaml +++ b/delivery.yaml @@ -1,6 +1,7 @@ build_steps: - desc: "Install dependencies" cmd: | + apt-get update apt-get install -q -y --no-install-recommends \ git \ python3.5 \ @@ -28,7 +29,7 @@ build_steps: RELEASE_VERSION=$(git describe --tags --always --dirty) AGENT_IMAGE=registry-write.opensource.zalan.do/eagleeye/kubernetes-log-watcher:${RELEASE_VERSION} else - AGENT_IMAGE=registry-write.opensource.zalan.do/eagleeye/kubernetes-log-watcher:${CDP_BUILD_VERSION} + AGENT_IMAGE=registry-write.opensource.zalan.do/eagleeye/kubernetes-log-watcher-unstable:${CDP_BUILD_VERSION} fi docker build --tag "$AGENT_IMAGE" . docker push "$AGENT_IMAGE" diff --git a/kube_log_watcher/kube.py b/kube_log_watcher/kube.py index 73c1ffc..fbfc095 100644 --- a/kube_log_watcher/kube.py +++ b/kube_log_watcher/kube.py @@ -6,8 +6,6 @@ import warnings from urllib.parse import urljoin -from typing import Tuple - import pykube import requests @@ -15,13 +13,17 @@ import requests DEFAULT_SERVICE_ACC = '/var/run/secrets/kubernetes.io/serviceaccount' DEFAULT_NAMESPACE = 'default' -PODS_URL = 'api/v1/namespaces/{}/pods' +PODS_URL = 'api/v1/namespaces/{}/pods/{}' PAUSE_CONTAINER_PREFIX = 'gcr.io/google_containers/pause-' logger = logging.getLogger('kube_log_watcher') +class PodNotFound(Exception): + pass + + def update_ca_certificate(): warnings.warn('update_ca_certificate is deprecated.') try: @@ -40,39 +42,37 @@ def get_client(): return client -def get_pods(kube_url=None, namespace=DEFAULT_NAMESPACE) -> list: +def get_pod(name, namespace=DEFAULT_NAMESPACE, kube_url=None) -> pykube.Pod: """ - Return list of pods in cluster. + Return Pod with name. If ``kube_url`` is not ``None`` then kubernetes service account config won't be used. + :param name: Pod name to use in filtering. + :type name: str + + :param namespace: Desired namespace of the pod. Default namespace is ``default``. + :type namespace: str + :param kube_url: URL of a proxy to kubernetes cluster api. This is useful to offload authentication/authorization to proxy service instead of depending on serviceaccount config. Default is ``None``. :type kube_url: str - :param namespace: Desired namespace of the pods. Default namespace is ``default``. - :type namespace: str - - :return: List of pods. - :rtype: list + :return: The matching pod. + :rtype: pykube.Pod """ - if kube_url: - r = requests.get(urljoin(kube_url, PODS_URL.format(namespace))) - - r.raise_for_status() - - return r.json().get('items', []) - - kube_client = get_client() - return pykube.Pod.objects(kube_client).filter(namespace=namespace) + try: + if kube_url: + r = requests.get(urljoin(kube_url, PODS_URL.format(namespace, name))) + r.raise_for_status() -def get_pod_labels_annotations(pods: list, pod_name: str) -> Tuple[dict, dict]: - for pod in pods: - metadata = pod.obj['metadata'] if hasattr(pod, 'obj') else pod.get('metadata', {}) - if metadata.get('name') == pod_name: - return metadata.get('labels', {}), metadata.get('annotations', {}) + return r.json().get('items', [])[0] - return {}, {} + kube_client = get_client() + return list( + pykube.Pod.objects(kube_client).filter(namespace=namespace, field_selector={'metadata.name': name}))[0] + except Exception: + raise PodNotFound('Cannot find pod: {}'.format(name)) def is_pause_container(config: dict) -> bool: diff --git a/kube_log_watcher/main.py b/kube_log_watcher/main.py index d13ed51..16f6fd9 100644 --- a/kube_log_watcher/main.py +++ b/kube_log_watcher/main.py @@ -19,6 +19,9 @@ DEST_PATH = '/mnt/jobs/' APP_LABEL = 'application' VERSION_LABEL = 'version' +ANNOTATION_PREFIX = 'annotation.' +KUBERNETES_PREFIX = 'io.kubernetes.' + BUILTIN_AGENTS = { 'appdynamics': AppDynamicsAgent, 'scalyr': ScalyrAgent, @@ -32,7 +35,7 @@ logger.addHandler(logging.StreamHandler(stream=sys.stdout)) logger.setLevel(logging.INFO) -def get_label_value(config, label) -> str: +def get_container_label_value(config, label) -> str: """ Get label value from container config. Usually those labels are namespaced in the form: io.kubernetes.container.name @@ -188,10 +191,6 @@ def get_new_containers_log_targets( :return: List of existing container log targets. :rtype: list """ - pod_map = {} - - pod_map[kube.DEFAULT_NAMESPACE] = kube.get_pods(kube_url=kube_url) - containers_log_targets = [] for container in containers: @@ -200,21 +199,20 @@ def get_new_containers_log_targets( if kube.is_pause_container(config['Config']): # We have no interest in Pause containers. - logger.debug('Skipping pause container({})'.format(container['id'])) continue - pod_name = get_label_value(config, 'pod.name') - container_name = get_label_value(config, 'container.name') - pod_namespace = get_label_value(config, 'pod.namespace') + pod_name = get_container_label_value(config, 'pod.name') + container_name = get_container_label_value(config, 'container.name') + pod_namespace = get_container_label_value(config, 'pod.namespace') - pods = pod_map.get(pod_namespace) - if not pods: - # We need to get pods in different namespace - logger.debug('Retrieving pods in namespace: {}'.format(pod_namespace)) - pods = kube.get_pods(kube_url=kube_url, namespace=pod_namespace) - pod_map[pod_namespace] = pods + try: + pod = kube.get_pod(pod_name, namespace=pod_namespace, kube_url=kube_url) + except kube.PodNotFound: + logger.warning('Cannot find pod "{}" ... skipping container: {}'.format(pod_name, container_name)) + continue - pod_labels, pod_annotations = kube.get_pod_labels_annotations(pods, pod_name) + metadata = pod.obj['metadata'] + pod_labels, pod_annotations = metadata.get('labels', {}), metadata.get('annotations', {}) kwargs = {} @@ -243,6 +241,8 @@ def get_new_containers_log_targets( continue else: if not kwargs['application_id']: + logger.warning('Cannot determine application_id for pod: {}. Falling back to pod name!'.format( + pod_name)) kwargs['application_id'] = kwargs['pod_name'] containers_log_targets.append({'id': container['id'], 'kwargs': kwargs, 'pod_labels': pod_labels}) @@ -367,7 +367,3 @@ def main(): logger.info('\tInterval: {}'.format(interval)) watch(containers_path, agents, cluster_id, interval=interval, kube_url=kube_url, strict_labels=strict_labels) - - -if __name__ == '__main__': - main()
Scalyr: pod labels and annotations extraction fail The issue is inconsistent, but in some pods created by cronjobs, log-watcher fails to get the ``labels`` and ``annotations`` which lead to breaking custom parsing and log search based on ``application`` or ``version`` fields.
zalando-incubator/kubernetes-log-watcher
diff --git a/tests/conftest.py b/tests/conftest.py index 6d5ad6a..d4bd81f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -51,7 +51,10 @@ TARGET_INVALID_ANNOT['kwargs']['pod_annotations'] = {SCALYR_ANNOTATION_PARSER: ' { 'config': { 'Config': { - 'Labels': {'pod.name': 'pod-1', 'pod.namespace': 'default', 'container.name': 'cont-1'}, + 'Labels': { + 'io.kubernetes.pod.name': 'pod-1', 'pod.namespace': 'default', 'container.name': 'cont-1', + 'annotation.some-annotation': 'v1', + }, 'Image': 'repo/example.org/cont-1:1.1' } }, @@ -151,7 +154,7 @@ TARGET_INVALID_ANNOT['kwargs']['pod_annotations'] = {SCALYR_ANNOTATION_PARSER: ' 'log_file_path': '/mnt/containers/cont-5/cont-5-json.log', 'container_name': 'cont-5', 'pod_annotations': {}, 'image': 'cont-5', 'image_version': 'latest' } - } + }, ], # 4. targets no labels [ diff --git a/tests/test_kube.py b/tests/test_kube.py index 9d64467..3375e8c 100644 --- a/tests/test_kube.py +++ b/tests/test_kube.py @@ -2,7 +2,7 @@ import pytest from mock import MagicMock -from kube_log_watcher.kube import get_pods, is_pause_container, get_pod_labels_annotations, get_client +from kube_log_watcher.kube import get_pod, is_pause_container, get_client, PodNotFound from kube_log_watcher.kube import PAUSE_CONTAINER_PREFIX, DEFAULT_SERVICE_ACC @@ -52,36 +52,53 @@ def test_get_client(monkeypatch): @pytest.mark.parametrize('namespace', ('default', 'kube-system')) -def test_get_pods_url(monkeypatch, namespace): +def test_get_pod_url(monkeypatch, namespace): get = MagicMock() - res = [1, 2, 3] + res = [1] get.return_value.json.return_value = {'items': res} monkeypatch.setattr('requests.get', get) - result = get_pods(KUBE_URL, namespace=namespace) + result = get_pod('my-pod', namespace=namespace, kube_url=KUBE_URL) - assert res == result + assert res[0] == result - get.assert_called_with('https://my-kube-api/api/v1/namespaces/{}/pods'.format(namespace)) + get.assert_called_with('https://my-kube-api/api/v1/namespaces/{}/pods/my-pod'.format(namespace)) @pytest.mark.parametrize('namespace', ('default', 'kube-system')) -def test_get_pods_pykube(monkeypatch, namespace): +def test_get_pod_pykube(monkeypatch, namespace): get = MagicMock() pod = MagicMock() - res = [1, 2, 3] + res = [1] pod.objects.return_value.filter.return_value = res monkeypatch.setattr('kube_log_watcher.kube.get_client', get) monkeypatch.setattr('pykube.Pod', pod) - result = get_pods(namespace=namespace) + result = get_pod('my-pod', namespace=namespace) - assert res == result + assert res[0] == result get.assert_called_once() - pod.objects.return_value.filter.assert_called_with(namespace=namespace) + pod.objects.return_value.filter.assert_called_with(namespace=namespace, field_selector={'metadata.name': 'my-pod'}) + + [email protected]('namespace', ('default', 'kube-system')) +def test_get_pod_pykube_not_found(monkeypatch, namespace): + get = MagicMock() + pod = MagicMock() + res = [] + pod.objects.return_value.filter.return_value = res + + monkeypatch.setattr('kube_log_watcher.kube.get_client', get) + monkeypatch.setattr('pykube.Pod', pod) + + with pytest.raises(PodNotFound): + get_pod('my-pod', namespace=namespace) + + get.assert_called_once() + pod.objects.return_value.filter.assert_called_with(namespace=namespace, field_selector={'metadata.name': 'my-pod'}) @pytest.mark.parametrize( @@ -96,16 +113,3 @@ def test_get_pods_pykube(monkeypatch, namespace): ) def test_pause_container(monkeypatch, config, res): assert res == is_pause_container(config) - - [email protected]( - 'pod_name,res', - ( - ('pod-1', ({'app': 'app-1', 'version': 'v1'}, {'annotation/1': 'a1', 'annotation/2': 'a2'})), - ('pod-2', ({'app': 'app-2', 'version': 'v1'}, {})), - ('pod-3', (POD_OBJ.obj['metadata']['labels'], {'annotation/1': 'a1', 'annotation/2': 'a2'})), - ('pod-4', ({}, {})), - ) -) -def test_get_pod_labels_annotations(monkeypatch, pod_name, res): - assert get_pod_labels_annotations(PODS, pod_name) == res diff --git a/tests/test_main.py b/tests/test_main.py index 6c0f1e3..03c424a 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -4,9 +4,10 @@ import pytest from mock import MagicMock, call +from kube_log_watcher.kube import PodNotFound from kube_log_watcher.template_loader import load_template from kube_log_watcher.main import ( - get_label_value, get_containers, sync_containers_log_agents, get_stale_containers, load_agents, + get_container_label_value, get_containers, sync_containers_log_agents, get_stale_containers, load_agents, get_new_containers_log_targets, get_container_image_parts, watch) from .conftest import CLUSTER_ID @@ -26,6 +27,13 @@ CONTAINERS_PATH = '/mnt/containers/' DEST_PATH = '/mnt/jobs/' +def pod_mock(metadata): + pod = MagicMock() + pod.obj = metadata + + return pod + + @pytest.mark.parametrize('image, res', ( ('repo/image-1:0.1', ('image-1', '0.1')), ('', ('', 'latest')), @@ -51,8 +59,8 @@ def test_get_container_image_parts(monkeypatch, image, res): ('container.nam', None), ) ) -def test_get_label_value(monkeypatch, label, val): - assert val == get_label_value(CONFIG, label) +def test_get_container_label_value(monkeypatch, label, val): + assert val == get_container_label_value(CONFIG, label) @pytest.mark.parametrize( @@ -121,10 +129,10 @@ def test_get_containers(monkeypatch, walk, config, res, exc): def test_sync_containers_log_agents(monkeypatch, watched_containers, fx_containers_sync): containers, pods, targets, _, result = fx_containers_sync - get_pods = MagicMock() - get_pods.return_value = pods + get_pod = MagicMock() + get_pod.side_effect = pods - monkeypatch.setattr('kube_log_watcher.kube.get_pods', get_pods) + monkeypatch.setattr('kube_log_watcher.kube.get_pod', get_pod) monkeypatch.setattr('kube_log_watcher.main.CLUSTER_NODE_NAME', 'node-1') stale_containers = watched_containers - result @@ -159,13 +167,53 @@ def test_sync_containers_log_agents(monkeypatch, watched_containers, fx_containe agent2.remove_log_target.assert_has_calls(remove_calls, any_order=True) [email protected]( + 'watched_containers', + ( + set(), + {'cont-5'}, + {'cont-4'}, # stale + ) +) +def test_sync_containers_log_agents_failure(monkeypatch, watched_containers, fx_containers_sync): + containers, pods, targets, _, result = fx_containers_sync + + get_pod = MagicMock() + get_pod.side_effect = pods + + monkeypatch.setattr('kube_log_watcher.kube.get_pod', get_pod) + monkeypatch.setattr('kube_log_watcher.main.CLUSTER_NODE_NAME', 'node-1') + + stale_containers = watched_containers - result + if watched_containers: + result = result - watched_containers + targets = [t for t in targets if t['id'] not in watched_containers] + + get_targets = MagicMock() + get_targets.return_value = targets + get_stale = MagicMock() + get_stale.return_value = stale_containers + monkeypatch.setattr('kube_log_watcher.main.get_new_containers_log_targets', get_targets) + monkeypatch.setattr('kube_log_watcher.main.get_stale_containers', get_stale) + + agent1 = MagicMock() + agent2 = MagicMock() + agent1.add_log_target.side_effect, agent2.add_log_target.side_effect = Exception, RuntimeError + agents = [agent1, agent2] + + existing, stale = sync_containers_log_agents(agents, watched_containers, containers, CONTAINERS_PATH, CLUSTER_ID) + + assert existing == result + assert stale == stale_containers + + def test_get_new_containers_log_targets(monkeypatch, fx_containers_sync): containers, pods, result, _, _ = fx_containers_sync - get_pods = MagicMock() - get_pods.return_value = pods + get_pod = MagicMock() + get_pod.side_effect = [pod_mock(p) for p in pods] - monkeypatch.setattr('kube_log_watcher.kube.get_pods', get_pods) + monkeypatch.setattr('kube_log_watcher.kube.get_pod', get_pod) monkeypatch.setattr('kube_log_watcher.main.CLUSTER_NODE_NAME', 'node-1') targets = get_new_containers_log_targets(containers, CONTAINERS_PATH, CLUSTER_ID, strict_labels=True) @@ -173,15 +221,44 @@ def test_get_new_containers_log_targets(monkeypatch, fx_containers_sync): assert targets == result +def test_get_new_containers_log_targets_not_found_pods(monkeypatch, fx_containers_sync): + containers, pods, _, _, _ = fx_containers_sync + + get_pod = MagicMock() + get_pod.side_effect = PodNotFound + + monkeypatch.setattr('kube_log_watcher.kube.get_pod', get_pod) + monkeypatch.setattr('kube_log_watcher.main.CLUSTER_NODE_NAME', 'node-1') + + targets = get_new_containers_log_targets(containers, CONTAINERS_PATH, CLUSTER_ID, strict_labels=True) + + assert targets == [] + + +def test_get_new_containers_log_targets_failuer(monkeypatch, fx_containers_sync): + containers, pods, _, _, _ = fx_containers_sync + + is_pause = MagicMock() + is_pause.side_effect = Exception + + # Force exception + monkeypatch.setattr('kube_log_watcher.kube.is_pause_container', is_pause) + monkeypatch.setattr('kube_log_watcher.main.CLUSTER_NODE_NAME', 'node-1') + + targets = get_new_containers_log_targets(containers, CONTAINERS_PATH, CLUSTER_ID, strict_labels=True) + + assert targets == [] + + def test_get_new_containers_log_targets_no_strict_labels(monkeypatch, fx_containers_sync): containers, pods, result_labels, result_no_labels, _ = fx_containers_sync result = result_labels + result_no_labels - get_pods = MagicMock() - get_pods.return_value = pods + get_pod = MagicMock() + get_pod.side_effect = [pod_mock(p) for p in pods] - monkeypatch.setattr('kube_log_watcher.kube.get_pods', get_pods) + monkeypatch.setattr('kube_log_watcher.kube.get_pod', get_pod) monkeypatch.setattr('kube_log_watcher.main.CLUSTER_NODE_NAME', 'node-1') targets = get_new_containers_log_targets(containers, CONTAINERS_PATH, CLUSTER_ID)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 3 }
0.17
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest_cov", "mock", "codecov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc python3-dev libffi-dev libssl-dev" ], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backports.zoneinfo==0.2.1 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 coverage==6.2 httplib2==0.22.0 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 Jinja2==2.8 -e git+https://github.com/zalando-incubator/kubernetes-log-watcher.git@c13fd091c4bf2965eea26d4a9840c7669fbf2978#egg=kubernetes_log_watcher MarkupSafe==2.0.1 mock==5.2.0 oauth2client==4.1.3 oauthlib==3.2.2 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyasn1==0.5.1 pyasn1-modules==0.3.0 pykube==0.15.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytz-deprecation-shim==0.1.0.post0 PyYAML==6.0.1 requests==2.27.1 requests-oauthlib==2.0.0 rsa==4.9 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 tzdata==2025.2 tzlocal==4.2 urllib3==1.26.20 zipp==3.6.0
name: kubernetes-log-watcher channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backports-zoneinfo==0.2.1 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - httplib2==0.22.0 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jinja2==2.8 - markupsafe==2.0.1 - mock==5.2.0 - oauth2client==4.1.3 - oauthlib==3.2.2 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyasn1==0.5.1 - pyasn1-modules==0.3.0 - pykube==0.15.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytz-deprecation-shim==0.1.0.post0 - pyyaml==6.0.1 - requests==2.27.1 - requests-oauthlib==2.0.0 - rsa==4.9 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - tzdata==2025.2 - tzlocal==4.2 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/kubernetes-log-watcher
[ "tests/test_kube.py::test_get_client", "tests/test_kube.py::test_get_pod_url[default]", "tests/test_kube.py::test_get_pod_url[kube-system]", "tests/test_kube.py::test_get_pod_pykube[default]", "tests/test_kube.py::test_get_pod_pykube[kube-system]", "tests/test_kube.py::test_get_pod_pykube_not_found[default]", "tests/test_kube.py::test_get_pod_pykube_not_found[kube-system]", "tests/test_kube.py::test_pause_container[config0-True]", "tests/test_kube.py::test_pause_container[config1-True]", "tests/test_kube.py::test_pause_container[config2-False]", "tests/test_kube.py::test_pause_container[config3-False]", "tests/test_kube.py::test_pause_container[config4-False]", "tests/test_main.py::test_get_container_image_parts[repo/image-1:0.1-res0]", "tests/test_main.py::test_get_container_image_parts[-res1]", "tests/test_main.py::test_get_container_image_parts[image-1:0.1-res2]", "tests/test_main.py::test_get_container_image_parts[repo/image-1:0.1:0.2:0.3-res3]", "tests/test_main.py::test_get_container_image_parts[repo/:0.1-res4]", "tests/test_main.py::test_get_container_image_parts[repo/image-1-res5]", "tests/test_main.py::test_get_container_image_parts[repo/-res6]", "tests/test_main.py::test_get_container_image_parts[repo/vendor/project/image-1:0.1-alpha-1-res7]", "tests/test_main.py::test_get_container_label_value[pod.name-pod-name]", "tests/test_main.py::test_get_container_label_value[pod.namespace-default]", "tests/test_main.py::test_get_container_label_value[io.kubernetes.container.name-container-1]", "tests/test_main.py::test_get_container_label_value[container.nam-None]", "tests/test_main.py::test_get_containers[walk0-config0-res0-None]", "tests/test_main.py::test_get_containers[walk1-config1-res1-None]", "tests/test_main.py::test_get_containers[walk2-config2-res2-None]", "tests/test_main.py::test_get_containers[walk3-config3-res3-Exception]", "tests/test_main.py::test_sync_containers_log_agents[fx_containers_sync0-watched_containers0]", "tests/test_main.py::test_sync_containers_log_agents[fx_containers_sync0-watched_containers1]", "tests/test_main.py::test_sync_containers_log_agents[fx_containers_sync0-watched_containers2]", "tests/test_main.py::test_sync_containers_log_agents_failure[fx_containers_sync0-watched_containers0]", "tests/test_main.py::test_sync_containers_log_agents_failure[fx_containers_sync0-watched_containers1]", "tests/test_main.py::test_sync_containers_log_agents_failure[fx_containers_sync0-watched_containers2]", "tests/test_main.py::test_get_new_containers_log_targets[fx_containers_sync0]", "tests/test_main.py::test_get_new_containers_log_targets_not_found_pods[fx_containers_sync0]", "tests/test_main.py::test_get_new_containers_log_targets_failuer[fx_containers_sync0]", "tests/test_main.py::test_get_new_containers_log_targets_no_strict_labels[fx_containers_sync0]", "tests/test_main.py::test_get_stale_containers[watched0-existing0-result0]", "tests/test_main.py::test_get_stale_containers[watched1-existing1-result1]", "tests/test_main.py::test_get_stale_containers[watched2-existing2-result2]", "tests/test_main.py::test_load_agents", "tests/test_main.py::test_watch[True]", "tests/test_main.py::test_watch[False]", "tests/test_main.py::test_watch_failure[True]", "tests/test_main.py::test_watch_failure[False]" ]
[]
[]
[]
MIT License
2,627
[ "delivery.yaml", "kube_log_watcher/kube.py", "kube_log_watcher/main.py" ]
[ "delivery.yaml", "kube_log_watcher/kube.py", "kube_log_watcher/main.py" ]
youknowone__ring-80
33fd69eed378616ed031a0560e14007b6d43008a
2018-06-06 18:15:26
f1cda974388d715e2294bb8b073127d0d7e97f45
codecov[bot]: # [Codecov](https://codecov.io/gh/youknowone/ring/pull/80?src=pr&el=h1) Report > Merging [#80](https://codecov.io/gh/youknowone/ring/pull/80?src=pr&el=desc) into [master](https://codecov.io/gh/youknowone/ring/commit/33fd69eed378616ed031a0560e14007b6d43008a?src=pr&el=desc) will **decrease** coverage by `1.27%`. > The diff coverage is `100%`. ```diff @@ Coverage Diff @@ ## master #80 +/- ## ========================================== - Coverage 97.88% 96.61% -1.27% ========================================== Files 13 13 Lines 1084 1090 +6 ========================================== - Hits 1061 1053 -8 - Misses 23 37 +14 ```
diff --git a/ring/wire.py b/ring/wire.py index 069ec40..078cb04 100644 --- a/ring/wire.py +++ b/ring/wire.py @@ -56,10 +56,17 @@ class Wire(object): _shared_attrs = {'attrs': {}} - if is_method(cwrapper) or is_classmethod(cwrapper): + c_is_method = is_method(cwrapper) + c_is_classmethod = is_classmethod(cwrapper) + if c_is_method or c_is_classmethod: @WiredProperty def _w(self): - wrapper_name = '__wrapper_' + cwrapper.code.co_name + wrapper_name_parts = ['__wire_', cwrapper.code.co_name] + if c_is_classmethod: + self_cls = self if type(self) == type else type(self) # fragile + wrapper_name_parts.extend(('_', self_cls.__name__)) + self = self_cls + wrapper_name = ''.join(wrapper_name_parts) wrapper = getattr(self, wrapper_name, None) if wrapper is None: _wrapper = cls(cwrapper, _shared_attrs)
[BUG] It doesn't work for classmethod very well ~Even if "cls" is different in classmethod, Ring doesn't distinguish them~ Now cls is correctly passed to classmethod, but not about subclasses. Related test: https://github.com/youknowone/ring/blob/master/tests/test_key.py#L64
youknowone/ring
diff --git a/tests/test_key.py b/tests/test_key.py index bf08f0a..5f87fe4 100644 --- a/tests/test_key.py +++ b/tests/test_key.py @@ -1,3 +1,4 @@ +import six import ring from ring.key import FormatKey, CallableKey @@ -61,7 +62,22 @@ def test_classmethod_key(): pass assert A.f.key().endswith('.A.f:A'), A.f.key() - # assert B.f.key().endswith('.A.f:B'), B.f.key() -- TODO + if six.PY2: + assert B.f.key().endswith('.B.f:B'), B.f.key() + else: + assert B.f.key().endswith('.A.f:B'), B.f.key() + + a = A() + b = B() + + assert a.f.key().endswith('.A.f:A'), a.f.key() + if six.PY2: + assert b.f.key().endswith('.B.f:B'), b.f.key() + else: + assert b.f.key().endswith('.A.f:B'), b.f.key() + + assert A.f.key() == a.f.key() + assert B.f.key() == b.f.key() def test_unexisting_ring_key():
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "mock", "patch", "pymemcache", "redis" ], "pre_install": [ "apt-get update", "apt-get install -y gcc libmemcached-dev memcached redis-server" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 asgiref==3.4.1 async-timeout==4.0.2 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 diskcache==5.6.3 Django==3.2.25 docutils==0.18.1 idna==3.10 imagesize==1.4.1 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.0.3 MarkupSafe==2.0.1 mock==5.2.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work patch==1.16 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work prettyexc==0.6.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work Pygments==2.14.0 pymemcache==3.5.2 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-cov==4.0.0 pytest-lazy-fixture==0.6.3 pytz==2025.2 redis==4.3.6 requests==2.27.1 -e git+https://github.com/youknowone/ring.git@33fd69eed378616ed031a0560e14007b6d43008a#egg=ring six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 sqlparse==0.4.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work tomli==1.2.3 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: ring channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - asgiref==3.4.1 - async-timeout==4.0.2 - babel==2.11.0 - charset-normalizer==2.0.12 - coverage==6.2 - diskcache==5.6.3 - django==3.2.25 - docutils==0.18.1 - idna==3.10 - imagesize==1.4.1 - jinja2==3.0.3 - markupsafe==2.0.1 - mock==5.2.0 - patch==1.16 - prettyexc==0.6.0 - pygments==2.14.0 - pymemcache==3.5.2 - pytest-cov==4.0.0 - pytest-lazy-fixture==0.6.3 - pytz==2025.2 - redis==4.3.6 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlparse==0.4.4 - tomli==1.2.3 - urllib3==1.26.20 prefix: /opt/conda/envs/ring
[ "tests/test_key.py::test_classmethod_key" ]
[]
[ "tests/test_key.py::test_provider_keys[format_key]", "tests/test_key.py::test_provider_keys[callable_key]", "tests/test_key.py::test_key_build[format_key]", "tests/test_key.py::test_key_build[callable_key]", "tests/test_key.py::test_key_repr[format_key]", "tests/test_key.py::test_key_repr[callable_key]", "tests/test_key.py::test_callable_key", "tests/test_key.py::test_unexisting_ring_key", "tests/test_key.py::test_singleton[None]", "tests/test_key.py::test_singleton[v1]" ]
[]
BSD License
2,629
[ "ring/wire.py" ]
[ "ring/wire.py" ]
oasis-open__cti-python-stix2-187
d67f2da0ea839db464197f7da0f7991bdd774d1f
2018-06-06 19:42:25
3084c9f51fcd00cf6b0ed76827af90d0e86746d5
diff --git a/stix2/base.py b/stix2/base.py index 2afba16..9b5308f 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -185,7 +185,13 @@ class _STIXBase(collections.Mapping): # Handle attribute access just like key access def __getattr__(self, name): - if name in self: + # Pickle-proofing: pickle invokes this on uninitialized instances (i.e. + # __init__ has not run). So no "self" attributes are set yet. The + # usual behavior of this method reads an __init__-assigned attribute, + # which would cause infinite recursion. So this check disables all + # attribute reads until the instance has been properly initialized. + unpickling = "_inner" not in self.__dict__ + if not unpickling and name in self: return self.__getitem__(name) raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
Infinite recursion on _STIXBase object deserialization Hi! There seems to be a bug in the way the `__getitem__`/`__getattr__` functions are implemented in `_STIXBase` (_cti-python-stix2/stix2/base.py_). The bug can be reproduced by trying to serialize/deserialize an object instance, resulting in infinite recursion causing the program to terminate with a `RecursionError` once the max recursion depth is exceeded. Here is a short example with copy.copy() triggering the recursion: ``` import copy, stix2 indicator = stix2.Indicator(name="a", labels=["a"], pattern="[file:name = 'a']") copy.copy(indicator) ``` I believe this is because the unpickling tries to find the optional `__set_state__` method in `_STIXBase`. But since it's not there, the `__getattr__` is being called for it. However, the way `__getattr__` is implemented in the class, the `__getitem__` is called which tries to look up an item in `self._inner`. Due to the way the deserialization works in general, the object itself is empty and the `__init__` was never called - meaning that the `_inner` attribute was never set. The access attempt on the non-existent `_inner` however triggers a call to `__getattr__` again, resulting in the recursion. Here are two possible patches, I'm not sure though if that's the proper way of fixing it: 1) Checking for `_inner` access in `__getitem__`: ``` def __getitem__(self, key): if key == '_inner': raise KeyError return self._inner[key] ``` 2) Checking for protected attributes in `__getattr__`: ``` def __getattr__(self, name): if name.startswith('_'): raise AttributeError(name) if name in self: return self.__getitem__(name) raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) ``` Thanks!
oasis-open/cti-python-stix2
diff --git a/stix2/test/test_pickle.py b/stix2/test/test_pickle.py new file mode 100644 index 0000000..9e2cc9a --- /dev/null +++ b/stix2/test/test_pickle.py @@ -0,0 +1,17 @@ +import pickle + +import stix2 + + +def test_pickling(): + """ + Ensure a pickle/unpickle cycle works okay. + """ + identity = stix2.Identity( + id="identity--d66cb89d-5228-4983-958c-fa84ef75c88c", + name="alice", + description="this is a pickle test", + identity_class="some_class" + ) + + pickle.loads(pickle.dumps(identity))
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 antlr4-python3-runtime==4.9.3 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 backcall==0.2.0 bleach==4.1.0 bump2version==1.0.1 bumpversion==0.6.0 certifi==2021.5.30 cfgv==3.3.1 charset-normalizer==2.0.12 coverage==6.2 decorator==5.1.1 defusedxml==0.7.1 distlib==0.3.9 docutils==0.18.1 entrypoints==0.4 filelock==3.4.1 identify==2.4.4 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.2.3 iniconfig==1.1.1 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 jsonschema==3.2.0 jupyter-client==7.1.2 jupyter-core==4.9.2 jupyterlab-pygments==0.1.2 MarkupSafe==2.0.1 mistune==0.8.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nbsphinx==0.3.2 nest-asyncio==1.6.0 nodeenv==1.6.0 packaging==21.3 pandocfilters==1.5.1 parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 platformdirs==2.4.0 pluggy==1.0.0 pre-commit==2.17.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 pyzmq==25.1.2 requests==2.27.1 simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==1.5.6 sphinx-prompt==1.5.0 -e git+https://github.com/oasis-open/cti-python-stix2.git@d67f2da0ea839db464197f7da0f7991bdd774d1f#egg=stix2 stix2-patterns==2.0.0 testpath==0.6.0 toml==0.10.2 tomli==1.2.3 tornado==6.1 tox==3.28.0 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.16.2 wcwidth==0.2.13 webencodings==0.5.1 zipp==3.6.0
name: cti-python-stix2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - antlr4-python3-runtime==4.9.3 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - backcall==0.2.0 - bleach==4.1.0 - bump2version==1.0.1 - bumpversion==0.6.0 - cfgv==3.3.1 - charset-normalizer==2.0.12 - coverage==6.2 - decorator==5.1.1 - defusedxml==0.7.1 - distlib==0.3.9 - docutils==0.18.1 - entrypoints==0.4 - filelock==3.4.1 - identify==2.4.4 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.2.3 - iniconfig==1.1.1 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - jsonschema==3.2.0 - jupyter-client==7.1.2 - jupyter-core==4.9.2 - jupyterlab-pygments==0.1.2 - markupsafe==2.0.1 - mistune==0.8.4 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbsphinx==0.3.2 - nest-asyncio==1.6.0 - nodeenv==1.6.0 - packaging==21.3 - pandocfilters==1.5.1 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - platformdirs==2.4.0 - pluggy==1.0.0 - pre-commit==2.17.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - pyzmq==25.1.2 - requests==2.27.1 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==1.5.6 - sphinx-prompt==1.5.0 - stix2-patterns==2.0.0 - testpath==0.6.0 - toml==0.10.2 - tomli==1.2.3 - tornado==6.1 - tox==3.28.0 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.16.2 - wcwidth==0.2.13 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/cti-python-stix2
[ "stix2/test/test_pickle.py::test_pickling" ]
[]
[]
[]
BSD 3-Clause "New" or "Revised" License
2,631
[ "stix2/base.py" ]
[ "stix2/base.py" ]
pika__pika-1066
17aed0fa20f55ed3bc080320414badbb27046e8d
2018-06-06 22:49:26
4c904dea651caaf2a54b0fca0b9e908dec18a4f8
diff --git a/examples/consume.py b/examples/consume.py index da95d9e..7344149 100644 --- a/examples/consume.py +++ b/examples/consume.py @@ -1,17 +1,15 @@ +import functools +import logging import pika -def on_message(channel, method_frame, header_frame, body): - channel.queue_declare(queue=body, auto_delete=True) +LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' + '-35s %(lineno) -5d: %(message)s') +LOGGER = logging.getLogger(__name__) - if body.startswith("queue:"): - queue = body.replace("queue:", "") - key = body + "_key" - print("Declaring queue %s bound with key %s" %(queue, key)) - channel.queue_declare(queue=queue, auto_delete=True) - channel.queue_bind(queue=queue, exchange="test_exchange", routing_key=key) - else: - print("Message body", body) +logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT) +def on_message(channel, method_frame, header_frame, body, userdata=None): + LOGGER.info('Userdata: {} Message body: {}'.format(userdata, body)) channel.basic_ack(delivery_tag=method_frame.delivery_tag) credentials = pika.PlainCredentials('guest', 'guest') @@ -24,7 +22,8 @@ channel.queue_declare(queue="standard", auto_delete=True) channel.queue_bind(queue="standard", exchange="test_exchange", routing_key="standard_key") channel.basic_qos(prefetch_count=1) -channel.basic_consume(on_message, 'standard') +on_message_callback = functools.partial(on_message, userdata='on_message_userdata') +channel.basic_consume(on_message_callback, 'standard') try: channel.start_consuming() diff --git a/pika/heartbeat.py b/pika/heartbeat.py index c02d5df..8d3d20a 100644 --- a/pika/heartbeat.py +++ b/pika/heartbeat.py @@ -23,13 +23,22 @@ class HeartbeatChecker(object): :param pika.connection.Connection: Connection object :param int interval: Heartbeat check interval. Note: heartbeats will be sent at interval / 2 frequency. + :param int idle_count: The number of heartbeat intervals without data + received that will close the current connection. """ self._connection = connection + # Note: see the following document: # https://www.rabbitmq.com/heartbeats.html#heartbeats-timeout self._interval = float(interval / 2) - self._max_idle_count = idle_count + + # Note: even though we're sending heartbeats in half the specified + # interval, the broker will be sending them to us at the specified + # interval. This means we'll be checking for an idle connection + # twice as many times as the broker will send heartbeats to us, + # so we need to double the max idle count here + self._max_idle_count = idle_count * 2 # Initialize counters self._bytes_received = 0 @@ -82,9 +91,12 @@ class HeartbeatChecker(object): been idle too long. """ - LOGGER.debug('Received %i heartbeat frames, sent %i', + LOGGER.debug('Received %i heartbeat frames, sent %i, ' + 'idle intervals %i, max idle count %i', self._heartbeat_frames_received, - self._heartbeat_frames_sent) + self._heartbeat_frames_sent, + self._idle_byte_intervals, + self._max_idle_count) if self.connection_is_idle: return self._close_connection()
HeartbeatChecker is confused about heartbeat timeouts cc @lukebakken, the fix should probably be back-ported to the 0.12 release candidate. `HeartbeatChecker` constructor presently accepts an interval value and an `idle_count` which defaults to 2. `Connection` class instantiates `HeartbeatChecker` with `interval=hearbeat_timeout` and default `idle_count`. So, if the connection is configured with a heartbeat timeout of 600 (10 minutes), it will pass 600 as the `interval` arg to `HeartbeatChecker`. So, `HearbeatChecker` will emit heartbeats to the broker only once every 600 seconds. And it will detect heartbeat timeout after 1200 seconds. So, in the event that receipt of the heartbeat by the broker is slightly delayed (and in absence of any other AMQP frames from the client), the broker can erroneously conclude that connection with the client is lost and prematurely close the connection. This is clearly not what was intended. `HeartbeatChecker` should be detecting a heartbeat timeout after 600 seconds of inactivity. And it should be sending a heartbeat to the broker more often than just once within the heartbeat timeout window. I see two problems here: 1. Given `HeartbeatChecker`'s present interface, `Connection` should be instantiating it as`HeartbeatChecker(self, interval=float(self.params.heartbeat) / 2, idle_count=2) or something like that (how often does RabbitMQ broker send heartbeats within one heartbeat timeout interval?) 2. `HeartbeatChecker` is not abstracting the internals of heartbeat processing sufficiently. It's constructor should accept the heartbeat timeout value directly (no interval/idle_count business) and encapsulate the frequency of heartbeats internally without bleeding that detail to the `Connection`.
pika/pika
diff --git a/tests/unit/heartbeat_tests.py b/tests/unit/heartbeat_tests.py index fa97338..f0431c2 100644 --- a/tests/unit/heartbeat_tests.py +++ b/tests/unit/heartbeat_tests.py @@ -29,7 +29,7 @@ class HeartbeatTests(unittest.TestCase): self.assertEqual(self.obj._interval, self.HALF_INTERVAL) def test_default_initialization_max_idle_count(self): - self.assertEqual(self.obj._max_idle_count, self.obj.MAX_IDLE_COUNT) + self.assertEqual(self.obj._max_idle_count, self.obj.MAX_IDLE_COUNT * 2) def test_constructor_assignment_connection(self): self.assertIs(self.obj._connection, self.mock_conn)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock", "cryptography" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "test-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 codecov==2.1.13 coverage==7.8.0 cryptography==44.0.2 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 mock==5.2.0 nose==1.3.7 packaging==24.2 -e git+https://github.com/pika/pika.git@17aed0fa20f55ed3bc080320414badbb27046e8d#egg=pika pluggy==1.5.0 pycparser==2.22 pytest==8.3.5 requests==2.32.3 tomli==2.2.1 tornado==6.4.2 Twisted==15.3.0 urllib3==2.3.0 zope.interface==7.2
name: pika channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - codecov==2.1.13 - coverage==7.8.0 - cryptography==44.0.2 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pycparser==2.22 - pytest==8.3.5 - requests==2.32.3 - tomli==2.2.1 - tornado==6.4.2 - twisted==15.3.0 - urllib3==2.3.0 - zope-interface==7.2 prefix: /opt/conda/envs/pika
[ "tests/unit/heartbeat_tests.py::HeartbeatTests::test_default_initialization_max_idle_count" ]
[]
[ "tests/unit/heartbeat_tests.py::HeartbeatTests::test_active_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_active_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_bytes_received_on_connection", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_close", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_is_idle_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_is_idle_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_assignment_connection", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_assignment_heartbeat_interval", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_called_setup_timer", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_bytes_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_bytes_sent", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_heartbeat_frames_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_heartbeat_frames_sent", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_idle_byte_intervals", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_default_initialization_interval", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_has_received_data_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_has_received_data_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_new_heartbeat_frame", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_increment_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_increment_no_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_missed_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_not_closed", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_send_heartbeat_frame", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_start_timer", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_update_counters", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_heartbeat_counter_incremented", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_heartbeat_send_frame_called", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_setup_timer_called", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_start_timer_active", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_start_timer_not_active", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_update_counters_bytes_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_update_counters_bytes_sent" ]
[]
BSD 3-Clause "New" or "Revised" License
2,632
[ "examples/consume.py", "pika/heartbeat.py" ]
[ "examples/consume.py", "pika/heartbeat.py" ]
pika__pika-1067
e1f0ef51de293395392bd3d28dba4262a61fbc98
2018-06-06 23:14:54
4c904dea651caaf2a54b0fca0b9e908dec18a4f8
diff --git a/examples/consume.py b/examples/consume.py index 2254cd1..e4f86de 100644 --- a/examples/consume.py +++ b/examples/consume.py @@ -6,7 +6,7 @@ LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' '-35s %(lineno) -5d: %(message)s') LOGGER = logging.getLogger(__name__) -logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) +logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT) def on_message(channel, method_frame, header_frame, body, userdata=None): LOGGER.info('Userdata: {} Message body: {}'.format(userdata, body)) diff --git a/pika/heartbeat.py b/pika/heartbeat.py index 3c9f46f..73a6df8 100644 --- a/pika/heartbeat.py +++ b/pika/heartbeat.py @@ -24,13 +24,22 @@ class HeartbeatChecker(object): :param pika.connection.Connection: Connection object :param int interval: Heartbeat check interval. Note: heartbeats will be sent at interval / 2 frequency. + :param int idle_count: The number of heartbeat intervals without data + received that will close the current connection. """ self._connection = connection + # Note: see the following document: # https://www.rabbitmq.com/heartbeats.html#heartbeats-timeout self._interval = float(interval / 2) - self._max_idle_count = idle_count + + # Note: even though we're sending heartbeats in half the specified + # interval, the broker will be sending them to us at the specified + # interval. This means we'll be checking for an idle connection + # twice as many times as the broker will send heartbeats to us, + # so we need to double the max idle count here + self._max_idle_count = idle_count * 2 # Initialize counters self._bytes_received = 0 @@ -83,9 +92,12 @@ class HeartbeatChecker(object): been idle too long. """ - LOGGER.debug('Received %i heartbeat frames, sent %i', + LOGGER.debug('Received %i heartbeat frames, sent %i, ' + 'idle intervals %i, max idle count %i', self._heartbeat_frames_received, - self._heartbeat_frames_sent) + self._heartbeat_frames_sent, + self._idle_byte_intervals, + self._max_idle_count) if self.connection_is_idle: self._close_connection()
HeartbeatChecker is confused about heartbeat timeouts cc @lukebakken, the fix should probably be back-ported to the 0.12 release candidate. `HeartbeatChecker` constructor presently accepts an interval value and an `idle_count` which defaults to 2. `Connection` class instantiates `HeartbeatChecker` with `interval=hearbeat_timeout` and default `idle_count`. So, if the connection is configured with a heartbeat timeout of 600 (10 minutes), it will pass 600 as the `interval` arg to `HeartbeatChecker`. So, `HearbeatChecker` will emit heartbeats to the broker only once every 600 seconds. And it will detect heartbeat timeout after 1200 seconds. So, in the event that receipt of the heartbeat by the broker is slightly delayed (and in absence of any other AMQP frames from the client), the broker can erroneously conclude that connection with the client is lost and prematurely close the connection. This is clearly not what was intended. `HeartbeatChecker` should be detecting a heartbeat timeout after 600 seconds of inactivity. And it should be sending a heartbeat to the broker more often than just once within the heartbeat timeout window. I see two problems here: 1. Given `HeartbeatChecker`'s present interface, `Connection` should be instantiating it as`HeartbeatChecker(self, interval=float(self.params.heartbeat) / 2, idle_count=2) or something like that (how often does RabbitMQ broker send heartbeats within one heartbeat timeout interval?) 2. `HeartbeatChecker` is not abstracting the internals of heartbeat processing sufficiently. It's constructor should accept the heartbeat timeout value directly (no interval/idle_count business) and encapsulate the frequency of heartbeats internally without bleeding that detail to the `Connection`.
pika/pika
diff --git a/tests/unit/heartbeat_tests.py b/tests/unit/heartbeat_tests.py index eaf339f..1cb1160 100644 --- a/tests/unit/heartbeat_tests.py +++ b/tests/unit/heartbeat_tests.py @@ -73,7 +73,7 @@ class HeartbeatTests(unittest.TestCase): self.assertEqual(self.obj._interval, self.HALF_INTERVAL) def test_default_initialization_max_idle_count(self): - self.assertEqual(self.obj._max_idle_count, self.obj.MAX_IDLE_COUNT) + self.assertEqual(self.obj._max_idle_count, self.obj.MAX_IDLE_COUNT * 2) def test_constructor_assignment_connection(self): self.assertIs(self.obj._connection, self.mock_conn)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "test-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 Automat==24.8.1 certifi==2025.1.31 charset-normalizer==3.4.1 codecov==2.1.13 constantly==23.10.4 coverage==7.8.0 exceptiongroup==1.2.2 hyperlink==21.0.0 idna==3.10 incremental==24.7.2 iniconfig==2.1.0 mock==5.2.0 nose==1.3.7 packaging==24.2 -e git+https://github.com/pika/pika.git@e1f0ef51de293395392bd3d28dba4262a61fbc98#egg=pika pluggy==1.5.0 pytest==8.3.5 requests==2.32.3 tomli==2.2.1 tornado==6.4.2 Twisted==24.11.0 typing_extensions==4.13.0 urllib3==2.3.0 zope.interface==7.2
name: pika channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - automat==24.8.1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - codecov==2.1.13 - constantly==23.10.4 - coverage==7.8.0 - exceptiongroup==1.2.2 - hyperlink==21.0.0 - idna==3.10 - incremental==24.7.2 - iniconfig==2.1.0 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - requests==2.32.3 - tomli==2.2.1 - tornado==6.4.2 - twisted==24.11.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - zope-interface==7.2 prefix: /opt/conda/envs/pika
[ "tests/unit/heartbeat_tests.py::HeartbeatTests::test_default_initialization_max_idle_count" ]
[]
[ "tests/unit/heartbeat_tests.py::HeartbeatTests::test_active_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_active_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_bytes_received_on_connection", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_close", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_is_idle_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_connection_is_idle_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_assignment_connection", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_assignment_heartbeat_interval", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_called_setup_timer", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_bytes_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_bytes_sent", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_heartbeat_frames_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_heartbeat_frames_sent", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_constructor_initial_idle_byte_intervals", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_default_initialization_interval", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_has_received_data_false", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_has_received_data_true", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_new_heartbeat_frame", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_increment_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_increment_no_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_missed_bytes", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_not_closed", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_send_heartbeat_frame", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_start_timer", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_and_check_update_counters", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_heartbeat_counter_incremented", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_send_heartbeat_send_frame_called", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_setup_timer_called", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_start_timer_active", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_start_timer_not_active", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_update_counters_bytes_received", "tests/unit/heartbeat_tests.py::HeartbeatTests::test_update_counters_bytes_sent" ]
[]
BSD 3-Clause "New" or "Revised" License
2,633
[ "examples/consume.py", "pika/heartbeat.py" ]
[ "examples/consume.py", "pika/heartbeat.py" ]
PlasmaPy__PlasmaPy-491
984c7a1e83f948c715c673d5ae6f5f9defff5866
2018-06-07 04:28:34
24113f1659d809930288374f6b1f95dc573aff47
diff --git a/docs/physics/index.rst b/docs/physics/index.rst index ecf12287..342c187e 100644 --- a/docs/physics/index.rst +++ b/docs/physics/index.rst @@ -24,6 +24,7 @@ We thus have: distribution quantum relativity + magnetostatics The subpackage makes heavy use of `astropy.units.Quantity` for handling conversions between different unit systems. This is especially important for electron volts, commonly used in plasma physics to denote temperature, although diff --git a/docs/physics/magnetostatics.rst b/docs/physics/magnetostatics.rst new file mode 100644 index 00000000..4682bce5 --- /dev/null +++ b/docs/physics/magnetostatics.rst @@ -0,0 +1,11 @@ +.. _magnetostatics: + +************************************************** +Magnetostatics (`plasmapy.physics.magnetostatics`) +************************************************** + +.. currentmodule:: plasmapy.physics.magnetostatics + +.. automodapi:: plasmapy.physics.magnetostatics + :no-heading: + diff --git a/plasmapy/classes/sources/plasma3d.py b/plasmapy/classes/sources/plasma3d.py index a2789cb1..24fcab63 100644 --- a/plasmapy/classes/sources/plasma3d.py +++ b/plasmapy/classes/sources/plasma3d.py @@ -5,6 +5,9 @@ import numpy as np import astropy.units as u +import itertools + +from plasmapy.physics.magnetostatics import MagnetoStatics from plasmapy.constants import (m_p, m_e, @@ -115,3 +118,13 @@ def is_datasource_for(cls, **kwargs): else: match = False return match + + def add_magnetostatic(self, *mstats: MagnetoStatics): + # for each MagnetoStatic argument + for mstat in mstats: + # loop over 3D-index (ix,iy,iz) + for point_index in itertools.product(*[list(range(n)) for n in self.domain_shape]): + # get coordinate + p = self.grid[(slice(None),)+point_index] # function as [:, *index] + # calculate magnetic field at this point and add back + self.magnetic_field[(slice(None),)+point_index] += mstat.magnetic_field(p) diff --git a/plasmapy/examples/plot_magnetic_statics.py b/plasmapy/examples/plot_magnetic_statics.py new file mode 100644 index 00000000..5e5631fd --- /dev/null +++ b/plasmapy/examples/plot_magnetic_statics.py @@ -0,0 +1,110 @@ +# coding: utf-8 +""" +Magnetostatic Fields +===================== + +An example of using PlasmaPy's `Magnetostatic` class in `physics` subpackage. +""" + +import plasmapy as pp +from plasmapy.physics import magnetostatics +from plasmapy.classes.sources import Plasma3D +import numpy as np +import astropy.units as u +import matplotlib.pyplot as plt +import itertools + +############################################################ +# Some common magnetostatic fields can be generated and added to a plasma object. +# A dipole + +dipole = magnetostatics.MagneticDipole(np.array([0, 0, 1])*u.A*u.m*u.m, np.array([0, 0, 0])*u.m) +print(dipole) + +############################################################ +# initialize a a plasma, where the magnetic field will be calculated on + +plasma = Plasma3D(domain_x=np.linspace(-2, 2, 30) * u.m, + domain_y=np.linspace(0, 0, 1) * u.m, + domain_z=np.linspace(-2, 2, 20) * u.m) + +############################################################ +# add the dipole field to it +plasma.add_magnetostatic(dipole) + +X, Z = plasma.grid[0, :, 0, :], plasma.grid[2, :, 0, :] +U = plasma.magnetic_field[0, :, 0, :].value.T # because grid uses 'ij' indexing +W = plasma.magnetic_field[2, :, 0, :].value.T # because grid uses 'ij' indexing + + +############################################################ +plt.figure() +plt.axis('square') +plt.xlim(-2, 2) +plt.ylim(-2, 2) +plt.title('Dipole field in x-z plane, generated by a dipole pointing in the z direction') +plt.streamplot(plasma.x.value, plasma.z.value, U, W) + +############################################################ +# A circular current-carring wire + +cw = magnetostatics.CircularWire(np.array([0, 0, 1]), np.array([0, 0, 0])*u.m, 1*u.m, 1*u.A) +print(cw) + +############################################################ +# initialize a a plasma, where the magnetic field will be calculated on +plasma = Plasma3D(domain_x=np.linspace(-2, 2, 30) * u.m, + domain_y=np.linspace(0, 0, 1) * u.m, + domain_z=np.linspace(-2, 2, 20) * u.m) + +############################################################ +# add the circular coil field to it +plasma.add_magnetostatic(cw) + +X, Z = plasma.grid[0, :, 0, :], plasma.grid[2, :, 0, :] +U = plasma.magnetic_field[0, :, 0, :].value.T # because grid uses 'ij' indexing +W = plasma.magnetic_field[2, :, 0, :].value.T # because grid uses 'ij' indexing + +plt.figure() +plt.axis('square') +plt.xlim(-2, 2) +plt.ylim(-2, 2) +plt.title('Circular coil field in x-z plane, generated by a circular coil in the x-y plane') +plt.streamplot(plasma.x.value, plasma.z.value, U, W) + +############################################################ +# a circular wire can be described as parametric equation and converted to GeneralWire + +gw_cw = cw.to_GeneralWire() + +# the calculated magnetic field is close +print(gw_cw.magnetic_field([0, 0, 0]) - cw.magnetic_field([0, 0, 0])) + + +############################################################ +# A infinite straight wire + + +iw = magnetostatics.InfiniteStraightWire(np.array([0, 1, 0]), np.array([0, 0, 0])*u.m, 1*u.A) +print(iw) + +############################################################ +# initialize a a plasma, where the magnetic field will be calculated on +plasma = Plasma3D(domain_x=np.linspace(-2, 2, 30) * u.m, + domain_y=np.linspace(0, 0, 1) * u.m, + domain_z=np.linspace(-2, 2, 20) * u.m) + +# add the infinite straight wire field to it +plasma.add_magnetostatic(iw) + +X, Z = plasma.grid[0, :, 0, :], plasma.grid[2, :, 0, :] +U = plasma.magnetic_field[0, :, 0, :].value.T # because grid uses 'ij' indexing +W = plasma.magnetic_field[2, :, 0, :].value.T # because grid uses 'ij' indexing + +plt.figure() +plt.title('Dipole field in x-z plane, generated by a infinite straight wire ' + 'pointing in the y direction') +plt.axis('square') +plt.xlim(-2, 2) +plt.ylim(-2, 2) +plt.streamplot(plasma.x.value, plasma.z.value, U, W) diff --git a/plasmapy/physics/__init__.py b/plasmapy/physics/__init__.py index ce6cbd9d..05d2a29b 100644 --- a/plasmapy/physics/__init__.py +++ b/plasmapy/physics/__init__.py @@ -36,3 +36,5 @@ from .relativity import Lorentz_factor from . import transport + +from . import magnetostatics diff --git a/plasmapy/physics/magnetostatics.py b/plasmapy/physics/magnetostatics.py new file mode 100644 index 00000000..9bfda4a6 --- /dev/null +++ b/plasmapy/physics/magnetostatics.py @@ -0,0 +1,421 @@ +""" +Define MagneticStatics class to calculate common static magnetic fields +as first raised in issue #100. +""" + +import abc + +import numpy as np +from astropy import units as u, constants +from scipy.special import roots_legendre + + +class MagnetoStatics(abc.ABC): + """Abstract class for all kinds of magnetic static fields""" + + @abc.abstractmethod + def magnetic_field(self, p: u.m) -> u.T: + """ + Calculate magnetic field generated by this wire at position `p` + + Parameters + ---------- + p : `astropy.units.Quantity` + three-dimensional position vector + + Returns + ------- + B : `astropy.units.Quantity` + magnetic field at the specified positon + + """ + + +class MagneticDipole(MagnetoStatics): + """ + Simple magnetic dipole - two nearby opposite point charges. + + Parameters + ---------- + moment: `astropy.units.Quantity` + Magnetic moment vector, in units of A * m^2 + p0: `astropy.units.Quantity` + Position of the dipole + + """ + + @u.quantity_input() + def __init__(self, moment: u.A * u.m**2, p0: u.m): + self.moment = moment.to(u.A*u.m*u.m).value + self.p0 = p0.to(u.m).value + + def __repr__(self): + return "{name}(moment={moment}, p0={p0})".format( + name=self.__class__.__name__, + moment=self.moment, + p0=self.p0 + ) + + def magnetic_field(self, p: u.m) -> u.T: + r""" + Calculate magnetic field generated by this wire at position `p` + + Parameters + ---------- + p : `astropy.units.Quantity` + three-dimensional position vector + + Returns + ------- + B : `astropy.units.Quantity` + magnetic field at the specified positon + + """ + r = p - self.p0 + m = self.moment + B = constants.mu0.value/4/np.pi \ + * (3*r*np.dot(m, r)/np.linalg.norm(r)**5 - m/np.linalg.norm(r)**3) + return B*u.T + + +class Wire(MagnetoStatics): + """Abstract wire class for concrete wires to be inherited from.""" + + +class GeneralWire(Wire): + r""" + General wire class described by its parametric vector equation + + Parameters + ---------- + parametric_eq: Callable + A vector-valued (with units of position) function of a single real + parameter. + t1: float + lower bound of the parameter, smaller than t2 + t2: float + upper bound of the parameter, larger than t1 + current: `astropy.units.Quantity` + electric current + + """ + + @u.quantity_input() + def __init__(self, parametric_eq, + t1, + t2, + current: + u.A): + if callable(parametric_eq): + self.parametric_eq = parametric_eq + else: + raise ValueError("Argument parametric_eq should be a callable") + if t1 < t2: + self.t1 = t1 + self.t2 = t2 + else: + raise ValueError(f"t1={t1} is not smaller than t2={t2}") + self.current = current.to(u.A).value + + def magnetic_field(self, p: u.m, n: int = 1000) -> u.T: + r""" + Calculate magnetic field generated by this wire at position `p` + + Parameters + ---------- + p : `astropy.units.Quantity` + three-dimensional position vector + n : int, optional + Number of segments for Wire calculation + (defaults to 1000) + + Returns + ------- + B : `astropy.units.Quantity` + magnetic field at the specified positon + + Notes + ----- + For simplicity, we segment the wire into n equal pieces, + and assume each segment is straight. Default n is 1000. + + .. math:: + + \vec B + \approx \frac{\mu_0 I}{4\pi} \sum_{i=1}^{n} + \frac{[\vec l(t_{i}) - \vec l(t_{i-1})] \times + \left[\vec p - \frac{\vec l(t_{i}) + \vec l(t_{i-1})}{2}\right]} + {\left|\vec p - \frac{\vec l(t_{i}) + \vec l(t_{i-1})}{2}\right|^3}, + \quad \text{where}\, t_i = t_{\min}+i/n*(t_{\max}-t_{\min}) + + """ + + p1 = self.parametric_eq(self.t1) + step = (self.t2 - self.t1) / n + t = self.t1 + B = 0 + for i in range(n): + t = t + step + p2 = self.parametric_eq(t) + dl = p2 - p1 + p1 = p2 + R = p - (p2 + p1) / 2 + B += np.cross(dl, R)/np.linalg.norm(R)**3 + B = B*constants.mu0.value/4/np.pi*self.current + return B*u.T + + +class FiniteStraightWire(Wire): + """ + Finite length straight wire class. + + p1 to p2 direction is the possitive current direction. + + Parameters + ---------- + p1: `astropy.units.Quantity` + three-dimensional Cartesian coordinate of one end of the straight wire + p2: `astropy.units.Quantity` + three-dimensional Cartesian coordinate of another end of the straight wire + current: `astropy.units.Quantity` + electric current + + """ + + @u.quantity_input() + def __init__(self, p1: u.m, p2: u.m, current: u.A): + self.p1 = p1.to(u.m).value + self.p2 = p2.to(u.m).value + if np.all(p1 == p2): + raise ValueError("p1, p2 should not be the same point.") + self.current = current.to(u.A).value + + def __repr__(self): + return "{name}(p1={p1}, p2={p2}, current={current})".format( + name=self.__class__.__name__, + p1=self.p1, + p2=self.p2, + current=self.current + ) + + def magnetic_field(self, p) -> u.T: + r""" + Calculate magnetic field generated by this wire at position `p` + + Parameters + ---------- + p : `astropy.units.Quantity` + three-dimensional position vector + + Returns + ------- + B : `astropy.units.Quantity` + magnetic field at the specified positon + + Notes + ----- + Let :math:`P_f` be the foot of perpendicular, :math:`\theta_1`(:math:`\theta_2`) be the + angles between :math:`\overrightarrow{PP_1}`(:math:`\overrightarrow{PP_2}`) + and :math:`\overrightarrow{P_2P_1}`. + + .. math: + \vec B = \frac{(\overrightarrow{P_2P_1}\times\overrightarrow{PP_f})^0} + {|\overrightarrow{PP_f}|} + \frac{\mu_0 I}{4\pi} (\cos\theta_1 - \cos\theta_2) + + """ + # foot of perpendicular + p1, p2 = self.p1, self.p2 + p2_p1 = p2 - p1 + ratio = np.dot(p - p1, p2_p1)/np.dot(p2_p1, p2_p1) + pf = p1 + p2_p1*ratio + + # angles: theta_1 = <p - p1, p2 - p1>, theta_2 = <p - p2, p2 - p1> + cos_theta_1 = np.dot(p - p1, p2_p1)/np.linalg.norm(p - p1)/np.linalg.norm(p2_p1) + cos_theta_2 = np.dot(p - p2, p2_p1)/np.linalg.norm(p - p2)/np.linalg.norm(p2_p1) + + B_unit = np.cross(p2_p1, p - pf) + B_unit = B_unit/np.linalg.norm(B_unit) + + B = B_unit/np.linalg.norm(p-pf)*(cos_theta_1 - cos_theta_2) \ + * constants.mu0.value/4/np.pi*self.current + + return B*u.T + + def to_GeneralWire(self): + """Convert this `Wire` into a `GeneralWire`.""" + p1, p2 = self.p1, self.p2 + return GeneralWire(lambda t: p1+(p2-p1)*t, 0, 1, self.current*u.A) + + +class InfiniteStraightWire(Wire): + """ + Infinite straight wire class. + + Parameters + ---------- + direction: + three-dimensional direction vector of the wire, also the positive current direction + p0: `astropy.units.Quantity` + one point on the wire + current: `astropy.units.Quantity` + electric current + + """ + + @u.quantity_input() + def __init__(self, direction, p0: u.m, current: u.A): + self.direction = direction/np.linalg.norm(direction) + self.p0 = p0.to(u.m).value + self.current = current.to(u.A).value + + def __repr__(self): + return "{name}(direction={direction}, p0={p0}, current={current})".format( + name=self.__class__.__name__, + direction=self.direction, + p0=self.p0, + current=self.current + ) + + def magnetic_field(self, p) -> u.T: + r""" + Calculate magnetic field generated by this wire at position `p` + + Parameters + ---------- + p : `astropy.units.Quantity` + three-dimensional position vector + + Returns + ------- + B : `astropy.units.Quantity` + magnetic field at the specified positon + + Notes + ----- + .. math: + \vec B = \frac{\mu_0 I}{2\pi r}*(\vec l^0\times \vec{PP_0})^0, + \text{where}\, \vec l^0\, \text{is the unit vector of current direction}, + r\, \text{is the perpendicular distance between} P_0 \text{and the infinite wire} + + """ + r = np.cross(self.direction, p - self.p0) + B_unit = r / np.linalg.norm(r) + r = np.linalg.norm(r) + + return B_unit/r*constants.mu0.value/2/np.pi*self.current*u.T + + +class CircularWire(Wire): + """ + Circular wire(coil) class + + Parameters + ---------- + normal: + three-dimensional normal vector of the circular coil + center: `astropy.units.Quantity` + three-dimensional position vector of the circular coil's center + radius: `astropy.units.Quantity` + radius of the circular coil + current: `astropy.units.Quantity` + electric current + + """ + + @u.quantity_input() + def __init__(self, normal, center: u.m, radius: u.m, + current: u.A, n=300): + self.normal = normal/np.linalg.norm(normal) + self.center = center.to(u.m).value + if radius > 0: + self.radius = radius.to(u.m).value + else: + raise ValueError("Radius should bu larger than 0") + self.current = current.to(u.A).value + + # parametric equation + # find other two axises in the disc plane + z = np.array([0, 0, 1]) + axis_x = np.cross(z, self.normal) + axis_y = np.cross(self.normal, axis_x) + + if np.linalg.norm(axis_x) == 0: + axis_x = np.array([1, 0, 0]) + axis_y = np.array([0, 1, 0]) + else: + axis_x = axis_x/np.linalg.norm(axis_x) + axis_y = axis_y/np.linalg.norm(axis_y) + + self.axis_x = axis_x + self.axis_y = axis_y + + def curve(t): + if isinstance(t, np.ndarray): + t = np.expand_dims(t, 0) + axis_x_mat = np.expand_dims(axis_x, 1) + axis_y_mat = np.expand_dims(axis_y, 1) + return self.radius*(np.matmul(axis_x_mat, np.cos(t)) + + np.matmul(axis_y_mat, np.sin(t))) \ + + np.expand_dims(self.center, 1) + else: + return self.radius*(np.cos(t)*axis_x + np.sin(t)*axis_y) + self.center + self.curve = curve + + self.roots_legendre = roots_legendre(n) + self.n = n + + def __repr__(self): + return "{name}(normal={normal}, center={center}, \ +radius={radius}, current={current})".format( + name=self.__class__.__name__, + normal=self.normal, + center=self.center, + radius=self.radius, + current=self.current + ) + + def magnetic_field(self, p) -> u.T: + r""" + Calculate magnetic field generated by this wire at position `p` + + Parameters + ---------- + p : `astropy.units.Quantity` + three-dimensional position vector + + Returns + ------- + B : `astropy.units.Quantity` + magnetic field at the specified positon + + Notes + ----- + .. math: + \vec B + = \frac{\mu_0 I}{4\pi} + \int \frac{d\vec l\times(\vec p - \vec l(t))}{|\vec p - \vec l(t)|^3}\\ + = \frac{\mu_0 I}{4\pi} \int_{-\pi}^{\pi} {(-r\sin\theta \hat x + r\cos\theta \hat y)} + \times \frac{\vec p - \vec l(t)}{|\vec p - \vec l(t)|^3} d\theta + + We use n points Gauss-Legendre quadrature to compute the integral. The default n is 300. + + """ + + x, w = self.roots_legendre + t = x*np.pi + pt = self.curve(t) + dl = self.radius*( + - np.matmul(np.expand_dims(self.axis_x, 1), np.expand_dims(np.sin(t), 0)) + + np.matmul(np.expand_dims(self.axis_y, 1), np.expand_dims(np.cos(t), 0))) # (3, n) + + r = np.expand_dims(p, 1) - pt # (3, n) + r_norm_3 = np.linalg.norm(r, axis=0)**3 + ft = np.cross(dl, r, axisa=0, axisb=0)/np.expand_dims(r_norm_3, 1) # (n, 3) + + return np.pi*np.matmul(np.expand_dims(w, 0), ft).squeeze(0) \ + * constants.mu0.value/4/np.pi*self.current*u.T + + def to_GeneralWire(self): + """Convert this `Wire` into a `GeneralWire`.""" + return GeneralWire(self.curve, -np.pi, np.pi, self.current*u.A) diff --git a/setup.cfg b/setup.cfg index 504ccf85..fc4a9ff7 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,7 +1,7 @@ [metadata] package_name = plasmapy -description = "Python package for plasma physics" -long_description = "PlasmaPy is a community-developed and community-driven Python package for plasma physics." +description = Python package for plasma physics +long_description = PlasmaPy is a community-developed and community-driven generalist Python package for plasma physics tools. author = PlasmaPy Community license = BSD 3-Clause url = http://www.plasmapy.org @@ -9,10 +9,9 @@ edit_on_github = True github_project = PlasmaPy/PlasmaPy # install_requires should be formatted as a comma-separated list, e.g.: # install_requires = astropy, scipy, matplotlib -setup_requires = numpy -install_requires = numpy, scipy, astropy, cython, lmfit, matplotlib, pytest, colorama, roman, mpmath +install_requires = numpy, scipy, astropy, cython, lmfit, matplotlib, colorama, roman, mpmath # version should be PEP386 compatible (http://www.python.org/dev/peps/pep-0386) -version = 0.1.1 +version = 0.1.1.dev [build_sphinx] source-dir = docs diff --git a/setup.py b/setup.py index 780eb6db..46c9ca79 100644 --- a/setup.py +++ b/setup.py @@ -23,6 +23,7 @@ from astropy_helpers.setup_helpers import (register_commands, get_debug_option, get_package_info) +from astropy_helpers.distutils_helpers import is_distutils_display_option from astropy_helpers.git_helpers import get_git_devstr from astropy_helpers.version_helpers import generate_version_py @@ -124,6 +125,18 @@ os.path.relpath(root, PACKAGENAME), filename)) package_info['package_data'][PACKAGENAME].extend(c_files) +setup_requires = ['numpy'] + +# Make sure to have the packages needed for building PlasmaPy, but do not require them +# when installing from an sdist as the c files are included there. +if not os.path.exists(os.path.join(os.path.dirname(__file__), 'PKG-INFO')): + setup_requires.extend(['cython>=0.27.2']) + +# Avoid installing setup_requires dependencies if the user just +# queries for information +if is_distutils_display_option(): + setup_requires = [] + # Note that requires and provides should not be included in the call to # ``setup``, since these are now deprecated. See this link for more details: # https://groups.google.com/forum/#!topic/astropy-dev/urYO8ckB2uM @@ -132,18 +145,33 @@ version=VERSION, description=DESCRIPTION, scripts=scripts, - setup_requires=metadata.get("setup_requires", None), + setup_requires=[s.strip() for s in metadata.get('install_requires', 'astropy').split(',')], install_requires=[s.strip() for s in metadata.get('install_requires', 'astropy').split(',')], author=AUTHOR, author_email=AUTHOR_EMAIL, license=LICENSE, url=URL, long_description=LONG_DESCRIPTION, + keywords=['plasma', 'physics', 'transport', 'collisions', 'science', + 'atomic', 'particle', 'simulation', 'langmuir', 'tokamak', + 'instability', 'modeling'], + classifiers=[ + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: BSD-2-Clause-Patent', + 'Operating System :: OS Independent', + 'Programming Language :: C', + 'Programming Language :: Cython', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: Implementation :: CPython', + 'Topic :: Scientific/Engineering :: Astronomy', + 'Topic :: Scientific/Engineering :: Physics' + ], cmdclass=cmdclassd, zip_safe=False, use_2to3=False, include_package_data=True, entry_points=entry_points, python_requires='>={}'.format("3.6"), + tests_require=["pytest", "pytest-astropy"], **package_info )
Improve project description on PyPI [Project description](https://pypi.org/project/plasmapy/#description) is currently bland. We should detail some functionality, problems that the project is trying to address, mention openAstronomy affiliation, etc.
PlasmaPy/PlasmaPy
diff --git a/plasmapy/classes/sources/tests/__init__.py b/plasmapy/classes/sources/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/plasmapy/classes/sources/tests/test_plasma3d.py b/plasmapy/classes/sources/tests/test_plasma3d.py new file mode 100644 index 00000000..92de1b38 --- /dev/null +++ b/plasmapy/classes/sources/tests/test_plasma3d.py @@ -0,0 +1,98 @@ +import pytest +import numpy as np +import astropy.units as u + +from plasmapy.classes.sources import plasma3d +from plasmapy.utils.exceptions import InvalidParticleError + + [email protected]('grid_dimensions, expected_size', [ + ((100, 1, 1), 100), # Test 1D setup + ((128, 128, 1), 16384), # 2D + ((64, 64, 64), 262144), # 3D +]) +def test_Plasma3D_setup(grid_dimensions, expected_size): + r"""Function to test basic setup of the Plasma3D object. + + Tests that a Plasma3D object initiated with a particular + specification behaves in the correct way. + + Parameters + ---------- + grid_dimensions : tuple of ints + Grid size of the Plasma3D object to test. Must be a tuple of + length 3, indicating length of the grid in x, y, and z + directions respectively. Directions not needed should have a + length of 1. + + expected_size : int + Product of grid dimensions. + + Examples + -------- + >>> test_Plasma3D_setup((10, 10, 10), 1000) + >>> test_Plasma3D_setup((100, 10, 1), 1000) + """ + x, y, z = grid_dimensions + test_plasma = plasma3d.Plasma3D(domain_x=np.linspace(0, 1, x) * u.m, + domain_y=np.linspace(0, 1, y) * u.m, + domain_z=np.linspace(0, 1, z) * u.m) + + # Basic grid setup + assert test_plasma.x.size == x + assert test_plasma.y.size == y + assert test_plasma.z.size == z + assert test_plasma.grid.size == 3 * expected_size + + # Core variable units and shapes + assert test_plasma.density.size == expected_size + assert test_plasma.density.si.unit == u.kg / u.m ** 3 + + assert test_plasma.momentum.size == 3 * expected_size + assert test_plasma.momentum.si.unit == u.kg / (u.m ** 2 * u.s) + + assert test_plasma.pressure.size == expected_size + assert test_plasma.pressure.si.unit == u.Pa + + assert test_plasma.magnetic_field.size == 3 * expected_size + assert test_plasma.magnetic_field.si.unit == u.T + + assert test_plasma.electric_field.size == 3 * expected_size + assert test_plasma.electric_field.si.unit == u.V / u.m + + +# @pytest.mark.parametrize([()]) +def test_Plasma3D_derived_vars(): + r"""Function to test derived variables of the Plasma3D class. + + Tests the shapes, units and values of variables derived from core + variables. The core variables are set with arbitrary uniform + values. + """ + test_plasma = plasma3d.Plasma3D(domain_x=np.linspace(0, 1, 64) * u.m, + domain_y=np.linspace(0, 1, 64) * u.m, + domain_z=np.linspace(0, 1, 1) * u.m) + + # Set an arbitrary uniform values throughout the plasma + test_plasma.density[...] = 2.0 * u.kg / u.m ** 3 + test_plasma.momentum[...] = 10.0 * u.kg / (u.m ** 2 * u.s) + test_plasma.pressure[...] = 1 * u.Pa + test_plasma.magnetic_field[...] = 0.01 * u.T + test_plasma.electric_field[...] = 0.01 * u.V / u.m + + # Test derived variable units and shapes + assert test_plasma.velocity.shape == test_plasma.momentum.shape + assert (test_plasma.velocity == 5.0 * u.m / u.s).all() + + assert test_plasma.magnetic_field_strength.shape == \ + test_plasma.magnetic_field.shape[1:] + assert test_plasma.magnetic_field_strength.si.unit == u.T + assert np.allclose(test_plasma.magnetic_field_strength.value, 0.017320508) + + assert test_plasma.electric_field_strength.shape == \ + test_plasma.electric_field.shape[1:] + assert test_plasma.electric_field_strength.si.unit == u.V / u.m + + assert test_plasma.alfven_speed.shape == test_plasma.density.shape + assert test_plasma.alfven_speed.unit.si == u.m / u.s + assert np.allclose(test_plasma.alfven_speed.value, 10.92548431) diff --git a/plasmapy/classes/tests/test_Plasma.py b/plasmapy/classes/sources/tests/test_plasmablob.py similarity index 94% rename from plasmapy/classes/tests/test_Plasma.py rename to plasmapy/classes/sources/tests/test_plasmablob.py index e0e901db..0b94f37e 100644 --- a/plasmapy/classes/tests/test_Plasma.py +++ b/plasmapy/classes/sources/tests/test_plasmablob.py @@ -3,6 +3,7 @@ import astropy.units as u from plasmapy.classes.sources import plasma3d, plasmablob +from plasmapy.physics import magnetostatics from plasmapy.utils.exceptions import InvalidParticleError @pytest.mark.parametrize('grid_dimensions, expected_size', [ @@ -96,7 +97,19 @@ def test_Plasma3D_derived_vars(): assert test_plasma.alfven_speed.unit.si == u.m / u.s assert np.allclose(test_plasma.alfven_speed.value, 10.92548431) - +def test_Plasma3D_add_magnetostatics(): + r"""Function to test add_magnetostatic function + """ + dipole = magnetostatics.MagneticDipole(np.array([0, 0, 1])*u.A*u.m*u.m, np.array([0, 0, 0])*u.m) + cw = magnetostatics.CircularWire(np.array([0, 0, 1]), np.array([0, 0, 0])*u.m, 1*u.m, 1*u.A) + gw_cw = cw.to_GeneralWire() + iw = magnetostatics.InfiniteStraightWire(np.array([0, 1, 0]), np.array([0, 0, 0])*u.m, 1*u.A) + plasma = plasma3d.Plasma3D(domain_x=np.linspace(-2, 2, 30) * u.m, + domain_y=np.linspace(0, 0, 1) * u.m, + domain_z=np.linspace(-2, 2, 20) * u.m) + + plasma.add_magnetostatic(dipole, cw, gw_cw, iw) + class Test_PlasmaBlobRegimes: def test_intermediate_coupling(self): r""" diff --git a/plasmapy/physics/tests/test_magnetostatics.py b/plasmapy/physics/tests/test_magnetostatics.py new file mode 100644 index 00000000..ceb2a162 --- /dev/null +++ b/plasmapy/physics/tests/test_magnetostatics.py @@ -0,0 +1,154 @@ +import numpy as np +import pytest +from astropy import units as u, constants + +from plasmapy.physics.magnetostatics import (MagnetoStatics, + MagneticDipole, + Wire, + GeneralWire, + FiniteStraightWire, + InfiniteStraightWire, + CircularWire) + + +mu0_4pi = constants.mu0/4/np.pi + + +class Test_MagneticDipole: + def setup_method(self): + self.moment = np.array([0, 0, 1])*u.A*u.m*u.m + self.p0 = np.array([0, 0, 0])*u.m + + def test_value1(self): + "Test a known solution" + p = np.array([1, 0, 0]) + B1 = MagneticDipole(self.moment, self.p0).magnetic_field(p) + B1_expected = np.array([0, 0, -1])*1e-7*u.T + assert np.all(np.isclose(B1.value, B1_expected.value)) + assert B1.unit == u.T + + def test_value2(self): + "Test a known solution" + p = np.array([0, 0, 1]) + B2 = MagneticDipole(self.moment, self.p0).magnetic_field(p) + B2_expected = np.array([0, 0, 2])*1e-7*u.T + assert np.all(np.isclose(B2.value, B2_expected.value)) + assert B2.unit == u.T + + +class Test_GeneralWire: + def setup_method(self): + self.cw = CircularWire(np.array([0, 0, 1]), np.array([0, 0, 0])*u.m, 1*u.m, 1*u.A) + p1 = np.array([0., 0., 0.])*u.m + p2 = np.array([0., 0., 1.])*u.m + self.fw = FiniteStraightWire(p1, p2, 1*u.A) + + def test_not_callable(self): + "Test that `GeneralWire` raises `ValueError` if its first argument is not callale" + with pytest.raises(ValueError): + GeneralWire("wire", 0, 1, 1*u.A) + + def test_close_cw(self): + "Test if the GeneralWire is close to the CircularWire it converted from" + gw_cw = self.cw.to_GeneralWire() + p = np.array([0, 0, 0]) + B_cw = self.cw.magnetic_field(p) + B_gw_cw = gw_cw.magnetic_field(p) + + assert np.all(np.isclose(B_cw.value, B_gw_cw.value)) + assert B_cw.unit == B_gw_cw.unit + + def test_close_fw(self): + "Test if the GeneralWire is close to the FiniteWire it converted from" + gw_fw = self.fw.to_GeneralWire() + p = np.array([1, 0, 0]) + B_fw = self.fw.magnetic_field(p) + B_gw_fw = gw_fw.magnetic_field(p) + + assert np.all(np.isclose(B_fw.value, B_gw_fw.value)) + assert B_fw.unit == B_gw_fw.unit + + def test_value_error(self): + "Test GeneralWire raise ValueError when argument t1>t2" + with pytest.raises(ValueError) as e: + gw_cw = GeneralWire(lambda t: [0,0,t], 2, 1, 1.*u.A) + + +class Test_FiniteStraightWire: + def setup_method(self): + self.p1 = np.array([0., 0., -1.])*u.m + self.p2 = np.array([0., 0., 1.])*u.m + self.current = 1*u.A + + def test_same_point(self): + "Test that `FintiteStraightWire` raises `ValueError` if p1 == p2 " + with pytest.raises(ValueError): + FiniteStraightWire(self.p1, self.p1, self.current) + + def test_value1(self): + "Test a known solution" + fw = FiniteStraightWire(self.p1, self.p2, self.current) + B1 = fw.magnetic_field([1, 0, 0]) + B1_expected = np.array([0, np.sqrt(2), 0])*1e-7*u.T + assert np.all(np.isclose(B1.value, B1_expected.value)) + assert B1.unit == u.T + + def test_repr(self): + "Test __repr__ function" + fw = FiniteStraightWire(self.p1, self.p2, self.current) + assert repr(fw) == r"FiniteStraightWire(p1=[ 0. 0. -1.], p2=[0. 0. 1.], current=1.0)" + + + +class Test_InfiniteStraightWire: + def setup_method(self): + self.direction = np.array([0, 1, 0]) + self.p0 = np.array([0, 0, 0])*u.m + self.current = 1*u.A + + def test_value1(self): + "Test a known solution" + iw = InfiniteStraightWire(self.direction, self.p0, self.current) + B1 = iw.magnetic_field([1, 0, 0]) + B1_expected = np.array([0, 0, -2])*1e-7*u.T + assert np.all(np.isclose(B1.value, B1_expected.value)) + assert B1.unit == u.T + + def test_repr(self): + "Test __repr__ function" + iw = InfiniteStraightWire(self.direction, self.p0, self.current) + assert repr(iw) == r"InfiniteStraightWire(direction=[0. 1. 0.], p0=[0. 0. 0.], current=1.0)" + +class Test_CircularWire: + def setup_method(self): + self.normalz = np.array([0, 0, 1]) + self.normalx = np.array([1, 0, 0]) + self.center = np.array([0, 0, 0])*u.m + self.radius = 1*u.m + self.current = 1*u.A + + def test_negative_radius(self): + "Test that `FintiteStraightWire` raises `ValueError` if radius < 0" + with pytest.raises(ValueError): + CircularWire(self.normalz, self.center, -1.*u.m, self.current) + + def test_value1(self): + "Test a known solution" + cw = CircularWire(self.normalz, self.center, self.radius, self.current) + B1 = cw.magnetic_field([0, 0, 1]) + B1_expected = np.array([0, 0, 1])*2*np.pi/2**1.5*1e-7*u.T + assert np.all(np.isclose(B1.value, B1_expected.value)) + assert B1.unit == u.T + + def test_value2(self): + "Test a known solution" + cw = CircularWire(self.normalx, self.center, self.radius, self.current) + B2 = cw.magnetic_field([1, 0, 0]) + B2_expected = np.array([1, 0, 0])*2*np.pi/2**1.5*1e-7*u.T + assert np.all(np.isclose(B2.value, B2_expected.value)) + assert B2.unit == u.T + + def test_repr(self): + "Test __repr__ function" + cw = CircularWire(self.normalz, self.center, self.radius, self.current) + assert repr(cw) == r"CircularWire(normal=[0. 0. 1.], center=[0. 0. 0.], radius=1.0, current=1.0)"
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 5 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asteval==0.9.26 astropy==4.1 attrs==22.2.0 certifi==2021.5.30 colorama==0.4.5 coverage==6.2 cycler==0.11.0 Cython==3.0.12 future==1.0.0 importlib-metadata==4.8.3 iniconfig==1.1.1 kiwisolver==1.3.1 lmfit==1.0.3 matplotlib==3.3.4 mpmath==1.3.0 numpy==1.19.5 packaging==21.3 Pillow==8.4.0 -e git+https://github.com/PlasmaPy/PlasmaPy.git@984c7a1e83f948c715c673d5ae6f5f9defff5866#egg=plasmapy pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 roman==3.3 scipy==1.5.4 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 uncertainties==3.1.7 zipp==3.6.0
name: PlasmaPy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asteval==0.9.26 - astropy==4.1 - attrs==22.2.0 - colorama==0.4.5 - coverage==6.2 - cycler==0.11.0 - cython==3.0.12 - future==1.0.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - kiwisolver==1.3.1 - lmfit==1.0.3 - matplotlib==3.3.4 - mpmath==1.3.0 - numpy==1.19.5 - packaging==21.3 - pillow==8.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - roman==3.3 - scipy==1.5.4 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - uncertainties==3.1.7 - zipp==3.6.0 prefix: /opt/conda/envs/PlasmaPy
[ "plasmapy/classes/sources/tests/test_plasma3d.py::test_Plasma3D_setup[grid_dimensions0-100]", "plasmapy/classes/sources/tests/test_plasma3d.py::test_Plasma3D_setup[grid_dimensions1-16384]", "plasmapy/classes/sources/tests/test_plasma3d.py::test_Plasma3D_setup[grid_dimensions2-262144]", "plasmapy/classes/sources/tests/test_plasma3d.py::test_Plasma3D_derived_vars", "plasmapy/classes/sources/tests/test_plasmablob.py::test_Plasma3D_setup[grid_dimensions0-100]", "plasmapy/classes/sources/tests/test_plasmablob.py::test_Plasma3D_setup[grid_dimensions1-16384]", "plasmapy/classes/sources/tests/test_plasmablob.py::test_Plasma3D_setup[grid_dimensions2-262144]", "plasmapy/classes/sources/tests/test_plasmablob.py::test_Plasma3D_derived_vars", "plasmapy/classes/sources/tests/test_plasmablob.py::test_Plasma3D_add_magnetostatics", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlob::test_invalid_particle", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlob::test_electron_temperature", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlob::test_electron_density", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlob::test_ionization", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlob::test_composition", "plasmapy/physics/tests/test_magnetostatics.py::Test_MagneticDipole::test_value1", "plasmapy/physics/tests/test_magnetostatics.py::Test_MagneticDipole::test_value2", "plasmapy/physics/tests/test_magnetostatics.py::Test_GeneralWire::test_not_callable", "plasmapy/physics/tests/test_magnetostatics.py::Test_GeneralWire::test_close_cw", "plasmapy/physics/tests/test_magnetostatics.py::Test_GeneralWire::test_close_fw", "plasmapy/physics/tests/test_magnetostatics.py::Test_GeneralWire::test_value_error", "plasmapy/physics/tests/test_magnetostatics.py::Test_FiniteStraightWire::test_same_point", "plasmapy/physics/tests/test_magnetostatics.py::Test_FiniteStraightWire::test_value1", "plasmapy/physics/tests/test_magnetostatics.py::Test_FiniteStraightWire::test_repr", "plasmapy/physics/tests/test_magnetostatics.py::Test_InfiniteStraightWire::test_value1", "plasmapy/physics/tests/test_magnetostatics.py::Test_InfiniteStraightWire::test_repr", "plasmapy/physics/tests/test_magnetostatics.py::Test_CircularWire::test_negative_radius", "plasmapy/physics/tests/test_magnetostatics.py::Test_CircularWire::test_value1", "plasmapy/physics/tests/test_magnetostatics.py::Test_CircularWire::test_value2", "plasmapy/physics/tests/test_magnetostatics.py::Test_CircularWire::test_repr" ]
[ "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlobRegimes::test_intermediate_coupling", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlobRegimes::test_strongly_coupled", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlobRegimes::test_weakly_coupled", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlobRegimes::test_thermal_kinetic_energy_dominant", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlobRegimes::test_fermi_quantum_energy_dominant", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlobRegimes::test_both_fermi_and_thermal_energy_important", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlob::test_coupling", "plasmapy/classes/sources/tests/test_plasmablob.py::Test_PlasmaBlob::test_quantum_theta" ]
[]
[]
BSD 3-Clause "New" or "Revised" License
2,634
[ "plasmapy/classes/sources/plasma3d.py", "setup.py", "plasmapy/physics/magnetostatics.py", "docs/physics/index.rst", "setup.cfg", "plasmapy/examples/plot_magnetic_statics.py", "docs/physics/magnetostatics.rst", "plasmapy/physics/__init__.py" ]
[ "plasmapy/classes/sources/plasma3d.py", "setup.py", "plasmapy/physics/magnetostatics.py", "docs/physics/index.rst", "setup.cfg", "plasmapy/examples/plot_magnetic_statics.py", "docs/physics/magnetostatics.rst", "plasmapy/physics/__init__.py" ]
conan-io__conan-3010
d9f36e5d34f22a7cdba5aba9f0ad90c86f71d760
2018-06-07 09:41:09
120e64ba2d7a182c7274016bc3dee82bf6e0409c
diff --git a/conans/client/graph/graph.py b/conans/client/graph/graph.py index a406e6e6f..2fb467e2d 100644 --- a/conans/client/graph/graph.py +++ b/conans/client/graph/graph.py @@ -141,6 +141,20 @@ class DepsGraph(object): open_nodes = nodes_by_level[1] return open_nodes + def full_closure(self, node): + closure = OrderedDict() + current = node.neighbors() + while current: + new_current = [] + for n in current: + closure[n] = n + for n in current: + for neigh in n.public_neighbors(): + if neigh not in new_current and neigh not in closure: + new_current.append(neigh) + current = new_current + return closure + def closure(self, node): closure = OrderedDict() current = node.neighbors() diff --git a/conans/client/installer.py b/conans/client/installer.py index 12860cdf6..054a42858 100644 --- a/conans/client/installer.py +++ b/conans/client/installer.py @@ -414,12 +414,13 @@ class ConanInstaller(object): @staticmethod def _propagate_info(node, levels, deps_graph): # Get deps_cpp_info from upstream nodes - closure = deps_graph.closure(node) + closure = deps_graph.full_closure(node) node_order = [] for level in levels: - for n in closure.values(): + for n in closure: if n in level: node_order.append(n) + conan_file = node.conanfile for n in node_order: conan_file.deps_cpp_info.update(n.conanfile.cpp_info, n.conan_ref.name) diff --git a/conans/client/source.py b/conans/client/source.py index 8559983cf..7fdd38099 100644 --- a/conans/client/source.py +++ b/conans/client/source.py @@ -14,8 +14,11 @@ from conans.util.files import rmdir, set_dirty, is_dirty, clean_dirty, mkdir def get_scm(conanfile, src_folder): data = getattr(conanfile, "scm", None) - if data is not None: + if data is not None and isinstance(data, dict): return SCM(data, src_folder) + else: + # not an instance of dict or None, skip SCM feature. + pass def complete_recipe_sources(remote_manager, client_cache, registry, conanfile, conan_reference):
conan 1.4.x fails when "scm" attribute in recipe is not a dict Hi @lasote and @memsharded , at first of all thanks for implementing the first version of scm feature. Sadly I was unable to review it completely before the 1.4.0 release. The current implementation fails (without changing our recipes) because we also have an "scm" attribute but which is an instance of our "private" SCM implementation. The traceback is: ``` Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/client/command.py", line 1182, in run method(args[0][1:]) File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/client/command.py", line 246, in create test_build_folder=args.test_build_folder) File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/client/conan_api.py", line 77, in wrapper return f(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/client/conan_api.py", line 310, in create self._user_io.out, self._client_cache) File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/client/cmd/export.py", line 61, in cmd_export _export_conanfile(conanfile_path, output, client_cache, conanfile, conan_ref, keep_source) File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/client/cmd/export.py", line 136, in _export_conanfile output, paths, conan_ref) File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/client/cmd/export.py", line 107, in _capture_export_scm_data scm = get_scm(conanfile, src_path) File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/client/source.py", line 18, in get_scm return SCM(data, src_folder) File "/usr/local/lib/python2.7/dist-packages/conan-1.4.2-py2.7.egg/conans/model/scm.py", line 13, in __init__ self.type = data.get("type") AttributeError: 'property' object has no attribute 'get' ``` The reason is that there is no dict instance check implemented in `get_scm()` but IMHO it has to. Something like the following should be enough: ``` def get_scm(conanfile, src_folder): data = getattr(conanfile, "scm", None) if data is not None and isinstance(data, dict): return SCM(data, src_folder) else: # not an instance of dict or None, skip SCM feature. pass ``` Would be nice if you can fix this as soon as possible. Thanks in advance. Best Aalmann --- To help us debug your issue please explain: - [x ] I've read the [CONTRIBUTING guide](https://raw.githubusercontent.com/conan-io/conan/develop/.github/CONTRIBUTING.md). - [ x] I've specified the Conan version, operating system version and any tool that can be relevant. - [ x] I've explained the steps to reproduce the error or the motivation/use case of the question/suggestion.
conan-io/conan
diff --git a/conans/test/functional/scm_test.py b/conans/test/functional/scm_test.py index 0fc72c328..2420e5b44 100644 --- a/conans/test/functional/scm_test.py +++ b/conans/test/functional/scm_test.py @@ -40,6 +40,20 @@ class SCMTest(unittest.TestCase): self.client.runner("git add .", cwd=self.client.current_folder) self.client.runner('git commit -m "commiting"', cwd=self.client.current_folder) + def test_scm_other_type_ignored(self): + conanfile = ''' +from conans import ConanFile, tools + +class ConanLib(ConanFile): + name = "lib" + version = "0.1" + scm = ["Other stuff"] + +''' + self.client.save({"conanfile.py": conanfile}) + # nothing breaks + self.client.run("export . user/channel") + def test_repeat_clone_changing_subfolder(self): tmp = ''' from conans import ConanFile, tools diff --git a/conans/test/integration/order_libs_test.py b/conans/test/integration/order_libs_test.py index a2f0ec268..7f9d37845 100644 --- a/conans/test/integration/order_libs_test.py +++ b/conans/test/integration/order_libs_test.py @@ -10,6 +10,62 @@ class OrderLibsTest(unittest.TestCase): def setUp(self): self.client = TestClient() + def private_order_test(self): + # https://github.com/conan-io/conan/issues/3006 + client = TestClient() + conanfile = """from conans import ConanFile +class LibBConan(ConanFile): + def package_info(self): + self.cpp_info.libs = ["LibC"] +""" + client.save({"conanfile.py": conanfile}) + client.run("create . LibC/0.1@user/channel") + + conanfile = """from conans import ConanFile +class LibCConan(ConanFile): + requires = "LibC/0.1@user/channel" + def package_info(self): + self.cpp_info.libs = ["LibB"] +""" + client.save({"conanfile.py": conanfile}) + client.run("create . LibB/0.1@user/channel") + + conanfile = """from conans import ConanFile +class LibCConan(ConanFile): + requires = ("LibB/0.1@user/channel", "private"), "LibC/0.1@user/channel" +""" + client.save({"conanfile.py": conanfile}) + client.run("install . -g cmake") + conanbuildinfo = load(os.path.join(client.current_folder, "conanbuildinfo.cmake")) + self.assertIn("set(CONAN_LIBS LibB LibC ${CONAN_LIBS})", conanbuildinfo) + # Change private + conanfile = """from conans import ConanFile +class LibCConan(ConanFile): + requires = "LibB/0.1@user/channel", ("LibC/0.1@user/channel", "private") +""" + client.save({"conanfile.py": conanfile}) + client.run("install . -g cmake") + conanbuildinfo = load(os.path.join(client.current_folder, "conanbuildinfo.cmake")) + self.assertIn("set(CONAN_LIBS LibB LibC ${CONAN_LIBS})", conanbuildinfo) + # Change order + conanfile = """from conans import ConanFile +class LibCConan(ConanFile): + requires = ("LibC/0.1@user/channel", "private"), "LibB/0.1@user/channel" +""" + client.save({"conanfile.py": conanfile}) + client.run("install . -g cmake") + conanbuildinfo = load(os.path.join(client.current_folder, "conanbuildinfo.cmake")) + self.assertIn("set(CONAN_LIBS LibB LibC ${CONAN_LIBS})", conanbuildinfo) + # Change order + conanfile = """from conans import ConanFile +class LibCConan(ConanFile): + requires = "LibC/0.1@user/channel", ("LibB/0.1@user/channel", "private") +""" + client.save({"conanfile.py": conanfile}) + client.run("install . -g cmake") + conanbuildinfo = load(os.path.join(client.current_folder, "conanbuildinfo.cmake")) + self.assertIn("set(CONAN_LIBS LibB LibC ${CONAN_LIBS})", conanbuildinfo) + def _export(self, name, deps=None, export=True): def _libs(): if name == "LibPNG":
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 3 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "conans/requirements.txt", "conans/requirements_osx.txt", "conans/requirements_server.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asn1crypto==1.5.1 astroid==1.6.6 attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.12.25 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 codecov==2.1.13 colorama==0.3.9 -e git+https://github.com/conan-io/conan.git@d9f36e5d34f22a7cdba5aba9f0ad90c86f71d760#egg=conan coverage==4.2 cryptography==2.1.4 deprecation==2.0.7 distro==1.1.0 fasteners==0.19 future==0.16.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==1.3.0 ndg-httpsclient==0.4.4 node-semver==0.2.0 nose==1.3.7 packaging==21.3 parameterized==0.8.1 patch==1.16 pbr==6.1.1 pluggy==1.0.0 pluginbase==0.7 py==1.11.0 pyasn==1.5.0b7 pyasn1==0.5.1 pycparser==2.21 Pygments==2.14.0 PyJWT==1.7.1 pylint==1.8.4 pyOpenSSL==17.5.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==3.12 requests==2.27.1 six==1.17.0 soupsieve==2.3.2.post1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 waitress==2.0.0 WebOb==1.8.9 WebTest==2.0.35 wrapt==1.16.0 zipp==3.6.0
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asn1crypto==1.5.1 - astroid==1.6.6 - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.12.25 - cffi==1.15.1 - charset-normalizer==2.0.12 - codecov==2.1.13 - colorama==0.3.9 - coverage==4.2 - cryptography==2.1.4 - deprecation==2.0.7 - distro==1.1.0 - fasteners==0.19 - future==0.16.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==1.3.0 - ndg-httpsclient==0.4.4 - node-semver==0.2.0 - nose==1.3.7 - packaging==21.3 - parameterized==0.8.1 - patch==1.16 - pbr==6.1.1 - pluggy==1.0.0 - pluginbase==0.7 - py==1.11.0 - pyasn==1.5.0b7 - pyasn1==0.5.1 - pycparser==2.21 - pygments==2.14.0 - pyjwt==1.7.1 - pylint==1.8.4 - pyopenssl==17.5.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==3.12 - requests==2.27.1 - six==1.17.0 - soupsieve==2.3.2.post1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - waitress==2.0.0 - webob==1.8.9 - webtest==2.0.35 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/conan
[ "conans/test/functional/scm_test.py::SCMTest::test_scm_other_type_ignored" ]
[ "conans/test/functional/scm_test.py::SCMTest::test_auto_git", "conans/test/functional/scm_test.py::SCMTest::test_deleted_source_folder", "conans/test/functional/scm_test.py::SCMTest::test_install_checked_out", "conans/test/functional/scm_test.py::SCMTest::test_local_source", "conans/test/functional/scm_test.py::SCMTest::test_repeat_clone_changing_subfolder", "conans/test/functional/scm_test.py::SCMTest::test_source_method_export_sources_and_scm_mixed" ]
[]
[]
MIT License
2,635
[ "conans/client/graph/graph.py", "conans/client/installer.py", "conans/client/source.py" ]
[ "conans/client/graph/graph.py", "conans/client/installer.py", "conans/client/source.py" ]
tomMoral__loky-134
1bf741a4796d15c517902a3331b5bd9e86502037
2018-06-07 11:54:58
1bf741a4796d15c517902a3331b5bd9e86502037
diff --git a/CHANGES.md b/CHANGES.md index 033eccb..e03a520 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ ### 2.2.0.dev0 (in development) - Fix bad interaction between `max_workers=None` and `reuse='auto'` (#132). +- Add initializer for `get_reusable_executor` (#134) ### 2.1.2 - 2018-06-04 - Release Highligths diff --git a/examples/deadlock_results.py b/examples/deadlocks/deadlock_results.py similarity index 95% rename from examples/deadlock_results.py rename to examples/deadlocks/deadlock_results.py index dc11ba6..d1de4cb 100644 --- a/examples/deadlock_results.py +++ b/examples/deadlocks/deadlock_results.py @@ -1,4 +1,5 @@ """Deadlock with unpickling error for the result +================================================= This example highlights the fact that the ProcessPoolExecutor implementation from concurrent.futures is not robust to pickling error (at least in versions diff --git a/examples/deadlock_timeout_shutdown.py b/examples/deadlocks/deadlock_timeout_shutdown.py similarity index 95% rename from examples/deadlock_timeout_shutdown.py rename to examples/deadlocks/deadlock_timeout_shutdown.py index 419467b..ba5a7e0 100644 --- a/examples/deadlock_timeout_shutdown.py +++ b/examples/deadlocks/deadlock_timeout_shutdown.py @@ -1,4 +1,5 @@ """Deadlock with pickling errors +================================ This example highlights the fact that the ProcessPoolExecutor implementation from concurrent.futures is not robust to pickling error (at least in versions diff --git a/examples/reuseable_executor.py b/examples/reuseable_executor.py new file mode 100644 index 0000000..36833c3 --- /dev/null +++ b/examples/reuseable_executor.py @@ -0,0 +1,42 @@ +""" +Advanced Executor Setup +======================= + +It is possible to reuse an executor even if it has a complicated setup. When +using the parameter `reuse=True`, the executor is resized if needed but the +arguments stay the same. +""" +from time import sleep +from loky import get_reusable_executor + +INITIALIZER_STATUS = "uninitialized" + + +def initializer(self, x): + global INITIALIZER_STATUS + INITIALIZER_STATUS = x + + +def test_initializer(self, delay=0): + print(delay) + sleep(delay) + + global INITIALIZER_STATUS + return INITIALIZER_STATUS + + +executor = get_reusable_executor( + max_workers=2, initializer=initializer, initargs=('initialized',)) + +assert executor.submit(test_initializer).result() == 'initialized' + +# With reuse=True, the executor use the same initializer +executor = get_reusable_executor(max_workers=4, reuse=True) +for x in executor.map(test_initializer, delay=.5): + assert x == 'initialized' + +# With reuse='auto', the initializer is not used anymore as a new executor is +# created. +executor = get_reusable_executor(max_workers=4) +for x in executor.map(test_initializer, delay=.1): + assert x == 'uninitialized' diff --git a/loky/reusable_executor.py b/loky/reusable_executor.py index 881ec83..30b217f 100644 --- a/loky/reusable_executor.py +++ b/loky/reusable_executor.py @@ -38,8 +38,9 @@ def _get_next_executor_id(): def get_reusable_executor(max_workers=None, context=None, timeout=10, - kill_workers=False, job_reducers=None, - result_reducers=None, reuse="auto"): + kill_workers=False, reuse="auto", + job_reducers=None, result_reducers=None, + initializer=None, initargs=()): """Return the current ReusableExectutor instance. Start a new instance if it has not been started already or if the previous @@ -69,9 +70,12 @@ def get_reusable_executor(max_workers=None, context=None, timeout=10, The ``job_reducers`` and ``result_reducers`` are used to customize the pickling of tasks and results send to the executor. + + When provided, the ``initializer`` is run first in newly spawned + processes with argument ``initargs``. """ with _executor_lock: - global _executor, _executor_args + global _executor, _executor_kwargs executor = _executor if max_workers is None: @@ -84,25 +88,27 @@ def get_reusable_executor(max_workers=None, context=None, timeout=10, "max_workers must be greater than 0, got {}." .format(max_workers)) - args = dict(context=context, timeout=timeout, - job_reducers=job_reducers, result_reducers=result_reducers) if isinstance(context, STRING_TYPE): context = get_context(context) if context is not None and context.get_start_method() == "fork": raise ValueError("Cannot use reusable executor with the 'fork' " "context") + + kwargs = dict(context=context, timeout=timeout, + job_reducers=job_reducers, + result_reducers=result_reducers, + initializer=initializer, initargs=initargs) if executor is None: mp.util.debug("Create a executor with max_workers={}." .format(max_workers)) executor_id = _get_next_executor_id() - _executor_args = args + _executor_kwargs = kwargs _executor = executor = _ReusablePoolExecutor( - _executor_lock, max_workers=max_workers, context=context, - timeout=timeout, executor_id=executor_id, - job_reducers=job_reducers, result_reducers=result_reducers) + _executor_lock, max_workers=max_workers, + executor_id=executor_id, **kwargs) else: if reuse == 'auto': - reuse = args == _executor_args + reuse = kwargs == _executor_kwargs if (executor._flags.broken or executor._flags.shutdown or not reuse): if executor._flags.broken: @@ -116,10 +122,10 @@ def get_reusable_executor(max_workers=None, context=None, timeout=10, "previous instance cannot be reused ({})." .format(max_workers, reason)) executor.shutdown(wait=True, kill_workers=kill_workers) - _executor = executor = _executor_args = None + _executor = executor = _executor_kwargs = None # Recursive call to build a new instance return get_reusable_executor(max_workers=max_workers, - **args) + **kwargs) else: mp.util.debug("Reusing existing executor with max_workers={}." .format(executor._max_workers)) @@ -131,11 +137,11 @@ def get_reusable_executor(max_workers=None, context=None, timeout=10, class _ReusablePoolExecutor(ProcessPoolExecutor): def __init__(self, submit_resize_lock, max_workers=None, context=None, timeout=None, executor_id=0, job_reducers=None, - result_reducers=None): + result_reducers=None, initializer=None, initargs=()): super(_ReusablePoolExecutor, self).__init__( max_workers=max_workers, context=context, timeout=timeout, - job_reducers=job_reducers, - result_reducers=result_reducers) + job_reducers=job_reducers, result_reducers=result_reducers, + initializer=initializer, initargs=initargs) self.executor_id = executor_id self._submit_resize_lock = submit_resize_lock
initializer for get_reusable_executor It is possible to set `initializer` for `ProcessPoolExecutor` but I could not find how to pass an initializer to `get_reusable_executor`.
tomMoral/loky
diff --git a/tests/test_reusable_executor.py b/tests/test_reusable_executor.py index 76e1aef..85385bf 100644 --- a/tests/test_reusable_executor.py +++ b/tests/test_reusable_executor.py @@ -43,6 +43,9 @@ except ImportError: pass +INITIALIZER_STATUS = 'uninitialized' + + def clean_warning_registry(): """Safe way to reset warnings.""" warnings.resetwarnings() @@ -651,3 +654,37 @@ def test_reusable_executor_reuse_true(): executor4 = get_reusable_executor() assert executor4 is executor3 + + +class TestExecutorInitializer(ReusableExecutorMixin): + def _initializer(self, x): + global INITIALIZER_STATUS + INITIALIZER_STATUS = x + + def _test_initializer(self, delay=0): + sleep(delay) + + global INITIALIZER_STATUS + return INITIALIZER_STATUS + + def test_reusable_initializer(self): + executor = get_reusable_executor( + max_workers=2, initializer=self._initializer, initargs=('done',)) + + assert executor.submit(self._test_initializer).result() == 'done' + + # when the initializer change, the executor is re-spawned + executor = get_reusable_executor( + max_workers=2, initializer=self._initializer, initargs=(42,)) + + assert executor.submit(self._test_initializer).result() == 42 + + # With reuse=True, the executor use the same initializer + executor = get_reusable_executor(max_workers=4, reuse=True) + for x in executor.map(self._test_initializer, delay=.1): + assert x == 42 + + # With reuse='auto', the initializer is not used anymore + executor = get_reusable_executor(max_workers=4) + for x in executor.map(self._test_initializer, delay=.1): + assert x == 'uninitialized'
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 4 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-timeout", "psutil", "coverage" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 cloudpickle==2.2.1 coverage==6.2 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/tomMoral/loky.git@1bf741a4796d15c517902a3331b5bd9e86502037#egg=loky more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==7.0.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-timeout==2.1.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: loky channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - cloudpickle==2.2.1 - coverage==6.2 - psutil==7.0.0 - pytest-timeout==2.1.0 prefix: /opt/conda/envs/loky
[ "tests/test_reusable_executor.py::TestExecutorInitializer::test_reusable_initializer" ]
[]
[ "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args0-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args1-PicklingError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args2-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args3-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args4-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args5-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[crash-args6-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[exit-args7-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[c_exit-args8-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[raise_error-args9-RuntimeError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args10-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args11-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args12-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args13-PicklingError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args14-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args15-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args0-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args1-PicklingError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args2-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args3-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args4-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args5-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[crash-args6-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[exit-args7-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[c_exit-args8-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[raise_error-args9-RuntimeError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args10-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args11-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args12-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args13-PicklingError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args14-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args15-BrokenProcessPool]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_callback_crash_on_submit", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_deadlock_kill", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crash_races[1]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crash_races[2]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crash_races[5]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crash_races[13]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_imap_handle_iterable_exception", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_queue_full_deadlock", "tests/test_reusable_executor.py::TestTerminateExecutor::test_shutdown_kill", "tests/test_reusable_executor.py::TestTerminateExecutor::test_shutdown_deadlock", "tests/test_reusable_executor.py::TestTerminateExecutor::test_kill_workers_on_new_options", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize_many_times[True-True]", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize_many_times[True-False]", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize_many_times[False-True]", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize_many_times[False-False]", "tests/test_reusable_executor.py::TestResizeExecutor::test_kill_after_resize_call", "tests/test_reusable_executor.py::TestResizeExecutor::test_resize_after_timeout", "tests/test_reusable_executor.py::test_invalid_process_number", "tests/test_reusable_executor.py::test_invalid_context", "tests/test_reusable_executor.py::test_call_item_gc_crash_or_exit", "tests/test_reusable_executor.py::test_pass_start_method_name_as_context", "tests/test_reusable_executor.py::test_interactively_define_executor_no_main", "tests/test_reusable_executor.py::test_compat_with_concurrent_futures_exception", "tests/test_reusable_executor.py::test_reusable_executor_thread_safety[constant-clean_start]", "tests/test_reusable_executor.py::test_reusable_executor_thread_safety[constant-broken_start]", "tests/test_reusable_executor.py::test_reusable_executor_thread_safety[varying-clean_start]", "tests/test_reusable_executor.py::test_reusable_executor_thread_safety[varying-broken_start]", "tests/test_reusable_executor.py::test_reusable_executor_reuse_true" ]
[]
BSD 3-Clause "New" or "Revised" License
2,636
[ "examples/reuseable_executor.py", "CHANGES.md", "examples/deadlock_results.py", "loky/reusable_executor.py", "examples/deadlock_timeout_shutdown.py" ]
[ "examples/reuseable_executor.py", "CHANGES.md", "examples/deadlocks/deadlock_results.py", "loky/reusable_executor.py", "examples/deadlocks/deadlock_timeout_shutdown.py" ]
conan-io__conan-3012
f94602138045e0d9dc9de4dd5a4ca213ce051525
2018-06-07 16:03:46
120e64ba2d7a182c7274016bc3dee82bf6e0409c
diff --git a/conans/client/build/cmake.py b/conans/client/build/cmake.py index 8237a716b..1703d4345 100644 --- a/conans/client/build/cmake.py +++ b/conans/client/build/cmake.py @@ -117,9 +117,8 @@ class CMake(object): if not self._compiler or not self._compiler_version or not self._arch: if self._os_build == "Windows": - raise ConanException("You must specify compiler, compiler.version and arch in " - "your settings to use a CMake generator. You can also declare " - "the env variable CONAN_CMAKE_GENERATOR.") + # Not enough settings to set a generator in Windows + return None return "Unix Makefiles" if self._compiler == "Visual Studio": @@ -243,11 +242,10 @@ class CMake(object): @property def command_line(self): - args = [ - '-G "%s"' % self.generator, - self.flags, - '-Wno-dev' - ] + args = ['-G "%s"' % self.generator] if self.generator else [] + args.append(self.flags) + args.append('-Wno-dev') + if self.toolset: args.append('-T "%s"' % self.toolset) return join_arguments(args) @@ -422,7 +420,7 @@ class CMake(object): if target is not None: args = ["--target", target] + args - if self.parallel: + if self.generator and self.parallel: if "Makefiles" in self.generator and "NMake" not in self.generator: if "--" not in args: args.append("--")
CMake helper requires compiler during package To help us debug your issue please explain: Hi everyone! I'm trying give some support to taocpp/PEGTL and I would like to use CMake helper to install the project. The project is header-only, thus it installs the license, headers and pegtl-config.cmake. However, when the package method runs over Windows, I receive the follow message: conans.errors.ConanExceptionInUserConanfileMethod: pegtl/2.5.2@taocpp/testing: Error in package() method, line 22 cmake = CMake(self) ConanException: You must specify compiler, compiler.version and arch in your settings to use a CMake generator. You can also declare the env variable CONAN_CMAKE_GENERATOR. When I run the same recipe on Linux (Travis CI), I have no problems. Appveyor error log: https://ci.appveyor.com/project/uilianries/pegtl/build/feature/conan-9/job/tnwvkd69gvkgsb6x#L250 The current PR uses just self.copy, but my intention is revert to follow state, using CMake: https://github.com/uilianries/PEGTL/blob/dc4011991624faedf67fd390e8f53737f562a897/conanfile.py Current PR for PEGTL: https://github.com/taocpp/PEGTL/pull/112 I'm curious if CONAN_CMAKE_GENERATOR is required by Conan or is just a CMake limitation. Conan Version: 1.4.3 - [X] I've read the [CONTRIBUTING guide](https://raw.githubusercontent.com/conan-io/conan/develop/.github/CONTRIBUTING.md). - [X] I've specified the Conan version, operating system version and any tool that can be relevant. - [X] I've explained the steps to reproduce the error or the motivation/use case of the question/suggestion.
conan-io/conan
diff --git a/conans/test/build_helpers/cmake_test.py b/conans/test/build_helpers/cmake_test.py index 09aab1631..4b5d400a9 100644 --- a/conans/test/build_helpers/cmake_test.py +++ b/conans/test/build_helpers/cmake_test.py @@ -820,9 +820,8 @@ build_type: [ Release] cmake = instance_with_os_build("Macos") self.assertEquals(cmake.generator, "Unix Makefiles") - with self.assertRaisesRegexp(ConanException, "You must specify compiler, " - "compiler.version and arch"): - instance_with_os_build("Windows") + cmake = instance_with_os_build("Windows") + self.assertEquals(cmake.generator, None) with tools.environment_append({"CONAN_CMAKE_GENERATOR": "MyCoolGenerator"}): cmake = instance_with_os_build("Windows") diff --git a/conans/test/integration/cmake_flags_test.py b/conans/test/integration/cmake_flags_test.py index 89d3308b1..56988dc54 100644 --- a/conans/test/integration/cmake_flags_test.py +++ b/conans/test/integration/cmake_flags_test.py @@ -254,13 +254,7 @@ class MyLib(ConanFile): client = TestClient() client.save({"conanfile.py": conanfile % settings_line}) client.run("install .") - error = client.run("build .", ignore_error=True) - if platform.system() == "Windows": - self.assertTrue(error) - self.assertIn("You must specify compiler, compiler.version and arch in " - "your settings to use a CMake generator", client.user_io.out,) - else: - self.assertFalse(error) + client.run("build .") def cmake_shared_flag_test(self): conanfile = """ diff --git a/conans/test/integration/cmake_install_package_test.py b/conans/test/integration/cmake_install_package_test.py index ecd2304f9..f7c222c2b 100644 --- a/conans/test/integration/cmake_install_package_test.py +++ b/conans/test/integration/cmake_install_package_test.py @@ -72,3 +72,14 @@ cmake_minimum_required(VERSION 2.8.12) client.run("create . user/channel") self.assertIn("Test/0.1@user/channel (test package): Content: my header h!!", client.user_io.out) + + # Test also recipe without settings + new_conanfile =\ + conanfile.replace("settings = \"os\", \"compiler\", \"build_type\", \"arch\"", "") + self.assertNotIn("settings = \"os\", \"compiler\", \"build_type\", \"arch\"", new_conanfile) + client.save({"conanfile.py": new_conanfile}) + + client.run("remove * --force") + client.run("create . user/channel") + self.assertIn("Test/0.1@user/channel (test package): Content: my header h!!", + client.user_io.out)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "nose-cov", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc g++-multilib" ], "python": "3.6", "reqs_path": [ "conans/requirements.txt", "conans/requirements_server.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==1.6.6 attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.12.25 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 colorama==0.3.9 -e git+https://github.com/conan-io/conan.git@f94602138045e0d9dc9de4dd5a4ca213ce051525#egg=conan cov-core==1.15.0 coverage==4.2 deprecation==2.0.7 distro==1.1.0 fasteners==0.19 future==0.16.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==1.3.0 node-semver==0.2.0 nose==1.3.7 nose-cov==1.6 packaging==21.3 parameterized==0.8.1 patch==1.16 pbr==6.1.1 pluggy==1.0.0 pluginbase==0.7 py==1.11.0 Pygments==2.14.0 PyJWT==1.7.1 pylint==1.8.4 pyparsing==3.1.4 pytest==7.0.1 PyYAML==3.12 requests==2.27.1 six==1.17.0 soupsieve==2.3.2.post1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 waitress==2.0.0 WebOb==1.8.9 WebTest==2.0.35 wrapt==1.16.0 zipp==3.6.0
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==1.6.6 - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.12.25 - charset-normalizer==2.0.12 - codecov==2.1.13 - colorama==0.3.9 - cov-core==1.15.0 - coverage==4.2 - deprecation==2.0.7 - distro==1.1.0 - fasteners==0.19 - future==0.16.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==1.3.0 - node-semver==0.2.0 - nose==1.3.7 - nose-cov==1.6 - packaging==21.3 - parameterized==0.8.1 - patch==1.16 - pbr==6.1.1 - pluggy==1.0.0 - pluginbase==0.7 - py==1.11.0 - pygments==2.14.0 - pyjwt==1.7.1 - pylint==1.8.4 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==3.12 - requests==2.27.1 - six==1.17.0 - soupsieve==2.3.2.post1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - waitress==2.0.0 - webob==1.8.9 - webtest==2.0.35 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/conan
[ "conans/test/build_helpers/cmake_test.py::CMakeTest::test_missing_settings" ]
[]
[ "conans/test/build_helpers/cmake_test.py::CMakeTest::test_clean_sh_path", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_cmake_system_version_android", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_cores_ancient_visual", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_deprecated_behaviour", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_pkg_config_path", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_run_tests", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_shared", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_sysroot", "conans/test/build_helpers/cmake_test.py::CMakeTest::test_verbose" ]
[]
MIT License
2,637
[ "conans/client/build/cmake.py" ]
[ "conans/client/build/cmake.py" ]
fniessink__next-action-110
cc56f793b0e7f8b9bce0a11aeb5749f77126619d
2018-06-07 20:08:06
cc56f793b0e7f8b9bce0a11aeb5749f77126619d
diff --git a/README.md b/README.md index 2797c49..dc14156 100644 --- a/README.md +++ b/README.md @@ -103,9 +103,9 @@ $ next-action (A) Call mom @phone ``` -The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks. FInally, tasks that belong to more projects get precedence over tasks that belong to fewer projects. +The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks. Finally, tasks that belong to more projects get precedence over tasks that belong to fewer projects. -Completed tasks (~~`x This is a completed task`~~) and tasks with a creation date in the future (`9999-01-01 Start preparing for five-digit years`) are not considered when determining the next action. +Completed tasks (~~`x This is a completed task`~~), tasks with a creation date in the future (`9999-01-01 Start preparing for five-digit years`), and tasks with a future threshold date (`Start preparing for emigration to Mars t:3000-01-01`) are not considered when determining the next action. ### Limiting the tasks from which next actions are selected @@ -194,7 +194,7 @@ $ next-action --all @store (G) Buy wood for new +DogHouse @store ``` -Note again that completed tasks and task with a future creation date are never shown since they can't be a next action. +Note again that completed tasks and task with a future creation or threshold date are never shown since they can't be a next action. ### Styling the output diff --git a/docs/todo.txt b/docs/todo.txt index 06842c9..7df531b 100644 --- a/docs/todo.txt +++ b/docs/todo.txt @@ -9,3 +9,4 @@ Buy flowers due:2018-02-14 (K) Pay July invoice @home due:2018-07-28 x This is a completed task 9999-01-01 Start preparing for five-digit years +Start preparing for emigration to Mars t:3000-01-01 diff --git a/next_action/pick_action.py b/next_action/pick_action.py index b65d42a..24dbff0 100644 --- a/next_action/pick_action.py +++ b/next_action/pick_action.py @@ -24,7 +24,8 @@ def next_actions(tasks: Sequence[Task], arguments: argparse.Namespace) -> Sequen projects = subset(arguments.filters, "+") excluded_contexts = subset(arguments.filters, "-@") excluded_projects = subset(arguments.filters, "-+") - # First, get the potential next actions by filtering out completed tasks and tasks with a future creation date + # First, get the potential next actions by filtering out completed tasks and tasks with a future creation date or + # future threshold date actionable_tasks = [task for task in tasks if task.is_actionable()] # Then, exclude tasks that have an excluded context eligible_tasks = filter(lambda task: not excluded_contexts & task.contexts() if excluded_contexts else True, diff --git a/next_action/todotxt/task.py b/next_action/todotxt/task.py index 6e420db..a8733b6 100644 --- a/next_action/todotxt/task.py +++ b/next_action/todotxt/task.py @@ -45,10 +45,13 @@ class Task(object): match = re.match(r"(?:\([A-Z]\) )?{0}\b".format(self.iso_date_reg_exp), self.text) return self.__create_date(match) + def threshold_date(self) -> Optional[datetime.date]: + """ Return the threshold date of the task. """ + return self.__find_keyed_date("t") + def due_date(self) -> Optional[datetime.date]: """ Return the due date of the task. """ - match = re.search(r"\bdue:{0}\b".format(self.iso_date_reg_exp), self.text) - return self.__create_date(match) + return self.__find_keyed_date("due") def is_due(self, due_date: datetime.date) -> bool: """ Return whether the task is due on or before the given due date. """ @@ -60,9 +63,15 @@ class Task(object): return self.text.startswith("x ") def is_future(self) -> bool: - """ Return whether the task is a future task, i.e. has a creation date in the future. """ + """ Return whether the task is a future task, i.e. has a creation or threshold date in the future. """ + today = datetime.date.today() creation_date = self.creation_date() - return creation_date > datetime.date.today() if creation_date else False + if creation_date: + return creation_date > today + threshold_date = self.threshold_date() + if threshold_date: + return threshold_date > today + return False def is_actionable(self) -> bool: """ Return whether the task is actionable, i.e. whether it's not completed and doesn't have a future creation @@ -70,7 +79,7 @@ class Task(object): return not self.is_completed() and not self.is_future() def is_overdue(self) -> bool: - """ Return whether the taks is overdue, i.e. whether it has a due date in the past. """ + """ Return whether the task is overdue, i.e. whether it has a due date in the past. """ due_date = self.due_date() return due_date < datetime.date.today() if due_date else False @@ -78,6 +87,11 @@ class Task(object): """ Return the prefixed items in the task. """ return {match.group(1) for match in re.finditer(" {0}([^ ]+)".format(prefix), self.text)} + def __find_keyed_date(self, key: str) -> Optional[datetime.date]: + """ Find a key:value pair with the supplied key where the value is a date. """ + match = re.search(r"\b{0}:{1}\b".format(key, self.iso_date_reg_exp), self.text) + return self.__create_date(match) + @staticmethod def __create_date(match: Optional[typing.Match[str]]) -> Optional[datetime.date]: """ Create a date from the match, if possible. """
Support t: for threshold (start date) in todo.txt files
fniessink/next-action
diff --git a/tests/unittests/todotxt/test_task.py b/tests/unittests/todotxt/test_task.py index 6172c77..e890535 100644 --- a/tests/unittests/todotxt/test_task.py +++ b/tests/unittests/todotxt/test_task.py @@ -87,7 +87,8 @@ class TaskPriorityTest(unittest.TestCase): class CreationDateTest(unittest.TestCase): - """ Unit tests for task creation dates. """ + """ Unit tests for task creation dates. Next-action interprets creation dates in the future as threshold, or + start date. """ def test_no_creation_date(self): """ Test that tasks have no creation date by default. """ @@ -121,6 +122,35 @@ class CreationDateTest(unittest.TestCase): self.assertFalse(todotxt.Task("{0} Todo".format(datetime.date.today().isoformat())).is_future()) +class ThresholdDateTest(unittest.TestCase): + """ Unit tests for the threshold date of a task. The core todo.txt standard only defines creation date, but + threshold (t:<date>) seems to be a widely used convention. """ + + def test_no_threshold(self): + """ Test that tasks have no threshold by default. """ + task = todotxt.Task("Todo") + self.assertEqual(None, task.threshold_date()) + self.assertFalse(task.is_future()) + + def test_past_threshold(self): + """ Test a past threshold date. """ + task = todotxt.Task("Todo t:2018-01-02") + self.assertEqual(datetime.date(2018, 1, 2), task.threshold_date()) + self.assertFalse(task.is_future()) + + def test_future_threshold(self): + """ Test a future threshold date. """ + task = todotxt.Task("Todo t:9999-01-01") + self.assertEqual(datetime.date(9999, 1, 1), task.threshold_date()) + self.assertTrue(task.is_future()) + + def test_threshold_today(self): + """ Test a task with threshold today. """ + task = todotxt.Task("Todo t:{0}".format(datetime.date.today().isoformat())) + self.assertEqual(datetime.date.today(), task.threshold_date()) + self.assertFalse(task.is_future()) + + class DueDateTest(unittest.TestCase): """ Unit tests for the due date of tasks. """
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 4 }
0.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
Cerberus==1.2 dateparser==0.7.0 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/fniessink/next-action.git@cc56f793b0e7f8b9bce0a11aeb5749f77126619d#egg=next_action packaging==24.2 pluggy==1.5.0 Pygments==2.2.0 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==3.12 regex==2024.11.6 six==1.17.0 tomli==2.2.1 tzlocal==5.3.1
name: next-action channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cerberus==1.2 - dateparser==0.7.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pygments==2.2.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==3.12 - regex==2024.11.6 - six==1.17.0 - tomli==2.2.1 - tzlocal==5.3.1 prefix: /opt/conda/envs/next-action
[ "tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_future_threshold", "tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_no_threshold", "tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_past_threshold", "tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_threshold_today" ]
[]
[ "tests/unittests/todotxt/test_task.py::TodoTest::test_task_repr", "tests/unittests/todotxt/test_task.py::TodoTest::test_task_text", "tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_context", "tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_space_before_at_sign", "tests/unittests/todotxt/test_task.py::TodoContextTest::test_one_context", "tests/unittests/todotxt/test_task.py::TodoContextTest::test_two_contexts", "tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_projects", "tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_space_before_at_sign", "tests/unittests/todotxt/test_task.py::TaskProjectTest::test_one_project", "tests/unittests/todotxt/test_task.py::TaskProjectTest::test_two_projects", "tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_faulty_priorities", "tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_no_priority", "tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priorities", "tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priority_at_least", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date_after_priority", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_invalid_creation_date", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_is_future_task", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_creation_date", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_space_after", "tests/unittests/todotxt/test_task.py::CreationDateTest::test_single_digits", "tests/unittests/todotxt/test_task.py::DueDateTest::test_due_today", "tests/unittests/todotxt/test_task.py::DueDateTest::test_future_due_date", "tests/unittests/todotxt/test_task.py::DueDateTest::test_invalid_date", "tests/unittests/todotxt/test_task.py::DueDateTest::test_is_due", "tests/unittests/todotxt/test_task.py::DueDateTest::test_no_due_date", "tests/unittests/todotxt/test_task.py::DueDateTest::test_no_space_after", "tests/unittests/todotxt/test_task.py::DueDateTest::test_past_due_date", "tests/unittests/todotxt/test_task.py::DueDateTest::test_single_digits", "tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_completed", "tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_not_completed", "tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_space_after_x", "tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_x_must_be_lowercase", "tests/unittests/todotxt/test_task.py::ActionableTest::test_completed_task", "tests/unittests/todotxt/test_task.py::ActionableTest::test_default", "tests/unittests/todotxt/test_task.py::ActionableTest::test_future_creation_date", "tests/unittests/todotxt/test_task.py::ActionableTest::test_past_creation_date", "tests/unittests/todotxt/test_task.py::ActionableTest::test_two_dates" ]
[]
Apache License 2.0
2,638
[ "docs/todo.txt", "next_action/todotxt/task.py", "README.md", "next_action/pick_action.py" ]
[ "docs/todo.txt", "next_action/todotxt/task.py", "README.md", "next_action/pick_action.py" ]
MechanicalSoup__MechanicalSoup-212
7d9ee675f465b0e6596b5fcb9f9c9cb7ce8ded74
2018-06-08 01:49:48
f1c71b55f7bf6aef39bf5abb81aaf9ad5e0984e9
diff --git a/docs/ChangeLog.rst b/docs/ChangeLog.rst index 787e4bb..faa9109 100644 --- a/docs/ChangeLog.rst +++ b/docs/ChangeLog.rst @@ -5,6 +5,16 @@ Release Notes Version 1.0 (in development) ============================ +Bug fixes +--------- + +* **Breaking Change:** :class:`~mechanicalsoup.LinkNotFoundError` now derives + from ``Exception`` instead of ``BaseException``. While this will bring the + behavior in line with most people's expectations, it may affect the behavior + of your code if you were heavily relying on this implementation detail in + your exception handling. + [`#203 <https://github.com/MechanicalSoup/MechanicalSoup/issues/203>`__] + Version 0.10 ============ diff --git a/mechanicalsoup/utils.py b/mechanicalsoup/utils.py index 740b35e..9ad7ff0 100644 --- a/mechanicalsoup/utils.py +++ b/mechanicalsoup/utils.py @@ -1,4 +1,4 @@ -class LinkNotFoundError(BaseException): +class LinkNotFoundError(Exception): """Exception raised when mechanicalsoup fails to find something. This happens in situations like (non-exhaustive list):
LinkNotFoundError should not inherit from BaseException Hello, I have code that performs many tests, reporting which tests failed. We therefore implement a try-catch such as ```python try: run_test() except Exception: msg = traceback.format_exc() report_failure() ``` LinkNotFoundError is not caught by this because it inherits from BaseException. Inheriting from BaseException is not recommended in the docs: https://docs.python.org/3/library/exceptions.html I'd like too see this change, or if there is a reason for it I'm curious to hear it.
MechanicalSoup/MechanicalSoup
diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..2400fcb --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,9 @@ +import mechanicalsoup +import pytest + + +def test_LinkNotFoundError(): + with pytest.raises(mechanicalsoup.LinkNotFoundError): + raise mechanicalsoup.utils.LinkNotFoundError + with pytest.raises(Exception): + raise mechanicalsoup.utils.LinkNotFoundError
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
0.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-flake8", "pytest-httpbin", "pytest-mock" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 beautifulsoup4==4.12.3 brotlicffi==1.0.9.2 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 dataclasses==0.8 decorator==5.1.1 flake8==5.0.4 flasgger==0.9.7.1 Flask==2.0.3 gevent==22.10.2 greenlet==2.0.2 httpbin==0.10.0 idna==3.10 importlib-metadata==4.2.0 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 jsonschema==3.2.0 lxml==5.3.1 MarkupSafe==2.0.1 mccabe==0.7.0 -e git+https://github.com/MechanicalSoup/MechanicalSoup.git@7d9ee675f465b0e6596b5fcb9f9c9cb7ce8ded74#egg=MechanicalSoup mistune==2.0.5 packaging==21.3 pluggy==1.0.0 py==1.11.0 pycodestyle==2.9.1 pycparser==2.21 pyflakes==2.5.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 pytest-flake8==1.1.1 pytest-httpbin==1.0.2 pytest-mock==3.6.1 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 soupsieve==2.3.2.post1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0 zope.event==4.6 zope.interface==5.5.2
name: MechanicalSoup channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - beautifulsoup4==4.12.3 - brotlicffi==1.0.9.2 - cffi==1.15.1 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - dataclasses==0.8 - decorator==5.1.1 - flake8==5.0.4 - flasgger==0.9.7.1 - flask==2.0.3 - gevent==22.10.2 - greenlet==2.0.2 - httpbin==0.10.0 - idna==3.10 - importlib-metadata==4.2.0 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - jsonschema==3.2.0 - lxml==5.3.1 - markupsafe==2.0.1 - mccabe==0.7.0 - mistune==2.0.5 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pycparser==2.21 - pyflakes==2.5.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-flake8==1.1.1 - pytest-httpbin==1.0.2 - pytest-mock==3.6.1 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - soupsieve==2.3.2.post1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 - zope-event==4.6 - zope-interface==5.5.2 prefix: /opt/conda/envs/MechanicalSoup
[ "tests/test_utils.py::test_LinkNotFoundError" ]
[ "tests/test_utils.py::flake-8::FLAKE8" ]
[]
[]
MIT License
2,639
[ "docs/ChangeLog.rst", "mechanicalsoup/utils.py" ]
[ "docs/ChangeLog.rst", "mechanicalsoup/utils.py" ]
oasis-open__cti-stix-validator-55
f3dcf83c352c99b5190e9697db7149ce3baf5961
2018-06-08 12:26:02
120c27adf9db76511d01e696d234c35d45f2face
diff --git a/stix2validator/scripts/stix2_validator.py b/stix2validator/scripts/stix2_validator.py index 15bd7b0..8dda167 100644 --- a/stix2validator/scripts/stix2_validator.py +++ b/stix2validator/scripts/stix2_validator.py @@ -292,9 +292,6 @@ def main(): options = ValidationOptions(args) try: - # Set the output level (e.g., quiet vs. verbose) - output.set_level(options.verbose) - if not options.no_cache: init_requests_cache(options.refresh_cache) diff --git a/stix2validator/util.py b/stix2validator/util.py index 4da0be5..327931f 100644 --- a/stix2validator/util.py +++ b/stix2validator/util.py @@ -1,5 +1,7 @@ from collections import Iterable +from .output import error, set_level, set_silent + class ValidationOptions(object): """Collection of validation options which can be set via command line or @@ -72,6 +74,12 @@ class ValidationOptions(object): self.refresh_cache = refresh_cache self.clear_cache = clear_cache + # Set the output level (e.g., quiet vs. verbose) + if self.silent and self.verbose: + error('Error: Output can either be silent or verbose, but not both.') + set_level(self.verbose) + set_silent(self.silent) + # Convert string of comma-separated checks to a list, # and convert check code numbers to names if self.disabled:
handle options --verbose and --silent correctly Related to #50 The correct combination of these two should be as follows: |--verbose | --silent | desired behavior | | --- | --- | --- | |absent (default is False) | absent (default is False) | all messages except those printed by info | |absent (default is False) | present (True) | no messages printed | present (True) | absent (default is False) | all messages, including info are printed | present (True) | present (True) | error | Current behavior is: |--verbose | --silent | current behavior | | --- | --- | --- | |absent (default is False) | absent (default is False) | all messages except those printed by info | |absent (default is False) | present (ignored, so the default - False) | all messages except those printed by info | | present (True) | absent (default is False) | all messages, including info are printed | present (True) | present (ignored, so the default - False) | all messages, including info are printed |
oasis-open/cti-stix-validator
diff --git a/stix2validator/test/bundle_tests.py b/stix2validator/test/bundle_tests.py index 8f417bd..52235ba 100644 --- a/stix2validator/test/bundle_tests.py +++ b/stix2validator/test/bundle_tests.py @@ -1,6 +1,8 @@ import copy import json +import pytest + from . import ValidatorTest VALID_BUNDLE = u""" @@ -51,3 +53,8 @@ class BundleTestCases(ValidatorTest): bundle['objects'][1]['modified'] = "2017-06-22T14:09:00.123Z" self.assertTrueWithOptions(bundle) + + def test_silent_and_verbose(self): + bundle = json.loads(VALID_BUNDLE) + with pytest.raises(SystemExit): + self.assertFalseWithOptions(bundle, silent=True, verbose=True)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 2 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "coverage" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 antlr4-python3-runtime==4.9.3 appdirs==1.4.4 attrs==21.4.0 Babel==2.11.0 bump2version==1.0.1 bumpversion==0.6.0 certifi==2021.5.30 cfgv==3.3.1 charset-normalizer==2.0.12 colorama==0.4.5 coverage==6.2 distlib==0.3.9 docutils==0.18.1 filelock==3.4.1 identify==2.4.4 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.2.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 jsonschema==2.5.1 MarkupSafe==2.0.1 nodeenv==1.6.0 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 pre-commit==2.17.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 requests-cache==0.7.5 simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-prompt==1.5.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 stix2-patterns==2.0.0 -e git+https://github.com/oasis-open/cti-stix-validator.git@f3dcf83c352c99b5190e9697db7149ce3baf5961#egg=stix2_validator toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 url-normalize==1.4.3 urllib3==1.26.20 virtualenv==20.16.2 zipp==3.6.0
name: cti-stix-validator channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - antlr4-python3-runtime==4.9.3 - appdirs==1.4.4 - attrs==21.4.0 - babel==2.11.0 - bump2version==1.0.1 - bumpversion==0.6.0 - cfgv==3.3.1 - charset-normalizer==2.0.12 - colorama==0.4.5 - coverage==6.2 - distlib==0.3.9 - docutils==0.18.1 - filelock==3.4.1 - identify==2.4.4 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.2.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - jsonschema==2.5.1 - markupsafe==2.0.1 - nodeenv==1.6.0 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - pre-commit==2.17.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - requests-cache==0.7.5 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-prompt==1.5.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - stix2-patterns==2.0.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - url-normalize==1.4.3 - urllib3==1.26.20 - virtualenv==20.16.2 - zipp==3.6.0 prefix: /opt/conda/envs/cti-stix-validator
[ "stix2validator/test/bundle_tests.py::BundleTestCases::test_silent_and_verbose" ]
[ "stix2validator/test/bundle_tests.py::BundleTestCases::test_bundle_duplicate_ids", "stix2validator/test/bundle_tests.py::BundleTestCases::test_wellformed_bundle" ]
[ "stix2validator/test/bundle_tests.py::BundleTestCases::test_bundle_created", "stix2validator/test/bundle_tests.py::BundleTestCases::test_bundle_object_categories", "stix2validator/test/bundle_tests.py::BundleTestCases::test_bundle_version" ]
[]
BSD 3-Clause "New" or "Revised" License
2,640
[ "stix2validator/scripts/stix2_validator.py", "stix2validator/util.py" ]
[ "stix2validator/scripts/stix2_validator.py", "stix2validator/util.py" ]
sendgrid__sendgrid-python-583
86708c7908102b171a9dbc92d31c5740aa218423
2018-06-08 14:00:59
56a0ad09e7343e0c95321931bea0745927ad61ed
diff --git a/sendgrid/helpers/mail/personalization.py b/sendgrid/helpers/mail/personalization.py index e49432c..8bb4bed 100644 --- a/sendgrid/helpers/mail/personalization.py +++ b/sendgrid/helpers/mail/personalization.py @@ -116,7 +116,7 @@ class Personalization(object): @substitutions.setter def substitutions(self, value): - self.substitutions = value + self._substitutions = value def add_substitution(self, substitution): """Add a new Substitution to this Personalization.
Attempting to set substitutions on Personalization helper causes infinite regress #### Issue Summary Attempting to set substitutions on a `Personalization` helper directly (rather than with `add_substitution`) throws a `RecursionError`. #### Steps to Reproduce ```python from sendgrid.helpers.mail import Personalization p = Personalization() p.substitutions = [{'a': 0}, {'b': 1}] ``` This throws a `RecursionError`. The offending line is [personalization.py#L119](https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/helpers/mail/personalization.py#L119). I will open a PR as this is an easy fix. #### Technical details: * sendgrid-python Version: `5.3.0` * Python Version: 3.6
sendgrid/sendgrid-python
diff --git a/test/test_mail.py b/test/test_mail.py index 86f21c0..7721b52 100644 --- a/test/test_mail.py +++ b/test/test_mail.py @@ -558,3 +558,7 @@ class UnitTests(unittest.TestCase): tracking_settings.get(), {'click_tracking': {'enable': False, 'enable_text': False}} ) + + def test_directly_setting_substitutions(self): + personalization = Personalization() + personalization.substitutions = [{'a': 0}]
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
5.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "tox", "coverage", "codecov", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc pandoc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 coverage==6.2 dataclasses==0.8 distlib==0.3.9 filelock==3.4.1 Flask==0.10.1 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 MarkupSafe==2.0.1 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-http-client==3.3.7 PyYAML==3.11 requests==2.27.1 -e git+https://github.com/sendgrid/sendgrid-python.git@86708c7908102b171a9dbc92d31c5740aa218423#egg=sendgrid six==1.17.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 Werkzeug==2.0.3 zipp==3.6.0
name: sendgrid-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - dataclasses==0.8 - distlib==0.3.9 - filelock==3.4.1 - flask==0.10.1 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - markupsafe==2.0.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-http-client==3.3.7 - pyyaml==3.11 - requests==2.27.1 - six==1.17.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/sendgrid-python
[ "test/test_mail.py::UnitTests::test_directly_setting_substitutions" ]
[]
[ "test/test_mail.py::UnitTests::test_asm_display_group_limit", "test/test_mail.py::UnitTests::test_disable_tracking", "test/test_mail.py::UnitTests::test_helloEmail", "test/test_mail.py::UnitTests::test_helloEmailAdditionalContent", "test/test_mail.py::UnitTests::test_kitchenSink", "test/test_mail.py::UnitTests::test_sendgridAPIKey", "test/test_mail.py::UnitTests::test_unicode_values_in_substitutions_helper" ]
[]
MIT License
2,641
[ "sendgrid/helpers/mail/personalization.py" ]
[ "sendgrid/helpers/mail/personalization.py" ]
attwad__python-osc-67
73777b367ac4327e9fd0b799366959e50266ebc2
2018-06-08 20:16:51
73777b367ac4327e9fd0b799366959e50266ebc2
diff --git a/pythonosc/osc_message.py b/pythonosc/osc_message.py index 911dbcf..b89a0d6 100644 --- a/pythonosc/osc_message.py +++ b/pythonosc/osc_message.py @@ -41,6 +41,8 @@ class OscMessage(object): val, index = osc_types.get_int(self._dgram, index) elif param == "f": # Float. val, index = osc_types.get_float(self._dgram, index) + elif param == "d": # Double. + val, index = osc_types.get_double(self._dgram, index) elif param == "s": # String. val, index = osc_types.get_string(self._dgram, index) elif param == "b": # Blob. diff --git a/pythonosc/osc_message_builder.py b/pythonosc/osc_message_builder.py index 0f9bfba..28128fb 100644 --- a/pythonosc/osc_message_builder.py +++ b/pythonosc/osc_message_builder.py @@ -12,6 +12,7 @@ class OscMessageBuilder(object): """Builds arbitrary OscMessage instances.""" ARG_TYPE_FLOAT = "f" + ARG_TYPE_DOUBLE = "d" ARG_TYPE_INT = "i" ARG_TYPE_STRING = "s" ARG_TYPE_BLOB = "b" @@ -24,8 +25,8 @@ class OscMessageBuilder(object): ARG_TYPE_ARRAY_STOP = "]" _SUPPORTED_ARG_TYPES = ( - ARG_TYPE_FLOAT, ARG_TYPE_INT, ARG_TYPE_BLOB, ARG_TYPE_STRING, ARG_TYPE_RGBA, - ARG_TYPE_MIDI, ARG_TYPE_TRUE, ARG_TYPE_FALSE) + ARG_TYPE_FLOAT, ARG_TYPE_DOUBLE, ARG_TYPE_INT, ARG_TYPE_BLOB, ARG_TYPE_STRING, + ARG_TYPE_RGBA, ARG_TYPE_MIDI, ARG_TYPE_TRUE, ARG_TYPE_FALSE) def __init__(self, address=None): """Initialize a new builder for a message. @@ -143,6 +144,8 @@ class OscMessageBuilder(object): dgram += osc_types.write_int(value) elif arg_type == self.ARG_TYPE_FLOAT: dgram += osc_types.write_float(value) + elif arg_type == self.ARG_TYPE_DOUBLE: + dgram += osc_types.write_double(value) elif arg_type == self.ARG_TYPE_BLOB: dgram += osc_types.write_blob(value) elif arg_type == self.ARG_TYPE_RGBA: diff --git a/pythonosc/parsing/osc_types.py b/pythonosc/parsing/osc_types.py index a91003b..5558399 100644 --- a/pythonosc/parsing/osc_types.py +++ b/pythonosc/parsing/osc_types.py @@ -21,6 +21,7 @@ IMMEDIATELY = 0 # Datagram length in bytes for types that have a fixed size. _INT_DGRAM_LEN = 4 _FLOAT_DGRAM_LEN = 4 +_DOUBLE_DGRAM_LEN = 8 _DATE_DGRAM_LEN = _INT_DGRAM_LEN * 2 # Strings and blob dgram length is always a multiple of 4 bytes. _STRING_DGRAM_PAD = 4 @@ -199,6 +200,42 @@ def get_float(dgram, start_index): raise ParseError('Could not parse datagram %s' % e) +def write_double(val): + """Returns the datagram for the given double parameter value + + Raises: + - BuildError if the double could not be converted. + """ + try: + return struct.pack('>d', val) + except struct.error as e: + raise BuildError('Wrong argument value passed: {}'.format(e)) + + +def get_double(dgram, start_index): + """Get a 64-bit big-endian IEEE 754 floating point number from the datagram. + + Args: + dgram: A datagram packet. + start_index: An index where the double starts in the datagram. + + Returns: + A tuple containing the double and the new end index. + + Raises: + ParseError if the datagram could not be parsed. + """ + try: + if len(dgram[start_index:]) < _DOUBLE_DGRAM_LEN: + raise ParseError('Datagram is too short') + return ( + struct.unpack('>d', + dgram[start_index:start_index + _DOUBLE_DGRAM_LEN])[0], + start_index + _DOUBLE_DGRAM_LEN) + except (struct.error, TypeError) as e: + raise ParseError('Could not parse datagram {}'.format(e)) + + def get_blob(dgram, start_index): """ Get a blob from the datagram.
Add support for 64 bits double type `unhandled type: d` warnings are all that gets returned, no handlers even end up running.
attwad/python-osc
diff --git a/pythonosc/test/parsing/test_osc_types.py b/pythonosc/test/parsing/test_osc_types.py index 0863fd5..8734ad1 100644 --- a/pythonosc/test/parsing/test_osc_types.py +++ b/pythonosc/test/parsing/test_osc_types.py @@ -232,6 +232,39 @@ class TestFloat(unittest.TestCase): self.assertEqual((0, 4), osc_types.get_float(dgram, 0)) +class TestDouble(unittest.TestCase): + + def test_get_double(self): + cases = { + b'\x00\x00\x00\x00\x00\x00\x00\x00': (0.0, 8), + b'?\xf0\x00\x00\x00\x00\x00\x00': (1.0, 8), + b'@\x00\x00\x00\x00\x00\x00\x00': (2.0, 8), + b'\xbf\xf0\x00\x00\x00\x00\x00\x00': (-1.0, 8), + b'\xc0\x00\x00\x00\x00\x00\x00\x00': (-2.0, 8), + + b"\x00\x00\x00\x00\x00\x00\x00\x00GARBAGE": (0.0, 8), + } + + for dgram, expected in cases.items(): + self.assertAlmostEqual(expected, osc_types.get_double(dgram, 0)) + + def test_get_double_raises_on_wrong_dgram(self): + cases = [True] + + for case in cases: + self.assertRaises(osc_types.ParseError, osc_types.get_double, case, 0) + + def test_get_double_raises_on_type_error(self): + cases = [None] + + for case in cases: + self.assertRaises(osc_types.ParseError, osc_types.get_double, case, 0) + + def test_datagram_too_short_pads(self): + dgram = b'\x00' * 2 + self.assertRaises(osc_types.ParseError, osc_types.get_double, dgram, 0) + + class TestBlob(unittest.TestCase): def test_get_blob(self): diff --git a/pythonosc/test/test_osc_message_builder.py b/pythonosc/test/test_osc_message_builder.py index c9720b4..d5bbe25 100644 --- a/pythonosc/test/test_osc_message_builder.py +++ b/pythonosc/test/test_osc_message_builder.py @@ -43,14 +43,15 @@ class TestOscMessageBuilder(unittest.TestCase): builder.add_arg([1, ["abc"]], [builder.ARG_TYPE_INT, [builder.ARG_TYPE_STRING]]) builder.add_arg(4278255360, builder.ARG_TYPE_RGBA) builder.add_arg((1, 145, 36, 125), builder.ARG_TYPE_MIDI) - self.assertEqual(len("fisTFb[i[s]]")*2+2, len(builder.args)) + builder.add_arg(1e-9, builder.ARG_TYPE_DOUBLE) + self.assertEqual(len("fisTFb[i[s]]")*2+3, len(builder.args)) self.assertEqual("/SYNC", builder.address) builder.address = '/SEEK' msg = builder.build() self.assertEqual("/SEEK", msg.address) self.assertSequenceEqual( [4.0, 2, "value", True, False, b"\x01\x02\x03", [1, ["abc"]]] * 2 + - [4278255360, (1, 145, 36, 125)], + [4278255360, (1, 145, 36, 125), 1e-9], msg.params) def test_long_list(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work -e git+https://github.com/attwad/python-osc.git@73777b367ac4327e9fd0b799366959e50266ebc2#egg=python_osc tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: python-osc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/python-osc
[ "pythonosc/test/parsing/test_osc_types.py::TestDouble::test_datagram_too_short_pads", "pythonosc/test/parsing/test_osc_types.py::TestDouble::test_get_double", "pythonosc/test/parsing/test_osc_types.py::TestDouble::test_get_double_raises_on_type_error", "pythonosc/test/parsing/test_osc_types.py::TestDouble::test_get_double_raises_on_wrong_dgram", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_all_param_types" ]
[]
[ "pythonosc/test/parsing/test_osc_types.py::TestString::test_get_string", "pythonosc/test/parsing/test_osc_types.py::TestString::test_get_string_raises_on_wrong_dgram", "pythonosc/test/parsing/test_osc_types.py::TestString::test_get_string_raises_on_wrong_start_index_negative", "pythonosc/test/parsing/test_osc_types.py::TestString::test_get_string_raises_when_datagram_too_short", "pythonosc/test/parsing/test_osc_types.py::TestInteger::test_datagram_too_short", "pythonosc/test/parsing/test_osc_types.py::TestInteger::test_get_integer", "pythonosc/test/parsing/test_osc_types.py::TestInteger::test_get_integer_raises_on_type_error", "pythonosc/test/parsing/test_osc_types.py::TestInteger::test_get_integer_raises_on_wrong_start_index", "pythonosc/test/parsing/test_osc_types.py::TestInteger::test_get_integer_raises_on_wrong_start_index_negative", "pythonosc/test/parsing/test_osc_types.py::TestRGBA::test_datagram_too_short", "pythonosc/test/parsing/test_osc_types.py::TestRGBA::test_get_rgba", "pythonosc/test/parsing/test_osc_types.py::TestRGBA::test_get_rgba_raises_on_type_error", "pythonosc/test/parsing/test_osc_types.py::TestRGBA::test_get_rgba_raises_on_wrong_start_index", "pythonosc/test/parsing/test_osc_types.py::TestRGBA::test_get_rgba_raises_on_wrong_start_index_negative", "pythonosc/test/parsing/test_osc_types.py::TestMidi::test_datagram_too_short", "pythonosc/test/parsing/test_osc_types.py::TestMidi::test_get_midi", "pythonosc/test/parsing/test_osc_types.py::TestMidi::test_get_midi_raises_on_type_error", "pythonosc/test/parsing/test_osc_types.py::TestMidi::test_get_midi_raises_on_wrong_start_index", "pythonosc/test/parsing/test_osc_types.py::TestMidi::test_get_midi_raises_on_wrong_start_index_negative", "pythonosc/test/parsing/test_osc_types.py::TestDate::test_get_ttag", "pythonosc/test/parsing/test_osc_types.py::TestDate::test_get_ttag_raises_on_type_error", "pythonosc/test/parsing/test_osc_types.py::TestDate::test_get_ttag_raises_on_wrong_start_index", "pythonosc/test/parsing/test_osc_types.py::TestDate::test_get_ttag_raises_on_wrong_start_index_negative", "pythonosc/test/parsing/test_osc_types.py::TestDate::test_ttag_datagram_too_short", "pythonosc/test/parsing/test_osc_types.py::TestFloat::test_datagram_too_short_pads", "pythonosc/test/parsing/test_osc_types.py::TestFloat::test_get_float", "pythonosc/test/parsing/test_osc_types.py::TestFloat::test_get_float_raises_on_type_error", "pythonosc/test/parsing/test_osc_types.py::TestFloat::test_get_float_raises_on_wrong_dgram", "pythonosc/test/parsing/test_osc_types.py::TestBlob::test_get_blob", "pythonosc/test/parsing/test_osc_types.py::TestBlob::test_get_blob_raises_on_wrong_dgram", "pythonosc/test/parsing/test_osc_types.py::TestBlob::test_get_blob_raises_on_wrong_start_index", "pythonosc/test/parsing/test_osc_types.py::TestBlob::test_get_blob_raises_too_short_buffer", "pythonosc/test/parsing/test_osc_types.py::TestBlob::test_get_blog_raises_on_wrong_start_index_negative", "pythonosc/test/parsing/test_osc_types.py::TestNTPTimestamp::test_datagram_too_short", "pythonosc/test/parsing/test_osc_types.py::TestNTPTimestamp::test_immediately_dgram", "pythonosc/test/parsing/test_osc_types.py::TestNTPTimestamp::test_origin_of_time", "pythonosc/test/parsing/test_osc_types.py::TestNTPTimestamp::test_write_date", "pythonosc/test/parsing/test_osc_types.py::TestBuildMethods::test_blob", "pythonosc/test/parsing/test_osc_types.py::TestBuildMethods::test_blob_raises", "pythonosc/test/parsing/test_osc_types.py::TestBuildMethods::test_float", "pythonosc/test/parsing/test_osc_types.py::TestBuildMethods::test_float_raises", "pythonosc/test/parsing/test_osc_types.py::TestBuildMethods::test_int", "pythonosc/test/parsing/test_osc_types.py::TestBuildMethods::test_int_raises", "pythonosc/test/parsing/test_osc_types.py::TestBuildMethods::test_string", "pythonosc/test/parsing/test_osc_types.py::TestBuildMethods::test_string_raises", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_add_arg_invalid_infered_type", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_bool_encoding", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_build_noarg_message", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_build_wrong_type_raises", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_just_address", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_long_list", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_no_address_raises", "pythonosc/test/test_osc_message_builder.py::TestOscMessageBuilder::test_wrong_param_raise" ]
[]
The Unlicense
2,642
[ "pythonosc/parsing/osc_types.py", "pythonosc/osc_message.py", "pythonosc/osc_message_builder.py" ]
[ "pythonosc/parsing/osc_types.py", "pythonosc/osc_message.py", "pythonosc/osc_message_builder.py" ]