Dataset Viewer
Auto-converted to Parquet Duplicate
instance_id
stringlengths
13
57
patch
stringlengths
273
19.3k
repo
stringlengths
9
53
base_commit
stringlengths
40
40
hints_text
stringclasses
1 value
test_patch
stringlengths
212
195k
problem_statement
stringlengths
40
7.66k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
144
PASS_TO_PASS
listlengths
0
1.46k
meta
dict
created_at
stringdate
2015-11-16 22:59:02
2024-04-24 11:36:26
license
stringclasses
7 values
__index_level_0__
int64
1
6.4k
alexmojaki__pure_eval-12
diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index fb89d46..0000000 --- a/.travis.yml +++ /dev/null @@ -1,32 +0,0 @@ -dist: xenial -language: python -sudo: false - -python: - - 3.5 - - 3.6 - - 3.7 - - 3.8-dev - - 3.9-dev - -env: - global: - - PURE_EVAL_SLOW_TESTS=1 - - COVERALLS_PARALLEL=true - -before_install: - - pip install --upgrade coveralls setuptools>=44 setuptools_scm>=3.4.3 pep517 - -install: - - pip install ".[tests]" - -script: - - coverage run --branch --include='pure_eval/*' -m pytest --junitxml=./rspec.xml - - coverage report -m - -after_success: - - coveralls - -notifications: - webhooks: https://coveralls.io/webhook - email: false diff --git a/MANIFEST.in b/MANIFEST.in index 800dfd8..09204c8 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,3 @@ include LICENSE.txt include pure_eval/py.typed +include README.md diff --git a/make_release.sh b/make_release.sh index f9b8308..f0c1ac8 100755 --- a/make_release.sh +++ b/make_release.sh @@ -26,5 +26,5 @@ export TAG="v${1}" git tag "${TAG}" git push origin master "${TAG}" rm -rf ./build ./dist -python3 -m pep517.build -bs . +python -m build --sdist --wheel . twine upload ./dist/*.whl dist/*.tar.gz diff --git a/pure_eval/core.py b/pure_eval/core.py index 0a0381e..748f051 100644 --- a/pure_eval/core.py +++ b/pure_eval/core.py @@ -15,6 +15,7 @@ from pure_eval.utils import ( of_standard_types, is_any, of_type, + ensure_dict, ) @@ -39,9 +40,9 @@ class Evaluator: """ return cls(ChainMap( - frame.f_locals, - frame.f_globals, - frame.f_builtins, + ensure_dict(frame.f_locals), + ensure_dict(frame.f_globals), + ensure_dict(frame.f_builtins), )) def __getitem__(self, node: ast.expr) -> Any: diff --git a/pure_eval/utils.py b/pure_eval/utils.py index 139d6dd..a8a3730 100644 --- a/pure_eval/utils.py +++ b/pure_eval/utils.py @@ -189,3 +189,13 @@ def copy_ast_without_context(x): return list(map(copy_ast_without_context, x)) else: return x + + +def ensure_dict(x): + """ + Handles invalid non-dict inputs + """ + try: + return dict(x) + except Exception: + return {} diff --git a/setup.cfg b/setup.cfg index 330cb29..3d07ca9 100644 --- a/setup.cfg +++ b/setup.cfg @@ -14,6 +14,7 @@ classifiers = Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 + Programming Language :: Python :: 3.10 License :: OSI Approved :: MIT License Operating System :: OS Independent @@ -22,7 +23,7 @@ packages = pure_eval install_requires = include_package_data = True tests_require = pytest -setup_requires = setuptools>=44; wheel; setuptools_scm[toml]>=3.4.3 +setup_requires = setuptools>=44; setuptools_scm[toml]>=3.4.3 [options.extras_require] tests = pytest diff --git a/tox.ini b/tox.ini index aa83fa0..3feff03 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py{35,36,37,38,39} +envlist = py{35,36,37,38,39,310} [testenv] commands = pytest
alexmojaki/pure_eval
b5e1617805fbb1e77101de1ad372d2a0d58053ce
diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml new file mode 100644 index 0000000..7f68be5 --- /dev/null +++ b/.github/workflows/pytest.yml @@ -0,0 +1,36 @@ +name: Tests +on: [push, pull_request] +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.7, 3.8, 3.9, 3.10-dev] + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: run tests + env: + PURE_EVAL_SLOW_TESTS: 1 + run: | + pip install -U pip + pip install --upgrade coveralls setuptools setuptools_scm pep517 + pip install .[tests] + coverage run --source pure_eval -m pytest + coverage report -m + - name: Coveralls Python + uses: AndreMiras/coveralls-python-action@v20201129 + with: + parallel: true + flag-name: test-${{ matrix.python-version }} + coveralls_finish: + needs: build + runs-on: ubuntu-latest + steps: + - name: Coveralls Finished + uses: AndreMiras/coveralls-python-action@v20201129 + with: + parallel-finished: true diff --git a/tests/test_utils.py b/tests/test_utils.py index 315ecc5..172f50e 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -17,6 +17,7 @@ from pure_eval.utils import ( safe_name, typing_annotation_samples, is_standard_types, + ensure_dict, ) @@ -126,3 +127,10 @@ def test_is_standard_types(): assert is_standard_types(lst, deep=False, check_dict_values=True) assert is_standard_types(lst[0], deep=True, check_dict_values=True) assert not is_standard_types(lst, deep=True, check_dict_values=True) + + +def test_ensure_dict(): + assert ensure_dict({}) == {} + assert ensure_dict([]) == {} + assert ensure_dict('foo') == {} + assert ensure_dict({'a': 1}) == {'a': 1}
TypeError for malformed metaclass example In https://github.com/ipython/ipython/issues/13481, the following example used to show a fatal error in IPython: ```python class X(type): def __prepare__(cls, *args, **kwargs): return [] class Y(metaclass=X): pass ``` If I try the same example with friendly-traceback, I also get a fatal error, with the following as part of a long traceback: ``` During handling of the above exception, another exception occurred: Traceback (most recent call last): File "LOCAL:\pure_eval\core.py", line 445, in group_expressions for node, value in expressions: File "FRIENDLY:\info_variables.py", line 119, in <genexpr> for nodes, obj in group_expressions( File "LOCAL:\pure_eval\core.py", line 358, in find_expressions value = self[node] File "LOCAL:\pure_eval\core.py", line 68, in __getitem__ self._cache[node] = result = self._handle(node) File "LOCAL:\pure_eval\core.py", line 89, in _handle return self.names[node.id] TypeError: list indices must be integers or slices, not str ``` In https://github.com/friendly-traceback/friendly-traceback/commit/276ec1b85f7c5949b0e5d1fb325b30b59b57d9c5, I've guarded against this type of fatal error. I didn't see any evidence that the IPython crash is caused by pure_eval or an other library of yours, but I thought you might want to know about it - and possibly include some safeguards in pure_eval.
0.0
b5e1617805fbb1e77101de1ad372d2a0d58053ce
[ "tests/test_utils.py::test_sys_modules", "tests/test_utils.py::test_repr_cannot_eval", "tests/test_utils.py::test_safe_name_types", "tests/test_utils.py::test_safe_name_samples", "tests/test_utils.py::test_safe_name_direct", "tests/test_utils.py::test_is_standard_types", "tests/test_utils.py::test_ensure_dict" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-01-22 15:31:07+00:00
mit
1,034
executablebooks__MyST-Parser-734
diff --git a/myst_parser/sphinx_ext/myst_refs.py b/myst_parser/sphinx_ext/myst_refs.py index 8a4dc20..74edcb3 100644 --- a/myst_parser/sphinx_ext/myst_refs.py +++ b/myst_parser/sphinx_ext/myst_refs.py @@ -178,9 +178,12 @@ class MystReferenceResolver(ReferencesResolver): ) assert self.app.builder - ref_node = make_refnode( - self.app.builder, from_docname, ref_docname, targetid, innernode - ) + try: + ref_node = make_refnode( + self.app.builder, from_docname, ref_docname, targetid, innernode + ) + except NoUri: + ref_node = innernode node.replace_self(ref_node) def resolve_myst_ref_any(
executablebooks/MyST-Parser
585ce9acfb282c555e86b436fa5cdc449b80f27d
diff --git a/tests/test_sphinx/sourcedirs/texi_table/index.md b/tests/test_sphinx/sourcedirs/texi_table/index.md deleted file mode 100644 index 9face4b..0000000 --- a/tests/test_sphinx/sourcedirs/texi_table/index.md +++ /dev/null @@ -1,3 +0,0 @@ -| foo | bar | -| --- | --- | -| baz | bim | diff --git a/tests/test_sphinx/sourcedirs/texi_table/conf.py b/tests/test_sphinx/sourcedirs/texinfo/conf.py similarity index 100% rename from tests/test_sphinx/sourcedirs/texi_table/conf.py rename to tests/test_sphinx/sourcedirs/texinfo/conf.py diff --git a/tests/test_sphinx/sourcedirs/texinfo/file.md b/tests/test_sphinx/sourcedirs/texinfo/file.md new file mode 100644 index 0000000..eeea438 --- /dev/null +++ b/tests/test_sphinx/sourcedirs/texinfo/file.md @@ -0,0 +1,3 @@ +--- +orphan: true +--- diff --git a/tests/test_sphinx/sourcedirs/texinfo/index.md b/tests/test_sphinx/sourcedirs/texinfo/index.md new file mode 100644 index 0000000..c0f15f9 --- /dev/null +++ b/tests/test_sphinx/sourcedirs/texinfo/index.md @@ -0,0 +1,9 @@ +Check that NoURIError is handled correctly: + +[](file.md) + +Check that tables can be built: + +| foo | bar | +| --- | --- | +| baz | bim | diff --git a/tests/test_sphinx/test_sphinx_builds.py b/tests/test_sphinx/test_sphinx_builds.py index b5b9acc..a41e96b 100644 --- a/tests/test_sphinx/test_sphinx_builds.py +++ b/tests/test_sphinx/test_sphinx_builds.py @@ -564,15 +564,11 @@ def test_fieldlist_extension( @pytest.mark.sphinx( buildername="texinfo", - srcdir=os.path.join(SOURCE_DIR, "texi_table"), + srcdir=os.path.join(SOURCE_DIR, "texinfo"), freshenv=True, ) -def test_texinfo_table( - app, - status, - warning, -): - """Test that tables can be built with the Texinfo builder.""" +def test_texinfo(app, status, warning): + """Test Texinfo builds.""" app.build() assert "build succeeded" in status.getvalue() # Build succeeded warnings = warning.getvalue().strip()
sphinx.errors.NoUri ### Describe the bug **context** I don't know whether this error relates to MyST-Parser, but I began getting this error after MyST-Parser 0.19.0 was released. **expectation** I expected no errors like my previous builds with myst v0.18.1. https://readthedocs.org/projects/deepmd/builds/19634134/ **bug** But instead, the `sphinx.errors.NoUri` error happens after myst v0.19.0 was released. https://readthedocs.org/projects/deepmd/builds/19635616/ https://readthedocs.org/projects/deepmd/builds/19635930/ https://readthedocs.org/projects/deepmd/builds/19647300/ Here's an error message I ran into... ```console Traceback (most recent call last): File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/cmd/build.py", line 284, in build_main app.build(args.force_all, args.filenames) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/application.py", line 347, in build self.builder.build_update() File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/builders/__init__.py", line 308, in build_update self.build(['__all__'], to_build) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/builders/__init__.py", line 377, in build self.write(docnames, list(updated_docnames), method) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/builders/latex/__init__.py", line 288, in write doctree = self.assemble_doctree( File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/builders/latex/__init__.py", line 354, in assemble_doctree self.env.resolve_references(largetree, indexfile, self) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/environment/__init__.py", line 656, in resolve_references self.apply_post_transforms(doctree, fromdocname) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/environment/__init__.py", line 668, in apply_post_transforms transformer.apply_transforms() File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/transforms/__init__.py", line 80, in apply_transforms super().apply_transforms() File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/docutils/transforms/__init__.py", line 171, in apply_transforms transform.apply(**kwargs) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/transforms/post_transforms/__init__.py", line 37, in apply self.run(**kwargs) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/myst_parser/sphinx_ext/myst_refs.py", line 80, in run self.resolve_myst_ref_doc(node) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/myst_parser/sphinx_ext/myst_refs.py", line 181, in resolve_myst_ref_doc ref_node = make_refnode( File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/util/nodes.py", line 550, in make_refnode node['refuri'] = builder.get_relative_uri(fromdocname, todocname) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/builders/latex/__init__.py", line 141, in get_relative_uri return self.get_target_uri(to, typ) File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/builders/latex/__init__.py", line 135, in get_target_uri raise NoUri(docname, typ) sphinx.errors.NoUri: ('install/install-tf.2.8', None) Exception occurred: File "/home/docs/checkouts/readthedocs.org/user_builds/deepmd/conda/latest/lib/python3.9/site-packages/sphinx/builders/latex/__init__.py", line 135, in get_target_uri raise NoUri(docname, typ) sphinx.errors.NoUri: ('install/install-tf.2.8', None) The full traceback has been saved in /tmp/sphinx-err-0n6n9ja3.log, if you want to report the issue to the developers. Please also report this if it was a user error, so that a better error message can be provided next time. A bug report can be filed in the tracker at <https://github.com/sphinx-doc/sphinx/issues>. Thanks! ``` **problem** Indeed I don't know the reason. ### Reproduce the bug This is my repository: https://github.com/deepmodeling/deepmd-kit/tree/devel/doc The error happens in this file: https://github.com/deepmodeling/deepmd-kit/blob/devel/doc/install/install-from-source.md with this sentence: ```md You may follow [the instruction](install-tf.2.8.md) or run the script `$deepmd_source_dir/source/install/build_tf.py` to install the corresponding C++ interface. ``` ### List your environment The error happens on the Read the doc server. ```py python 3.9.16 Sphinx 6.1.3 myst-parser 0.19.0 sphinx_rtd_theme 1.2.0 ```
0.0
585ce9acfb282c555e86b436fa5cdc449b80f27d
[ "tests/test_sphinx/test_sphinx_builds.py::test_texinfo" ]
[ "tests/test_sphinx/test_sphinx_builds.py::test_references", "tests/test_sphinx/test_sphinx_builds.py::test_references_singlehtml", "tests/test_sphinx/test_sphinx_builds.py::test_heading_slug_func", "tests/test_sphinx/test_sphinx_builds.py::test_includes", "tests/test_sphinx/test_sphinx_builds.py::test_include_from_rst", "tests/test_sphinx/test_sphinx_builds.py::test_footnotes", "tests/test_sphinx/test_sphinx_builds.py::test_commonmark_only", "tests/test_sphinx/test_sphinx_builds.py::test_substitutions", "tests/test_sphinx/test_sphinx_builds.py::test_gettext", "tests/test_sphinx/test_sphinx_builds.py::test_gettext_html", "tests/test_sphinx/test_sphinx_builds.py::test_gettext_additional_targets", "tests/test_sphinx/test_sphinx_builds.py::test_mathjax_warning", "tests/test_sphinx/test_sphinx_builds.py::test_fieldlist_extension" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-03-02 05:26:24+00:00
mit
2,208
tefra__pytuber-20
diff --git a/pytuber/cli.py b/pytuber/cli.py index f432978..2c7d6e6 100644 --- a/pytuber/cli.py +++ b/pytuber/cli.py @@ -68,6 +68,8 @@ def add(): """Add playlist.""" +add.add_command(core.add_from_editor) +add.add_command(core.add_from_file) add.add_command(lastfm.add) diff --git a/pytuber/core/commands/__init__.py b/pytuber/core/commands/__init__.py index 27fbf7e..888f16e 100644 --- a/pytuber/core/commands/__init__.py +++ b/pytuber/core/commands/__init__.py @@ -7,6 +7,7 @@ from pytuber.core.commands.cmd_show import show from pytuber.core.commands.cmd_autocomplete import autocomplete from pytuber.core.commands.cmd_clean import clean from pytuber.core.commands.cmd_quota import quota +from pytuber.core.commands.cmd_add import add_from_editor, add_from_file __all__ = [ "setup", @@ -18,4 +19,6 @@ __all__ = [ "autocomplete", "clean", "quota", + "add_from_editor", + "add_from_file", ] diff --git a/pytuber/core/commands/cmd_add.py b/pytuber/core/commands/cmd_add.py new file mode 100644 index 0000000..e0af66b --- /dev/null +++ b/pytuber/core/commands/cmd_add.py @@ -0,0 +1,97 @@ +from typing import List + +import click +from tabulate import tabulate + +from pytuber.core.models import ( + PlaylistManager, + PlaylistType, + Provider, + TrackManager, +) +from pytuber.lastfm.commands.cmd_add import option_title +from pytuber.utils import magenta + + [email protected]("editor") +@option_title() +def add_from_editor(title: str) -> None: + """Create playlist in a text editor.""" + marker = ( + "\n\n# Copy/Paste your track list and hit save!\n" + "# One line per track, make sure it doesn't start with a #\n" + "# Separate the track artist and title with a single dash `-`\n" + ) + message = click.edit(marker) + create_playlist(title, parse_tracklist(message or "")) + + [email protected]("file") [email protected]("file", type=click.Path(), required=True) +@option_title() +def add_from_file(file: str, title: str) -> None: + """Import a playlist from a text file.""" + + with open(file, "r") as fp: + text = fp.read() + + create_playlist(title, parse_tracklist(text or "")) + + +def parse_tracklist(text): + tracks: List[tuple] = [] + for line in text.split("\n"): + line = line.strip() + if not line or line.startswith("#"): + continue + + parts = line.split("-", 1) + if len(parts) != 2: + continue + + artist, track = list(map(str.strip, parts)) + if not artist or not track or (artist, track) in tracks: + continue + + tracks.append((artist, track)) + + return tracks + + +def create_playlist(title, tracks): + if not tracks: + return click.secho("Tracklist is empty, aborting...") + + click.clear() + click.secho( + "{}\n\n{}\n".format( + tabulate( # type: ignore + [ + (magenta("Title:"), title), + (magenta("Tracks:"), len(tracks)), + ], + tablefmt="plain", + colalign=("right", "left"), + ), + tabulate( # type: ignore + [ + (i + 1, track[0], track[1]) + for i, track in enumerate(tracks) + ], + headers=("No", "Artist", "Track Name"), + ), + ) + ) + click.confirm("Are you sure you want to save this playlist?", abort=True) + playlist = PlaylistManager.set( + dict( + type=PlaylistType.EDITOR, + provider=Provider.user, + title=title.strip(), + tracks=[ + TrackManager.set(dict(artist=artist, name=name)).id + for artist, name in tracks + ], + ) + ) + click.secho("Added playlist: {}!".format(playlist.id)) diff --git a/pytuber/core/commands/s b/pytuber/core/commands/s new file mode 100644 index 0000000..e69de29 diff --git a/pytuber/core/models.py b/pytuber/core/models.py index 861373d..53f12c0 100644 --- a/pytuber/core/models.py +++ b/pytuber/core/models.py @@ -16,6 +16,14 @@ from pytuber.utils import timestamp class Provider(enum.Enum): lastfm = "last.fm" youtube = "youtube" + user = "user" + + def __str__(self): + return self.value + + +class PlaylistType(enum.Enum): + EDITOR = "editor" def __str__(self): return self.value diff --git a/pytuber/lastfm/commands/cmd_add.py b/pytuber/lastfm/commands/cmd_add.py index 1fd87a3..1f451b1 100644 --- a/pytuber/lastfm/commands/cmd_add.py +++ b/pytuber/lastfm/commands/cmd_add.py @@ -16,7 +16,7 @@ from .cmd_fetch import fetch_tracks @click.group("lastfm") def add(): - """Last.fm is a music service that learns what you love.""" + """Create playlists from Last.fm api.""" option_limit = partial(
tefra/pytuber
ae19a31c38462821ec22cd7376914ddce6a15a4f
diff --git a/tests/core/commands/test_cmd_add.py b/tests/core/commands/test_cmd_add.py new file mode 100644 index 0000000..c1fdd90 --- /dev/null +++ b/tests/core/commands/test_cmd_add.py @@ -0,0 +1,104 @@ +from unittest import mock + +from pytuber import cli +from pytuber.core.commands.cmd_add import create_playlist, parse_tracklist +from pytuber.core.models import PlaylistManager, PlaylistType, Provider +from tests.utils import CommandTestCase, PlaylistFixture + + +class CommandAddTests(CommandTestCase): + @mock.patch("click.edit") + @mock.patch("pytuber.core.commands.cmd_add.create_playlist") + @mock.patch("pytuber.core.commands.cmd_add.parse_tracklist") + def test_add_from_editor(self, parse_tracklist, create_playlist, clk_edit): + clk_edit.return_value = "foo" + parse_tracklist.return_value = ["a", "b"] + self.runner.invoke( + cli, ["add", "editor", "--title", "My Cool Playlist"] + ) + parse_tracklist.assert_called_once_with("foo") + create_playlist.assert_called_once_with("My Cool Playlist", ["a", "b"]) + + @mock.patch("pytuber.core.commands.cmd_add.create_playlist") + @mock.patch("pytuber.core.commands.cmd_add.parse_tracklist") + def test_add_from_file(self, parse_tracklist, create_playlist): + parse_tracklist.return_value = ["a", "b"] + with self.runner.isolated_filesystem(): + with open("hello.txt", "w") as f: + f.write("foo") + + self.runner.invoke( + cli, + ["add", "file", "hello.txt", "--title", "My Cool Playlist"], + ) + + parse_tracklist.assert_called_once_with("foo") + create_playlist.assert_called_once_with( + "My Cool Playlist", ["a", "b"] + ) + + +class CommandAddUtilsTests(CommandTestCase): + def test_parse_tracklist(self): + text = "\n".join( + ( + "Queen - Bohemian Rhapsody", + " Queen - Bohemian Rhapsody", + "Queen -I want to break free", + "#" " ", + "Wrong Format", + ) + ) + actual = parse_tracklist(text) + expected = [ + ("Queen", "Bohemian Rhapsody"), + ("Queen", "I want to break free"), + ] + self.assertEqual(expected, actual) + + @mock.patch("pytuber.core.commands.cmd_add.magenta") + @mock.patch.object(PlaylistManager, "set") + @mock.patch("click.confirm") + @mock.patch("click.secho") + @mock.patch("click.clear") + def test_create_playlist(self, clear, secho, confirm, set, magenta): + magenta.side_effect = lambda x: x + set.return_value = PlaylistFixture.one() + tracks = [ + ("Queen", "Bohemian Rhapsody"), + ("Queen", "I want to break free"), + ] + create_playlist("My Cool Playlist", tracks) + + expected_ouput = ( + "Title: My Cool Playlist", + "Tracks: 2", + "", + " No Artist Track Name", + "---- -------- --------------------", + " 1 Queen Bohemian Rhapsody", + " 2 Queen I want to break free", + ) + + self.assertOutput(expected_ouput, secho.call_args_list[0][0][0]) + self.assertEqual( + "Added playlist: id_a!", secho.call_args_list[1][0][0] + ) + + clear.assert_called_once_with() + confirm.assert_called_once_with( + "Are you sure you want to save this playlist?", abort=True + ) + set.assert_called_once_with( + dict( + type=PlaylistType.EDITOR, + provider=Provider.user, + title="My Cool Playlist", + tracks=["55a4d2b", "b045fee"], + ) + ) + + @mock.patch("click.secho") + def test_create_playlist_empty_tracks(self, secho): + create_playlist("foo", []) + secho.assert_called_once_with("Tracklist is empty, aborting...")
Support raw string format A file containing tracks one per line and a direct copy/paste in the terminal
0.0
ae19a31c38462821ec22cd7376914ddce6a15a4f
[ "tests/core/commands/test_cmd_add.py::CommandAddTests::test_add_from_editor", "tests/core/commands/test_cmd_add.py::CommandAddTests::test_add_from_file", "tests/core/commands/test_cmd_add.py::CommandAddUtilsTests::test_create_playlist", "tests/core/commands/test_cmd_add.py::CommandAddUtilsTests::test_create_playlist_empty_tracks", "tests/core/commands/test_cmd_add.py::CommandAddUtilsTests::test_parse_tracklist" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-02-10 17:39:49+00:00
mit
5,839
joscha0__daily-wiki-13
diff --git a/getwiki.py b/getwiki.py index 395aac1..0c1db59 100644 --- a/getwiki.py +++ b/getwiki.py @@ -33,4 +33,4 @@ def get_wiki(language): img = imgs[0] img['src'] = 'http:'+img['src'] - return img, text + return str(img), str(text) diff --git a/sendmail.py b/sendmail.py index 41288e4..1538d0e 100644 --- a/sendmail.py +++ b/sendmail.py @@ -10,7 +10,7 @@ from getwiki import get_wiki def send_email(img, text, email): unsubscribe_tag = f'<a href="https://daily-wiki-newsletter.herokuapp.com/unsubscribe/{email}">unsubscribe</a>' - msg = MIMEText(str(img) + 3*'<br>' + text + 3 * + msg = MIMEText(img + 3*'<br>' + text + 3 * '<br>' + unsubscribe_tag, 'html') msg['Subject'] = 'today wiki' msg['From'] = '[email protected]' @@ -42,9 +42,16 @@ if __name__ == "__main__": languages = ["en", "de", "fr", "sv", "ja", "zh"] wikis = {} for language in languages: - img, text = get_wiki(language) + try: + img, text = get_wiki(language) + except: + print(f"Error getting article for {language}") wikis[language] = (img, text) data = firestore.getusers() for email in data: img, text = wikis[data[email]["language"]] - send_email(img, text, email) + try: + send_email(img, text, email) + print(f"Sent email to {email}") + except: + print(f"Email failed to send to {email}")
joscha0/daily-wiki
1630910248178e4d9d865f66e7d8b186b39d1315
diff --git a/tests/test_getwiki.py b/tests/test_getwiki.py new file mode 100644 index 0000000..ac45dae --- /dev/null +++ b/tests/test_getwiki.py @@ -0,0 +1,28 @@ +import unittest +from getwiki import get_wiki + + +class TestFirestore(unittest.TestCase): + + def test_get_wiki(self): + languages = ["en", "de", "fr", "sv", "ja", "zh"] + wikis = {} + for language in languages: + img, text = get_wiki(language) + wikis[language] = (img, text) + output = True + for key, value in wikis.items(): + if output == False: + break + if not value[0].startswith('<img'): + print('\n\nNot an Image:'+value[0]) + if len(value[1]) < 10: + print('\n\nShort Text:'+value[0]) + self.assertIn(key, languages) + self.assertIsInstance(value, tuple) + self.assertIsInstance(value[0], str) + self.assertIsInstance(value[1], str) + self.assertTrue(len(value) == 2) + + if __name__ == "__main__": + unittest.main()
fix email invalid if one email is invalid throws error `Traceback (most recent call last): File "sendmail.py", line 50, in <module> send_email(img, text, email) File "sendmail.py", line 21, in send_email s.sendmail(msg['From'], msg['To'], msg.as_string()) File "/app/.heroku/python/lib/python3.6/smtplib.py", line 881, in sendmail raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'[email protected]': (450, b'4.1.2 <[email protected]>: Recipient address rejected: Domain not found')} `
0.0
1630910248178e4d9d865f66e7d8b186b39d1315
[ "tests/test_getwiki.py::TestFirestore::test_get_wiki" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-10-21 12:46:56+00:00
mit
3,337
Turbo87__utm-31
diff --git a/utm/conversion.py b/utm/conversion.py old mode 100755 new mode 100644 index d21742a..449f3d1 --- a/utm/conversion.py +++ b/utm/conversion.py @@ -216,13 +216,13 @@ def latlon_to_zone_number(latitude, longitude): return 32 if 72 <= latitude <= 84 and longitude >= 0: - if longitude <= 9: + if longitude < 9: return 31 - elif longitude <= 21: + elif longitude < 21: return 33 - elif longitude <= 33: + elif longitude < 33: return 35 - elif longitude <= 42: + elif longitude < 42: return 37 return int((longitude + 180) / 6) + 1
Turbo87/utm
4c7c13f2b2b9c01a8581392641aeb8bbda6aba6f
diff --git a/test/test_utm.py b/test/test_utm.py index 55686d7..c820cea 100755 --- a/test/test_utm.py +++ b/test/test_utm.py @@ -231,5 +231,22 @@ class Zone32V(unittest.TestCase): self.assert_zone_equal(UTM.from_latlon(64, 12), 33, 'W') +class TestRightBoundaries(unittest.TestCase): + + def assert_zone_equal(self, result, expected_number): + self.assertEqual(result[2], expected_number) + + def test_limits(self): + self.assert_zone_equal(UTM.from_latlon(40, 0), 31) + self.assert_zone_equal(UTM.from_latlon(40, 5.999999), 31) + self.assert_zone_equal(UTM.from_latlon(40, 6), 32) + + self.assert_zone_equal(UTM.from_latlon(72, 0), 31) + self.assert_zone_equal(UTM.from_latlon(72, 5.999999), 31) + self.assert_zone_equal(UTM.from_latlon(72, 6), 31) + self.assert_zone_equal(UTM.from_latlon(72, 8.999999), 31) + self.assert_zone_equal(UTM.from_latlon(72, 9), 33) + + if __name__ == '__main__': unittest.main()
UTM zone exceptions error By definition zones are left-closed, right-open intervals, e.g. zone 31: 0 <= latitude < 6. In function latlon_to_zone_number: ``` if 72 <= latitude <= 84 and longitude >= 0: if longitude <= 9: return 31 elif longitude <= 21: return 33 elif longitude <= 33: return 35 elif longitude <= 42: return 37 ``` For latitudes >=72, this results in: zone 31: 0 <= longitude <= 9 zone 33: 9 < longitude <= 21 zone 35: 21< longitude <= 33 zone 37: 33< longitude <= 42 but for latitudes < 72: zone 37: 36 <= latitude < 42
0.0
4c7c13f2b2b9c01a8581392641aeb8bbda6aba6f
[ "test/test_utm.py::TestRightBoundaries::test_limits" ]
[ "test/test_utm.py::KnownValues::test_from_latlon", "test/test_utm.py::KnownValues::test_to_latlon", "test/test_utm.py::BadInput::test_from_latlon_range_checks", "test/test_utm.py::BadInput::test_to_latlon_range_checks", "test/test_utm.py::Zone32V::test_above", "test/test_utm.py::Zone32V::test_below", "test/test_utm.py::Zone32V::test_inside", "test/test_utm.py::Zone32V::test_left_of", "test/test_utm.py::Zone32V::test_right_of" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-06-26 10:44:15+00:00
mit
799
wireservice__agate-637
diff --git a/agate/aggregations/any.py b/agate/aggregations/any.py index 70fa702..67a9651 100644 --- a/agate/aggregations/any.py +++ b/agate/aggregations/any.py @@ -32,7 +32,7 @@ class Any(Aggregation): column = table.columns[self._column_name] data = column.values() - if isinstance(column.data_type, Boolean): + if isinstance(column.data_type, Boolean) and self._test is None: return any(data) return any(self._test(d) for d in data)
wireservice/agate
0d2671358cdea94c83bd8f28b5a6718a9326b033
diff --git a/tests/test_aggregations.py b/tests/test_aggregations.py index c3c8fbb..11eefe1 100644 --- a/tests/test_aggregations.py +++ b/tests/test_aggregations.py @@ -138,6 +138,7 @@ class TestBooleanAggregation(unittest.TestCase): table = Table(rows, ['test'], [Boolean()]) Any('test').validate(table) self.assertEqual(Any('test').run(table), False) + self.assertEqual(Any('test', lambda r: not r).run(table), True) def test_all(self): rows = [
agate.All cannot test whether all data is False If the column data type is boolean, test gets overwritten to search for True values.
0.0
0d2671358cdea94c83bd8f28b5a6718a9326b033
[ "tests/test_aggregations.py::TestBooleanAggregation::test_any" ]
[ "tests/test_aggregations.py::TestSimpleAggregation::test_all", "tests/test_aggregations.py::TestSimpleAggregation::test_any", "tests/test_aggregations.py::TestSimpleAggregation::test_count", "tests/test_aggregations.py::TestSimpleAggregation::test_count_column", "tests/test_aggregations.py::TestSimpleAggregation::test_count_value", "tests/test_aggregations.py::TestSimpleAggregation::test_has_nulls", "tests/test_aggregations.py::TestSimpleAggregation::test_summary", "tests/test_aggregations.py::TestBooleanAggregation::test_all", "tests/test_aggregations.py::TestDateTimeAggregation::test_max", "tests/test_aggregations.py::TestDateTimeAggregation::test_min", "tests/test_aggregations.py::TestNumberAggregation::test_deciles", "tests/test_aggregations.py::TestNumberAggregation::test_iqr", "tests/test_aggregations.py::TestNumberAggregation::test_mad", "tests/test_aggregations.py::TestNumberAggregation::test_max", "tests/test_aggregations.py::TestNumberAggregation::test_max_precision", "tests/test_aggregations.py::TestNumberAggregation::test_mean", "tests/test_aggregations.py::TestNumberAggregation::test_mean_with_nulls", "tests/test_aggregations.py::TestNumberAggregation::test_median", "tests/test_aggregations.py::TestNumberAggregation::test_min", "tests/test_aggregations.py::TestNumberAggregation::test_mode", "tests/test_aggregations.py::TestNumberAggregation::test_percentiles", "tests/test_aggregations.py::TestNumberAggregation::test_percentiles_locate", "tests/test_aggregations.py::TestNumberAggregation::test_population_stdev", "tests/test_aggregations.py::TestNumberAggregation::test_population_variance", "tests/test_aggregations.py::TestNumberAggregation::test_quartiles", "tests/test_aggregations.py::TestNumberAggregation::test_quartiles_locate", "tests/test_aggregations.py::TestNumberAggregation::test_quintiles", "tests/test_aggregations.py::TestNumberAggregation::test_stdev", "tests/test_aggregations.py::TestNumberAggregation::test_sum", "tests/test_aggregations.py::TestNumberAggregation::test_variance", "tests/test_aggregations.py::TestTextAggregation::test_max_length", "tests/test_aggregations.py::TestTextAggregation::test_max_length_invalid" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2016-10-30 16:11:15+00:00
mit
6,247
encode__httpcore-641
diff --git a/httpcore/_async/http11.py b/httpcore/_async/http11.py index 7ad3664..32fa3a6 100644 --- a/httpcore/_async/http11.py +++ b/httpcore/_async/http11.py @@ -20,6 +20,7 @@ from .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError, + WriteError, map_exceptions, ) from .._models import Origin, Request, Response @@ -84,10 +85,21 @@ class AsyncHTTP11Connection(AsyncConnectionInterface): try: kwargs = {"request": request} - async with Trace("send_request_headers", logger, request, kwargs) as trace: - await self._send_request_headers(**kwargs) - async with Trace("send_request_body", logger, request, kwargs) as trace: - await self._send_request_body(**kwargs) + try: + async with Trace( + "send_request_headers", logger, request, kwargs + ) as trace: + await self._send_request_headers(**kwargs) + async with Trace("send_request_body", logger, request, kwargs) as trace: + await self._send_request_body(**kwargs) + except WriteError: + # If we get a write error while we're writing the request, + # then we supress this error and move on to attempting to + # read the response. Servers can sometimes close the request + # pre-emptively and then respond with a well formed HTTP + # error response. + pass + async with Trace( "receive_response_headers", logger, request, kwargs ) as trace: diff --git a/httpcore/_sync/http11.py b/httpcore/_sync/http11.py index edcce72..0cc100e 100644 --- a/httpcore/_sync/http11.py +++ b/httpcore/_sync/http11.py @@ -20,6 +20,7 @@ from .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError, + WriteError, map_exceptions, ) from .._models import Origin, Request, Response @@ -84,10 +85,21 @@ class HTTP11Connection(ConnectionInterface): try: kwargs = {"request": request} - with Trace("send_request_headers", logger, request, kwargs) as trace: - self._send_request_headers(**kwargs) - with Trace("send_request_body", logger, request, kwargs) as trace: - self._send_request_body(**kwargs) + try: + with Trace( + "send_request_headers", logger, request, kwargs + ) as trace: + self._send_request_headers(**kwargs) + with Trace("send_request_body", logger, request, kwargs) as trace: + self._send_request_body(**kwargs) + except WriteError: + # If we get a write error while we're writing the request, + # then we supress this error and move on to attempting to + # read the response. Servers can sometimes close the request + # pre-emptively and then respond with a well formed HTTP + # error response. + pass + with Trace( "receive_response_headers", logger, request, kwargs ) as trace:
encode/httpcore
80ff02f1276eba3cb6b6493b3f0b033a26d6348d
diff --git a/tests/_async/test_connection.py b/tests/_async/test_connection.py index 8b29942..b6ee0c7 100644 --- a/tests/_async/test_connection.py +++ b/tests/_async/test_connection.py @@ -9,10 +9,13 @@ from httpcore import ( SOCKET_OPTION, AsyncHTTPConnection, AsyncMockBackend, + AsyncMockStream, AsyncNetworkStream, ConnectError, ConnectionNotAvailable, Origin, + RemoteProtocolError, + WriteError, ) @@ -83,7 +86,109 @@ async def test_concurrent_requests_not_available_on_http11_connections(): await conn.request("GET", "https://example.com/") [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.anyio +async def test_write_error_with_response_sent(): + """ + If a server half-closes the connection while the client is sending + the request, it may still send a response. In this case the client + should successfully read and return the response. + + See also the `test_write_error_without_response_sent` test above. + """ + + class ErrorOnRequestTooLargeStream(AsyncMockStream): + def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: + super().__init__(buffer, http2) + self.count = 0 + + async def write( + self, buffer: bytes, timeout: typing.Optional[float] = None + ) -> None: + self.count += len(buffer) + + if self.count > 1_000_000: + raise WriteError() + + class ErrorOnRequestTooLarge(AsyncMockBackend): + async def connect_tcp( + self, + host: str, + port: int, + timeout: typing.Optional[float] = None, + local_address: typing.Optional[str] = None, + socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, + ) -> AsyncMockStream: + return ErrorOnRequestTooLargeStream(list(self._buffer), http2=self._http2) + + origin = Origin(b"https", b"example.com", 443) + network_backend = ErrorOnRequestTooLarge( + [ + b"HTTP/1.1 413 Payload Too Large\r\n", + b"Content-Type: plain/text\r\n", + b"Content-Length: 37\r\n", + b"\r\n", + b"Request body exceeded 1,000,000 bytes", + ] + ) + + async with AsyncHTTPConnection( + origin=origin, network_backend=network_backend, keepalive_expiry=5.0 + ) as conn: + content = b"x" * 10_000_000 + response = await conn.request("POST", "https://example.com/", content=content) + assert response.status == 413 + assert response.content == b"Request body exceeded 1,000,000 bytes" + + [email protected] [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") +async def test_write_error_without_response_sent(): + """ + If a server fully closes the connection while the client is sending + the request, then client should raise an error. + + See also the `test_write_error_with_response_sent` test above. + """ + + class ErrorOnRequestTooLargeStream(AsyncMockStream): + def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: + super().__init__(buffer, http2) + self.count = 0 + + async def write( + self, buffer: bytes, timeout: typing.Optional[float] = None + ) -> None: + self.count += len(buffer) + + if self.count > 1_000_000: + raise WriteError() + + class ErrorOnRequestTooLarge(AsyncMockBackend): + async def connect_tcp( + self, + host: str, + port: int, + timeout: typing.Optional[float] = None, + local_address: typing.Optional[str] = None, + socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, + ) -> AsyncMockStream: + return ErrorOnRequestTooLargeStream(list(self._buffer), http2=self._http2) + + origin = Origin(b"https", b"example.com", 443) + network_backend = ErrorOnRequestTooLarge([]) + + async with AsyncHTTPConnection( + origin=origin, network_backend=network_backend, keepalive_expiry=5.0 + ) as conn: + content = b"x" * 10_000_000 + with pytest.raises(RemoteProtocolError) as exc_info: + await conn.request("POST", "https://example.com/", content=content) + assert str(exc_info.value) == "Server disconnected without sending a response." + + [email protected] [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") async def test_http2_connection(): origin = Origin(b"https", b"example.com", 443) network_backend = AsyncMockBackend( diff --git a/tests/_sync/test_connection.py b/tests/_sync/test_connection.py index 9e0c403..37c82e0 100644 --- a/tests/_sync/test_connection.py +++ b/tests/_sync/test_connection.py @@ -9,10 +9,13 @@ from httpcore import ( SOCKET_OPTION, HTTPConnection, MockBackend, + MockStream, NetworkStream, ConnectError, ConnectionNotAvailable, Origin, + RemoteProtocolError, + WriteError, ) @@ -83,7 +86,109 @@ def test_concurrent_requests_not_available_on_http11_connections(): conn.request("GET", "https://example.com/") [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") +def test_write_error_with_response_sent(): + """ + If a server half-closes the connection while the client is sending + the request, it may still send a response. In this case the client + should successfully read and return the response. + + See also the `test_write_error_without_response_sent` test above. + """ + + class ErrorOnRequestTooLargeStream(MockStream): + def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: + super().__init__(buffer, http2) + self.count = 0 + + def write( + self, buffer: bytes, timeout: typing.Optional[float] = None + ) -> None: + self.count += len(buffer) + + if self.count > 1_000_000: + raise WriteError() + + class ErrorOnRequestTooLarge(MockBackend): + def connect_tcp( + self, + host: str, + port: int, + timeout: typing.Optional[float] = None, + local_address: typing.Optional[str] = None, + socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, + ) -> MockStream: + return ErrorOnRequestTooLargeStream(list(self._buffer), http2=self._http2) + + origin = Origin(b"https", b"example.com", 443) + network_backend = ErrorOnRequestTooLarge( + [ + b"HTTP/1.1 413 Payload Too Large\r\n", + b"Content-Type: plain/text\r\n", + b"Content-Length: 37\r\n", + b"\r\n", + b"Request body exceeded 1,000,000 bytes", + ] + ) + + with HTTPConnection( + origin=origin, network_backend=network_backend, keepalive_expiry=5.0 + ) as conn: + content = b"x" * 10_000_000 + response = conn.request("POST", "https://example.com/", content=content) + assert response.status == 413 + assert response.content == b"Request body exceeded 1,000,000 bytes" + + + [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") +def test_write_error_without_response_sent(): + """ + If a server fully closes the connection while the client is sending + the request, then client should raise an error. + + See also the `test_write_error_with_response_sent` test above. + """ + + class ErrorOnRequestTooLargeStream(MockStream): + def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: + super().__init__(buffer, http2) + self.count = 0 + + def write( + self, buffer: bytes, timeout: typing.Optional[float] = None + ) -> None: + self.count += len(buffer) + + if self.count > 1_000_000: + raise WriteError() + + class ErrorOnRequestTooLarge(MockBackend): + def connect_tcp( + self, + host: str, + port: int, + timeout: typing.Optional[float] = None, + local_address: typing.Optional[str] = None, + socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, + ) -> MockStream: + return ErrorOnRequestTooLargeStream(list(self._buffer), http2=self._http2) + + origin = Origin(b"https", b"example.com", 443) + network_backend = ErrorOnRequestTooLarge([]) + + with HTTPConnection( + origin=origin, network_backend=network_backend, keepalive_expiry=5.0 + ) as conn: + content = b"x" * 10_000_000 + with pytest.raises(RemoteProtocolError) as exc_info: + conn.request("POST", "https://example.com/", content=content) + assert str(exc_info.value) == "Server disconnected without sending a response." + + + [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") def test_http2_connection(): origin = Origin(b"https", b"example.com", 443) network_backend = MockBackend(
Handle HTTP/1.1 half-closed connections gracefully. There's an HTTP/1.1 case that can occur where... * The client starts sending a request. * The server half-closes the connection. * The server sends a response, such as an HTTP 413 Content Too Large. Currently our behaviour here is that we'll see a `WriteError` occur here and never get a response. A more graceful behaviour is handle this case, and return the 413 response. Prompted via https://github.com/encode/httpx/discussions/2503. *A follow up question to this will be... is there an equivalent to this for HTTP/2 streams? But let's only consider that once we've dealt with this as a precursor.*
0.0
80ff02f1276eba3cb6b6493b3f0b033a26d6348d
[ "tests/_async/test_connection.py::test_write_error_with_response_sent[asyncio]", "tests/_async/test_connection.py::test_write_error_without_response_sent[asyncio]", "tests/_async/test_connection.py::test_write_error_with_response_sent[trio]", "tests/_async/test_connection.py::test_write_error_without_response_sent[trio]", "tests/_sync/test_connection.py::test_write_error_with_response_sent", "tests/_sync/test_connection.py::test_write_error_without_response_sent" ]
[ "tests/_async/test_connection.py::test_http_connection[asyncio]", "tests/_async/test_connection.py::test_concurrent_requests_not_available_on_http11_connections[asyncio]", "tests/_async/test_connection.py::test_http2_connection[asyncio]", "tests/_async/test_connection.py::test_request_to_incorrect_origin[asyncio]", "tests/_async/test_connection.py::test_connection_retries[asyncio]", "tests/_async/test_connection.py::test_connection_retries_tls[asyncio]", "tests/_async/test_connection.py::test_uds_connections[asyncio]", "tests/_async/test_connection.py::test_http_connection[trio]", "tests/_async/test_connection.py::test_concurrent_requests_not_available_on_http11_connections[trio]", "tests/_async/test_connection.py::test_http2_connection[trio]", "tests/_async/test_connection.py::test_request_to_incorrect_origin[trio]", "tests/_async/test_connection.py::test_connection_retries[trio]", "tests/_async/test_connection.py::test_connection_retries_tls[trio]", "tests/_async/test_connection.py::test_uds_connections[trio]", "tests/_sync/test_connection.py::test_http_connection", "tests/_sync/test_connection.py::test_concurrent_requests_not_available_on_http11_connections", "tests/_sync/test_connection.py::test_http2_connection", "tests/_sync/test_connection.py::test_request_to_incorrect_origin", "tests/_sync/test_connection.py::test_connection_retries", "tests/_sync/test_connection.py::test_connection_retries_tls", "tests/_sync/test_connection.py::test_uds_connections" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-13 19:52:44+00:00
bsd-3-clause
2,109
devopsspiral__KubeLibrary-124
diff --git a/CHANGELOG.md b/CHANGELOG.md index b7b2f42..e8800dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,8 +5,14 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## In progress + +## [0.8.1] - 2022-12-16 +### Added - Add proxy configuration fetched from `HTTP_PROXY` or `http_proxy` environment variable +### Fixed +Fix disabling cert validation [#124](https://github.com/devopsspiral/KubeLibrary/pull/124) + ## [0.8.0] - 2022-10-27 ### Added - Add function list_namespaced_stateful_set_by_pattern [#114](https://github.com/devopsspiral/KubeLibrary/pull/113) by [@siaomingjeng](https://github.com/siaomingjeng) diff --git a/src/KubeLibrary/KubeLibrary.py b/src/KubeLibrary/KubeLibrary.py index 3f73adc..ebff896 100755 --- a/src/KubeLibrary/KubeLibrary.py +++ b/src/KubeLibrary/KubeLibrary.py @@ -1,6 +1,5 @@ import json import re -import ssl import urllib3 from os import environ @@ -276,7 +275,7 @@ class KubeLibrary: def _add_api(self, reference, class_name): self.__dict__[reference] = class_name(self.api_client) if not self.cert_validation: - self.__dict__[reference].api_client.rest_client.pool_manager.connection_pool_kw['cert_reqs'] = ssl.CERT_NONE + self.__dict__[reference].api_client.configuration.verify_ssl = False def k8s_api_ping(self): """Performs GET on /api/v1/ for simple check of API availability. diff --git a/src/KubeLibrary/version.py b/src/KubeLibrary/version.py index 8675559..73baf8f 100644 --- a/src/KubeLibrary/version.py +++ b/src/KubeLibrary/version.py @@ -1,1 +1,1 @@ -version = "0.8.0" +version = "0.8.1"
devopsspiral/KubeLibrary
7f4037c283a38751f9a31160944a17e7b80ec97b
diff --git a/test/test_KubeLibrary.py b/test/test_KubeLibrary.py index b99291b..7cae67e 100644 --- a/test/test_KubeLibrary.py +++ b/test/test_KubeLibrary.py @@ -1,7 +1,6 @@ import json import mock import re -import ssl import unittest from KubeLibrary import KubeLibrary from KubeLibrary.exceptions import BearerTokenWithPrefixException @@ -306,7 +305,7 @@ class TestKubeLibrary(unittest.TestCase): kl = KubeLibrary(kube_config='test/resources/k3d', cert_validation=False) for api in TestKubeLibrary.apis: target = getattr(kl, api) - self.assertEqual(target.api_client.rest_client.pool_manager.connection_pool_kw['cert_reqs'], ssl.CERT_NONE) + self.assertEqual(target.api_client.configuration.verify_ssl, False) @responses.activate def test_KubeLibrary_inits_with_bearer_token(self):
certificate verify failed issue when using Get Namespaced Pod Exec When using the Get Namespaced Pod Exec keywork on a k8s cluster using a custom CA, the following error occurs : ``` ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get issuer certificate (_ssl.c:1129) ``` Other keywords (Read Namespaced Pod Status, List Namespaced Pod By Pattern ...) are working as expected. As a quick fix, I'm adding the following line in the _add_api method of the library : ``` def _add_api(self, reference, class_name): self.__dict__[reference] = class_name(self.api_client) if not self.cert_validation: self.__dict__[reference].api_client.rest_client.pool_manager.connection_pool_kw['cert_reqs'] = ssl.CERT_NONE self.__dict__[reference].api_client.configuration.verify_ssl = False ``` Am I missing something regarding the library configuration ? Versions : ``` KubeLibrary: 0.8.0 Python: 3.9.13 Kubernetes: 1.24 ``` KubeLibrary : ``` Library KubeLibrary kube_config=${KUBECONFIG_FILE} cert_validation=False KubeLibrary.Get Namespaced Pod Exec ... name=my-pod ... namespace=${namespace} ... argv_cmd=${command} ```
0.0
7f4037c283a38751f9a31160944a17e7b80ec97b
[ "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_deployment_by_pattern" ]
[ "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_delete", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespace", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_inits_with_bearer_token", "test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_endpoints", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_daemon_set", "test/test_KubeLibrary.py::TestKubeLibrary::test_inits_all_api_clients", "test/test_KubeLibrary.py::TestKubeLibrary::test_assert_pod_has_annotations", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_secret_by_pattern", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_create", "test/test_KubeLibrary.py::TestKubeLibrary::test_get_namespaced_exec_without_container", "test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_cron_job", "test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_ingress", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_service_account_by_pattern", "test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_horizontal_pod_autoscaler", "test/test_KubeLibrary.py::TestKubeLibrary::test_assert_container_has_env_vars", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_ingress", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_replace", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_job_by_pattern", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_inits_with_context", "test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_daemon_set", "test/test_KubeLibrary.py::TestKubeLibrary::test_get_matching_pods_in_namespace", "test/test_KubeLibrary.py::TestKubeLibrary::test_get_namespaced_exec_not_argv_and_list", "test/test_KubeLibrary.py::TestKubeLibrary::test_get_configmaps_in_namespace", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_cluster_role_binding", "test/test_KubeLibrary.py::TestKubeLibrary::test_filter_containers_images", "test/test_KubeLibrary.py::TestKubeLibrary::test_filter_pods_containers_statuses_by_name", "test/test_KubeLibrary.py::TestKubeLibrary::test_evaluate_callable_from_k8s_client", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_persistent_volume_claim_by_pattern", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_init", "test/test_KubeLibrary.py::TestKubeLibrary::test_get_kubelet_version", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_role_binding", "test/test_KubeLibrary.py::TestKubeLibrary::test_generate_alphanumeric_str", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_inits_from_kubeconfig", "test/test_KubeLibrary.py::TestKubeLibrary::test_assert_pod_has_labels", "test/test_KubeLibrary.py::TestKubeLibrary::test_filter_pods_containers_by_name", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_patch", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_inits_with_bearer_token_with_ca_crt", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_role", "test/test_KubeLibrary.py::TestKubeLibrary::test_filter_containers_resources", "test/test_KubeLibrary.py::TestKubeLibrary::test_get_namespaced_exec_with_container", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_fails_for_wrong_context", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_stateful_set_by_pattern", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_persistent_volume_claim", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_horizontal_pod_autoscaler", "test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_get", "test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_service", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_service", "test/test_KubeLibrary.py::TestKubeLibrary::test_inits_with_bearer_token_raises_BearerTokenWithPrefixException", "test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_pod_status", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_replica_set_by_pattern", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_cron_job", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_pod_by_pattern", "test/test_KubeLibrary.py::TestKubeLibrary::test_list_cluster_role" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-16 14:17:09+00:00
mit
1,894
PyFstat__PyFstat-489
diff --git a/docs/source/pyfstat.utils.rst b/docs/source/pyfstat.utils.rst index 260c2a7..1465894 100644 --- a/docs/source/pyfstat.utils.rst +++ b/docs/source/pyfstat.utils.rst @@ -7,7 +7,7 @@ Most of these are used internally by other parts of the package and are of interest mostly only for developers, but others can also be helpful for end users. -Functions in these modules can be directly acessed via ``pyfstat.utils`` +Functions in these modules can be directly accessed via ``pyfstat.utils`` without explicitly mentioning the specific module in where they reside. (E.g. just call ``pyfstat.utils.some_function``, not ``pyfstat.utils.some_topic.some_function``.) @@ -15,6 +15,14 @@ not ``pyfstat.utils.some_topic.some_function``.) Submodules ---------- +pyfstat.utils.atoms module +-------------------------- + +.. automodule:: pyfstat.utils.atoms + :members: + :undoc-members: + :show-inheritance: + pyfstat.utils.cli module ------------------------ diff --git a/pyfstat/core.py b/pyfstat/core.py index 9f0b3f1..023ec12 100644 --- a/pyfstat/core.py +++ b/pyfstat/core.py @@ -1317,19 +1317,10 @@ class ComputeFstat(BaseSearchClass): # and return the maximum of that? idx_maxTwoF = self.FstatMap.get_maxF_idx() for X in range(self.FstatResults.numDetectors): - # For each detector, we need to build a MultiFstatAtomVector - # because that's what the Fstat map function expects. - singleIFOmultiFatoms = lalpulsar.CreateMultiFstatAtomVector(1) - # The first [0] index on the multiFatoms here is over frequency bins; + # The [0] index on the multiFatoms here is over frequency bins; # we always operate on a single bin. - singleIFOmultiFatoms.data[0] = lalpulsar.CreateFstatAtomVector( - self.FstatResults.multiFatoms[0].data[X].length - ) - singleIFOmultiFatoms.data[0].TAtom = ( - self.FstatResults.multiFatoms[0].data[X].TAtom - ) - singleIFOmultiFatoms.data[0].data = ( - self.FstatResults.multiFatoms[0].data[X].data + singleIFOmultiFatoms = utils.extract_singleIFOmultiFatoms_from_multiAtoms( + self.FstatResults.multiFatoms[0], X ) FXstatMap, timingFXstatMap = tcw.call_compute_transient_fstat_map( self.tCWFstatMapVersion, @@ -1987,19 +1978,10 @@ class SemiCoherentSearch(ComputeFstat): "This function is available only if singleFstats or BSGL options were set." ) for X in range(self.FstatResults.numDetectors): - # For each detector, we need to build a MultiFstatAtomVector - # because that's what the Fstat map function expects. - singleIFOmultiFatoms = lalpulsar.CreateMultiFstatAtomVector(1) - # The first [0] index on the multiFatoms here is over frequency bins; + # The [0] index on the multiFatoms here is over frequency bins; # we always operate on a single bin. - singleIFOmultiFatoms.data[0] = lalpulsar.CreateFstatAtomVector( - self.FstatResults.multiFatoms[0].data[X].length - ) - singleIFOmultiFatoms.data[0].TAtom = ( - self.FstatResults.multiFatoms[0].data[X].TAtom - ) - singleIFOmultiFatoms.data[0].data = ( - self.FstatResults.multiFatoms[0].data[X].data + singleIFOmultiFatoms = utils.extract_singleIFOmultiFatoms_from_multiAtoms( + self.FstatResults.multiFatoms[0], X ) FXstatMap = lalpulsar.ComputeTransientFstatMap( multiFstatAtoms=singleIFOmultiFatoms, diff --git a/pyfstat/utils/__init__.py b/pyfstat/utils/__init__.py index 7230235..2161e53 100644 --- a/pyfstat/utils/__init__.py +++ b/pyfstat/utils/__init__.py @@ -6,6 +6,7 @@ and are of interest mostly only for developers, but others can also be helpful for end users. """ +from .atoms import copy_FstatAtomVector, extract_singleIFOmultiFatoms_from_multiAtoms from .cli import match_commandlines, run_commandline from .converting import ( convert_aPlus_aCross_to_h0_cosi, diff --git a/pyfstat/utils/atoms.py b/pyfstat/utils/atoms.py new file mode 100644 index 0000000..39eb2f8 --- /dev/null +++ b/pyfstat/utils/atoms.py @@ -0,0 +1,69 @@ +import logging + +import lalpulsar + +logger = logging.getLogger(__name__) + + +def extract_singleIFOmultiFatoms_from_multiAtoms( + multiAtoms: lalpulsar.MultiFstatAtomVector, X: int +) -> lalpulsar.MultiFstatAtomVector: + """Extract a length-1 MultiFstatAtomVector from a larger MultiFstatAtomVector. + + The result is needed as input to ``lalpulsar.ComputeTransientFstatMap`` in some places. + + The new object is freshly allocated, + and we do a deep copy of the actual per-timestamp atoms. + + Parameters + ------- + multiAtoms: + Fully allocated multi-detector struct of `length > X`. + X: + The detector index for which to extract atoms. + Returns + ------- + singleIFOmultiFatoms: + Length-1 MultiFstatAtomVector with only the data for detector `X`. + """ + if X >= multiAtoms.length: + raise ValueError( + f"Detector index {X} is out of range for multiAtoms of length {multiAtoms.length}." + ) + singleIFOmultiFatoms = lalpulsar.CreateMultiFstatAtomVector(1) + singleIFOmultiFatoms.data[0] = lalpulsar.CreateFstatAtomVector( + multiAtoms.data[X].length + ) + # we deep-copy the entries of the atoms vector, + # since just assigning the whole array can cause a segfault + # from memory cleanup in looping over this function + copy_FstatAtomVector(singleIFOmultiFatoms.data[0], multiAtoms.data[X]) + return singleIFOmultiFatoms + + +def copy_FstatAtomVector( + dest: lalpulsar.FstatAtomVector, src: lalpulsar.FstatAtomVector +): + """Deep-copy an FstatAtomVector with all its per-SFT FstatAtoms. + + The two vectors must have the same length, + and the destination vector must already be allocated. + + Parameters + ------- + dest: + The destination vector to copy to. + Must already be allocated. + Will be modified in-place. + src: + The source vector to copy from. + """ + if dest.length != src.length: + raise ValueError( + f"Lengths of destination and source vectors do not match. ({dest.length} != {src.length})" + ) + dest.TAtom = src.TAtom + for k in range(dest.length): + # this is now copying the actual FstatAtom object, + # with its actual data in memory (no more pointers) + dest.data[k] = src.data[k]
PyFstat/PyFstat
c502303284fc4fba4dbe34eee1063d0f75d8b7e5
diff --git a/tests/test_utils/test_atoms.py b/tests/test_utils/test_atoms.py new file mode 100644 index 0000000..a425fec --- /dev/null +++ b/tests/test_utils/test_atoms.py @@ -0,0 +1,75 @@ +import lalpulsar +import pytest + +from pyfstat.utils import ( + copy_FstatAtomVector, + extract_singleIFOmultiFatoms_from_multiAtoms, +) + + [email protected] +def arbitrary_singleAtoms(): + single_atoms = lalpulsar.CreateFstatAtomVector(5) + + single_atoms.TAtom = 1800 + + for i in range(single_atoms.length): + + for attr in [ + "timestamp", + "a2_alpha", + "b2_alpha", + "ab_alpha", + "Fa_alpha", + "Fb_alpha", + ]: + setattr(single_atoms.data[i], attr, i) + + return single_atoms + + [email protected] +def arbitrary_multiAtoms(arbitrary_singleAtoms): + ma = lalpulsar.CreateMultiFstatAtomVector(1) + ma.data[0] = arbitrary_singleAtoms + return ma + + +def compare_FstatAtomVector(vectorA, vectorB): + + for attr in ["TAtom", "length"]: + assert getattr(vectorA, attr) == getattr(vectorB, attr) + + for i in range(vectorA.length): + + for attr in [ + "timestamp", + "a2_alpha", + "b2_alpha", + "ab_alpha", + "Fa_alpha", + "Fb_alpha", + ]: + assert getattr(vectorA.data[i], attr) == getattr(vectorB.data[i], attr) + + +def test_extract_singleIFOmultiFatoms_from_multiAtoms( + arbitrary_singleAtoms, arbitrary_multiAtoms +): + + single_atoms = extract_singleIFOmultiFatoms_from_multiAtoms(arbitrary_multiAtoms, 0) + compare_FstatAtomVector(single_atoms.data[0], arbitrary_multiAtoms.data[0]) + + with pytest.raises(ValueError): + extract_singleIFOmultiFatoms_from_multiAtoms(arbitrary_multiAtoms, 1) + + +def test_copy_FstatAtomVector(arbitrary_singleAtoms): + + single_atoms = lalpulsar.CreateFstatAtomVector(arbitrary_singleAtoms.length) + copy_FstatAtomVector(single_atoms, arbitrary_singleAtoms) + compare_FstatAtomVector(single_atoms, arbitrary_singleAtoms) + + faulty_atoms = lalpulsar.CreateFstatAtomVector(arbitrary_singleAtoms.length + 1) + with pytest.raises(ValueError): + copy_FstatAtomVector(faulty_atoms, arbitrary_singleAtoms)
segmentation fault from BSGL grid test with recent LALSuite nightlies **Describe the bug** see https://github.com/PyFstat/PyFstat/actions/runs/3360239212/jobs/5569188206#step:7:104 The first failing version seems to be `7.10.1.dev20221025`. Note that the non-BSGL `TestGridSearch::test_semicoherent_grid_search` does **not** segfault. **Expected behavior** no segfault **Environment (please complete the following information):** - see action setup, but can aso reproduce locally **To Reproduce** ``` pip install --upgrade --pre lalsuite==7.10.1.dev20221025 pytest tests/test_grid_based_searches.py::TestGridSearchBSGL::test_semicoherent_grid_search ``` **Additional context** ---
0.0
c502303284fc4fba4dbe34eee1063d0f75d8b7e5
[ "tests/test_utils/test_atoms.py::test_extract_singleIFOmultiFatoms_from_multiAtoms", "tests/test_utils/test_atoms.py::test_copy_FstatAtomVector" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-11-01 17:07:09+00:00
mit
549
google-research__arxiv-latex-cleaner-29
diff --git a/arxiv_latex_cleaner/arxiv_latex_cleaner.py b/arxiv_latex_cleaner/arxiv_latex_cleaner.py index 96dcd0c..bc12ddc 100644 --- a/arxiv_latex_cleaner/arxiv_latex_cleaner.py +++ b/arxiv_latex_cleaner/arxiv_latex_cleaner.py @@ -111,6 +111,36 @@ def _remove_environment(text, environment): text) +def _remove_iffalse_block(text): + """Removes possibly nested r'\iffalse*\fi' blocks from 'text'.""" + p = re.compile(r'\\if(\w+)|\\fi') + level = -1 + positions_to_del = [] + start, end = 0, 0 + for m in p.finditer(text): + if m.group() == r'\iffalse' and level == -1: + level += 1 + start = m.start() + elif m.group().startswith(r'\if') and level >= 0: + level += 1 + elif m.group() == r'\fi' and level >= 0: + if level == 0: + end = m.end() + positions_to_del.append((start, end)) + level -= 1 + else: + pass + + for (start, end) in reversed(positions_to_del): + if end < len(text) and text[end].isspace(): + end_to_del = end + 1 + else: + end_to_del = end + text = text[:start] + text[end_to_del:] + + return text + + def _remove_comments_inline(text): """Removes the comments from the string 'text'.""" if 'auto-ignore' in text: @@ -147,6 +177,7 @@ def _remove_comments(content, parameters): """Erases all LaTeX comments in the content, and writes it.""" content = [_remove_comments_inline(line) for line in content] content = _remove_environment(''.join(content), 'comment') + content = _remove_iffalse_block(content) for command in parameters['commands_to_delete']: content = _remove_command(content, command) return content diff --git a/tex/main.tex b/tex/main.tex index 2e434d5..0a9abac 100644 --- a/tex/main.tex +++ b/tex/main.tex @@ -15,6 +15,16 @@ This is a todo command\mytodo{Do this later} \mytodo{This is a todo command with a nested \textit{command}. Please remember that up to \texttt{2 levels} of \textit{nesting} are supported.} +\newif\ifvar + +\ifvar +\iffalse +\ifvar +Text +\fi +\fi +\fi + \input{figures/figure_included.tex} % \input{figures/figure_not_included.tex} diff --git a/tex_arXiv_true/main.tex b/tex_arXiv_true/main.tex index c3b203f..2df5b95 100644 --- a/tex_arXiv_true/main.tex +++ b/tex_arXiv_true/main.tex @@ -9,6 +9,11 @@ This is a percent \%. This is a todo command +\newif\ifvar + +\ifvar +\fi + \input{figures/figure_included.tex} \includegraphics{ext_tikz/test1.pdf}
google-research/arxiv-latex-cleaner
2045634c0b52bad482c9b3a0b507a7add84450e2
diff --git a/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py b/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py index 0a34693..60258f1 100644 --- a/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py +++ b/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py @@ -88,6 +88,41 @@ class UnitTests(parameterized.TestCase): arxiv_latex_cleaner._remove_environment(text_in, 'comment'), true_output) + @parameterized.named_parameters( + { + 'testcase_name': 'no_iffalse', + 'text_in': 'Foo\n', + 'true_output': 'Foo\n' + }, { + 'testcase_name': 'if_not_removed', + 'text_in': '\\ifvar\n\\ifvar\nFoo\n\\fi\n\\fi\n', + 'true_output': '\\ifvar\n\\ifvar\nFoo\n\\fi\n\\fi\n' + }, { + 'testcase_name': 'if_removed_with_nested_ifvar', + 'text_in': '\\ifvar\n\\iffalse\n\\ifvar\nFoo\n\\fi\n\\fi\n\\fi\n', + 'true_output': '\\ifvar\n\\fi\n' + }, { + 'testcase_name': 'if_removed_with_nested_iffalse', + 'text_in': '\\ifvar\n\\iffalse\n\\iffalse\nFoo\n\\fi\n\\fi\n\\fi\n', + 'true_output': '\\ifvar\n\\fi\n' + }, { + 'testcase_name': 'if_removed_eof', + 'text_in': '\\iffalse\nFoo\n\\fi', + 'true_output': '' + }, { + 'testcase_name': 'if_removed_space', + 'text_in': '\\iffalse\nFoo\n\\fi ', + 'true_output': '' + }, { + 'testcase_name': 'if_removed_backslash', + 'text_in': '\\iffalse\nFoo\n\\fi\\end{document}', + 'true_output': '\\end{document}' + }) + def test_remove_iffalse_block(self, text_in, true_output): + self.assertEqual( + arxiv_latex_cleaner._remove_iffalse_block(text_in), + true_output) + @parameterized.named_parameters( { 'testcase_name': 'all_pass',
Nested \iffalse \fi block comments. I used \iffalse ... \fi to block comment in my latex document, and used this modification of the _remove_environment command: ``` def _remove_iffalse(text): """Removes '\\iffalse *\\fi' from 'text'.""" """This has problems with nested \\iffalse \\fi statements""" return re.sub( r'\\iffalse[\s\S]*?\\fi', '', text) ``` However, this runs incorrectly on: ``` \iffalse A \iffalse B \fi C \fi ``` Which in latex outputs nothing, but with the _remove_iffalse code above outputs: ``` C \fi ``` (I had one such nested comment in my document, because of commenting out a subsection of a section that was later commented out in its entirety.) A similar problem does not exist for \begin{comment} \end{comment}, because ``` \begin{comment} A \begin{comment} B \end{comment} C \end{comment} ``` Does not compile in Latex.
0.0
2045634c0b52bad482c9b3a0b507a7add84450e2
[ "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_not_removed", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_backslash", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_eof", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_space", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_with_nested_iffalse", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_with_nested_ifvar", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_no_iffalse" ]
[ "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_keep_pattern_all_pass", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_keep_pattern_not_all_pass", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_not_removed", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_removed", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_no_command", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_auto_ignore", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_comment", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_comment_inline", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_no_comment", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_percent", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_environment_not_removed", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_environment_removed", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_no_environment", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_pattern_all_pass", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_pattern_not_all_pass", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_no_tikz", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_tikz_match", "arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_tikz_no_match" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-01 11:02:07+00:00
apache-2.0
2,561
repobee__repobee-feedback-26
diff --git a/repobee_feedback/_generate_multi_issues_file.py b/repobee_feedback/_generate_multi_issues_file.py new file mode 100644 index 0000000..4f007cb --- /dev/null +++ b/repobee_feedback/_generate_multi_issues_file.py @@ -0,0 +1,62 @@ +"""A helper command to automatically generate a file called issue.md +wich contains templates of issues for multiple students assignments. + +.. module:: _generate_multi_issues_file + :synopsis: A helper command to automatically generate a file + called issue.md wich contains templates of issues for multiple + students assignments. + +.. moduleauthor:: Marcelo Freitas +""" +import pathlib +import sys +from typing import List + +import repobee_plug as plug +from repobee_plug.cli.categorization import Action + +MULTI_ISSUES_FILENAME = "issue.md" + +GENERATE_MULTI_ISSUES_FILE_ACTION = Action( + name="generate-multi-issues-file", + category=plug.cli.CoreCommand.issues, +) + + +class GenerateMultiIssuesFile(plug.Plugin, plug.cli.Command): + __settings__ = plug.cli.command_settings( + help=( + "auto generate multi-issues file" + " for the `issues feedback` command" + ), + description="Will generate a multi-issues file template " + "where each pair of student assignment passed " + "will become an issue that starts with the line " + "#ISSUE#<STUDENT_REPO_NAME>#<ISSUE_TITLE>, followed by its " + "body. Title and body should be filled appropriately later.", + action=GENERATE_MULTI_ISSUES_FILE_ACTION, + base_parsers=[plug.BaseParser.ASSIGNMENTS, plug.BaseParser.STUDENTS], + ) + + def command(self): + content = _generate_multi_issues_file_content( + self.args.students, self.args.assignments + ) + + pathlib.Path(MULTI_ISSUES_FILENAME).write_text( + content, encoding=sys.getdefaultencoding() + ) + + plug.echo(f"Created multi-issues file '{MULTI_ISSUES_FILENAME}'") + + +def _generate_multi_issues_file_content( + students: List[str], assignments: List[str] +) -> str: + + issue_headers = [ + f"#ISSUE#{repo_name}#<ISSUE-TITLE>\n<ISSUE-BODY>" + for repo_name in plug.generate_repo_names(students, assignments) + ] + + return "\n\n".join(issue_headers) diff --git a/repobee_feedback/feedback.py b/repobee_feedback/feedback.py index f4ceb59..cc6d488 100644 --- a/repobee_feedback/feedback.py +++ b/repobee_feedback/feedback.py @@ -15,6 +15,9 @@ from textwrap import indent from typing import Iterable, Tuple, List, Mapping import repobee_plug as plug +from repobee_feedback._generate_multi_issues_file import ( # noqa: F401 + GenerateMultiIssuesFile, +) PLUGIN_NAME = "feedback"
repobee/repobee-feedback
304e38cfcaaa1dba37dbe7bf52e37dca2387572f
diff --git a/tests/test_generate_multi_issues_file.py b/tests/test_generate_multi_issues_file.py new file mode 100644 index 0000000..29b2c36 --- /dev/null +++ b/tests/test_generate_multi_issues_file.py @@ -0,0 +1,45 @@ +import sys + +import repobee +from repobee_feedback._generate_multi_issues_file import ( + MULTI_ISSUES_FILENAME, + GENERATE_MULTI_ISSUES_FILE_ACTION, + GenerateMultiIssuesFile, +) + + +class TestGenerateMultiIssuesFile: + """Tests generation of a multi-issues file""" + + def test_creates_non_empty_output_file(self, tmp_path): + students = "alice bob".split() + assignments = "task-1 task-2".split() + command = [ + *GENERATE_MULTI_ISSUES_FILE_ACTION.as_name_tuple(), + "--students", + *students, + "--assignments", + *assignments, + ] + + expected_content = ( + "#ISSUE#alice-task-1#<ISSUE-TITLE>\n" + "<ISSUE-BODY>\n\n" + "#ISSUE#bob-task-1#<ISSUE-TITLE>\n" + "<ISSUE-BODY>\n\n" + "#ISSUE#alice-task-2#<ISSUE-TITLE>\n" + "<ISSUE-BODY>\n\n" + "#ISSUE#bob-task-2#<ISSUE-TITLE>\n" + "<ISSUE-BODY>" + ) + + repobee.run( + command, + plugins=[GenerateMultiIssuesFile], + workdir=tmp_path, + ) + + outfile = tmp_path / MULTI_ISSUES_FILENAME + content = outfile.read_text(encoding=sys.getdefaultencoding()) + assert outfile.is_file() + assert content == expected_content
Auto generate multi-issue file I'm getting real tired of adding #ISSUE#name-task-X#Pass/fail to a file 15 times so I considered writing a plugin to do that for me but realized I can just add it to the feedback plugin if that's okay with you @slarse I'm thinking something like: `repobee issues feedback create-mi-file`
0.0
304e38cfcaaa1dba37dbe7bf52e37dca2387572f
[ "tests/test_generate_multi_issues_file.py::TestGenerateMultiIssuesFile::test_creates_non_empty_output_file" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2021-12-21 18:27:15+00:00
mit
5,246
seddonym__import-linter-79
diff --git a/AUTHORS.rst b/AUTHORS.rst index b34e861..b0fa74b 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -9,3 +9,4 @@ Contributors ============ * Anthony Sottile - https://github.com/asottile +* Łukasz Skarżyński - https://github.com/skarzi diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 49ecc2c..3df7df3 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -87,3 +87,5 @@ latest ------ * Upgrade Grimp to 1.2.2. +* Add SetField +* Use a SetField for ignore_imports options diff --git a/src/importlinter/contracts/forbidden.py b/src/importlinter/contracts/forbidden.py index 89a10de..6badb2b 100644 --- a/src/importlinter/contracts/forbidden.py +++ b/src/importlinter/contracts/forbidden.py @@ -14,8 +14,8 @@ class ForbiddenContract(Contract): - source_modules: A list of Modules that should not import the forbidden modules. - forbidden_modules: A list of Modules that should not be imported by the source modules. - - ignore_imports: A list of DirectImports. These imports will be ignored: if the import - would cause a contract to be broken, adding it to the list will cause + - ignore_imports: A set of DirectImports. These imports will be ignored: if the import + would cause a contract to be broken, adding it to the set will cause the contract be kept instead. (Optional.) """ @@ -23,7 +23,7 @@ class ForbiddenContract(Contract): source_modules = fields.ListField(subfield=fields.ModuleField()) forbidden_modules = fields.ListField(subfield=fields.ModuleField()) - ignore_imports = fields.ListField(subfield=fields.DirectImportField(), required=False) + ignore_imports = fields.SetField(subfield=fields.DirectImportField(), required=False) def check(self, graph: ImportGraph) -> ContractCheck: is_kept = True diff --git a/src/importlinter/contracts/independence.py b/src/importlinter/contracts/independence.py index 71a7ff7..14f206e 100644 --- a/src/importlinter/contracts/independence.py +++ b/src/importlinter/contracts/independence.py @@ -16,15 +16,15 @@ class IndependenceContract(Contract): Configuration options: - modules: A list of Modules that should be independent from each other. - - ignore_imports: A list of DirectImports. These imports will be ignored: if the import - would cause a contract to be broken, adding it to the list will cause + - ignore_imports: A set of DirectImports. These imports will be ignored: if the import + would cause a contract to be broken, adding it to the set will cause the contract be kept instead. (Optional.) """ type_name = "independence" modules = fields.ListField(subfield=fields.ModuleField()) - ignore_imports = fields.ListField(subfield=fields.DirectImportField(), required=False) + ignore_imports = fields.SetField(subfield=fields.DirectImportField(), required=False) def check(self, graph: ImportGraph) -> ContractCheck: is_kept = True diff --git a/src/importlinter/contracts/layers.py b/src/importlinter/contracts/layers.py index 6aa43b5..cf15223 100644 --- a/src/importlinter/contracts/layers.py +++ b/src/importlinter/contracts/layers.py @@ -42,8 +42,8 @@ class LayersContract(Contract): - layers: An ordered list of layers. Each layer is the name of a module relative to its parent package. The order is from higher to lower level layers. - containers: A list of the parent Modules of the layers (optional). - - ignore_imports: A list of DirectImports. These imports will be ignored: if the import - would cause a contract to be broken, adding it to the list will cause + - ignore_imports: A set of DirectImports. These imports will be ignored: if the import + would cause a contract to be broken, adding it to the set will cause the contract be kept instead. (Optional.) """ @@ -51,7 +51,7 @@ class LayersContract(Contract): layers = fields.ListField(subfield=LayerField()) containers = fields.ListField(subfield=fields.StringField(), required=False) - ignore_imports = fields.ListField(subfield=fields.DirectImportField(), required=False) + ignore_imports = fields.SetField(subfield=fields.DirectImportField(), required=False) def check(self, graph: ImportGraph) -> ContractCheck: is_kept = True diff --git a/src/importlinter/domain/fields.py b/src/importlinter/domain/fields.py index 7809113..e226ec9 100644 --- a/src/importlinter/domain/fields.py +++ b/src/importlinter/domain/fields.py @@ -1,16 +1,18 @@ import abc import re -from typing import Any, List, Union +from typing import Generic, Iterable, List, Set, TypeVar, Union from importlinter.domain.imports import DirectImport, Module +FieldValue = TypeVar("FieldValue") + class ValidationError(Exception): def __init__(self, message: str) -> None: self.message = message -class Field(abc.ABC): +class Field(Generic[FieldValue], abc.ABC): """ Base class for containers for some data on a Contract. @@ -21,7 +23,7 @@ class Field(abc.ABC): self.required = required @abc.abstractmethod - def parse(self, raw_data: Union[str, List[str]]) -> Any: + def parse(self, raw_data: Union[str, List[str]]) -> FieldValue: """ Given some raw data supplied by a user, return some clean data. @@ -42,16 +44,13 @@ class StringField(Field): return str(raw_data) -class ListField(Field): +class BaseMultipleValueField(Field): """ - A field for multiple values of any type. + An abstract field for multiple values of any type. Arguments: - - subfield: An instance of a single-value Field. Each item in the list will be the return - value of this subfield. - Usage: - - field = ListField(subfield=AnotherField()) + - subfield: An instance of a single-value Field. Each item in the iterable will be + the return value of this subfield. """ @@ -59,7 +58,8 @@ class ListField(Field): super().__init__(*args, **kwargs) self.subfield = subfield - def parse(self, raw_data: Union[str, List]) -> List[Any]: + @abc.abstractmethod + def parse(self, raw_data: Union[str, List]) -> Iterable[FieldValue]: if isinstance(raw_data, tuple): raw_data = list(raw_data) if not isinstance(raw_data, list): @@ -70,6 +70,37 @@ class ListField(Field): return clean_list +class ListField(BaseMultipleValueField): + """ + A field for multiple values of any type. + + Fields values are returned in list sorted by parsing order. + + Usage: + + field = ListField(subfield=AnotherField()) + """ + + def parse(self, raw_data: Union[str, List]) -> List[FieldValue]: + return list(super().parse(raw_data)) + + +class SetField(BaseMultipleValueField): + """ + A field for multiple, unique values of any type. + + Fields values are returned inordered in set. + + Usage: + + field = SetField(subfield=AnotherField()) + + """ + + def parse(self, raw_data: Union[str, List]) -> Set[FieldValue]: + return set(super().parse(raw_data)) + + class ModuleField(Field): """ A field for Modules.
seddonym/import-linter
334b4d1b85bae7f21f7678e5bda17af0e7487af2
diff --git a/tests/unit/contracts/test_forbidden.py b/tests/unit/contracts/test_forbidden.py index 684d8eb..e69dc93 100644 --- a/tests/unit/contracts/test_forbidden.py +++ b/tests/unit/contracts/test_forbidden.py @@ -125,6 +125,19 @@ class TestForbiddenContract: ): contract.check(graph=graph) + def test_ignore_imports_tolerates_duplicates(self): + graph = self._build_graph() + contract = self._build_contract( + forbidden_modules=("mypackage.blue", "mypackage.yellow"), + ignore_imports=( + "mypackage.three -> mypackage.green", + "mypackage.utils -> mypackage.purple", + "mypackage.three -> mypackage.green", + ), + include_external_packages=False, + ) + assert contract.check(graph=graph) + def _build_graph(self): graph = ImportGraph() for module in ( @@ -171,7 +184,9 @@ class TestForbiddenContract: ) return graph - def _build_contract(self, forbidden_modules, include_external_packages=False): + def _build_contract( + self, forbidden_modules, ignore_imports=None, include_external_packages=False + ): session_options = {"root_packages": ["mypackage"]} if include_external_packages: session_options["include_external_packages"] = "True" @@ -182,6 +197,7 @@ class TestForbiddenContract: contract_options={ "source_modules": ("mypackage.one", "mypackage.two", "mypackage.three"), "forbidden_modules": forbidden_modules, + "ignore_imports": ignore_imports or [], }, ) diff --git a/tests/unit/contracts/test_independence.py b/tests/unit/contracts/test_independence.py index fefc36d..db3ba26 100644 --- a/tests/unit/contracts/test_independence.py +++ b/tests/unit/contracts/test_independence.py @@ -392,3 +392,30 @@ def test_missing_module(): with pytest.raises(ValueError, match=("Module 'mypackage.bar' does not exist.")): contract.check(graph=graph) + + +def test_ignore_imports_tolerates_duplicates(): + graph = ImportGraph() + graph.add_module("mypackage") + graph.add_import( + importer="mypackage.a", imported="mypackage.b", line_number=1, line_contents="-" + ) + graph.add_import( + importer="mypackage.a", imported="mypackage.c", line_number=2, line_contents="-" + ) + contract = IndependenceContract( + name="Independence contract", + session_options={"root_packages": ["mypackage"]}, + contract_options={ + "modules": ("mypackage.a", "mypackage.b"), + "ignore_imports": [ + "mypackage.a -> mypackage.b", + "mypackage.a -> mypackage.c", + "mypackage.a -> mypackage.b", + ], + }, + ) + + contract_check = contract.check(graph=graph) + + assert contract_check.kept diff --git a/tests/unit/contracts/test_layers.py b/tests/unit/contracts/test_layers.py index 36b1086..82231c4 100644 --- a/tests/unit/contracts/test_layers.py +++ b/tests/unit/contracts/test_layers.py @@ -765,6 +765,20 @@ class TestIgnoreImports: with pytest.raises(MissingImport): contract.check(graph=graph) + def test_ignore_imports_tolerates_duplicates(self): + contract = self._build_contract( + ignore_imports=[ + "mypackage.low.black -> mypackage.medium.orange", + "mypackage.utils.foo -> mypackage.utils.bar", + "mypackage.low.black -> mypackage.medium.orange", + ] + ) + graph = self._build_graph() + + contract_check = contract.check(graph=graph) + + assert contract_check.kept + def _build_graph(self): graph = ImportGraph() for module in ( diff --git a/tests/unit/domain/test_fields.py b/tests/unit/domain/test_fields.py index 851404a..76883f0 100644 --- a/tests/unit/domain/test_fields.py +++ b/tests/unit/domain/test_fields.py @@ -7,6 +7,7 @@ from importlinter.domain.fields import ( Field, ListField, ModuleField, + SetField, StringField, ValidationError, ) @@ -83,9 +84,23 @@ class TestDirectImportField(BaseFieldTest): "raw_data, expected_value", ( (["mypackage.foo", "mypackage.bar"], [Module("mypackage.foo"), Module("mypackage.bar")]), + (["mypackage.foo", "mypackage.foo"], [Module("mypackage.foo"), Module("mypackage.foo")]), ("singlevalue", [Module("singlevalue")]), ), ) class TestListField(BaseFieldTest): field_class = ListField field_kwargs = dict(subfield=ModuleField()) + + [email protected]( + "raw_data, expected_value", + ( + (["mypackage.foo", "mypackage.bar"], {Module("mypackage.foo"), Module("mypackage.bar")}), + (["mypackage.foo", "mypackage.foo"], {Module("mypackage.foo")}), + ("singlevalue", {Module("singlevalue")}), + ), +) +class TestSetField(BaseFieldTest): + field_class = SetField + field_kwargs = dict(subfield=ModuleField())
Duplicate ignored_imports lead to confusing error If you include an ignored import twice in a contract, you get the following error (as it tries to remove it the second time): ``` The edge mypackage.foo-mypackage.bar not in graph. ```
0.0
334b4d1b85bae7f21f7678e5bda17af0e7487af2
[ "tests/unit/contracts/test_forbidden.py::TestForbiddenContract::test_is_kept_when_no_forbidden_modules_imported", "tests/unit/contracts/test_forbidden.py::TestForbiddenContract::test_is_broken_when_forbidden_modules_imported", "tests/unit/contracts/test_forbidden.py::TestForbiddenContract::test_is_broken_when_forbidden_external_modules_imported", "tests/unit/contracts/test_forbidden.py::TestForbiddenContract::test_is_invalid_when_forbidden_externals_but_graph_does_not_include_externals", "tests/unit/contracts/test_forbidden.py::TestForbiddenContract::test_ignore_imports_tolerates_duplicates", "tests/unit/contracts/test_forbidden.py::test_render_broken_contract", "tests/unit/contracts/test_independence.py::TestIndependenceContract::test_when_modules_are_independent", "tests/unit/contracts/test_independence.py::TestIndependenceContract::test_when_root_imports_root_directly", "tests/unit/contracts/test_independence.py::TestIndependenceContract::test_when_root_imports_root_indirectly", "tests/unit/contracts/test_independence.py::TestIndependenceContract::test_chains_via_other_independent_modules", "tests/unit/contracts/test_independence.py::TestIndependenceContract::test_when_child_imports_child", "tests/unit/contracts/test_independence.py::TestIndependenceContract::test_when_grandchild_imports_root", "tests/unit/contracts/test_independence.py::test_ignore_imports[ignore_imports0-False]", "tests/unit/contracts/test_independence.py::test_ignore_imports[ignore_imports1-True]", "tests/unit/contracts/test_independence.py::test_ignore_imports[ignore_imports2-True]", "tests/unit/contracts/test_independence.py::test_render_broken_contract", "tests/unit/contracts/test_independence.py::test_missing_module", "tests/unit/contracts/test_independence.py::test_ignore_imports_tolerates_duplicates", "tests/unit/contracts/test_layers.py::TestLayerContractSingleContainers::test_no_illegal_imports_means_contract_is_kept", "tests/unit/contracts/test_layers.py::TestLayerContractSingleContainers::test_illegal_child_imports_means_contract_is_broken", "tests/unit/contracts/test_layers.py::TestLayerContractSingleContainers::test_illegal_grandchild_to_child_means_contract_is_broken", "tests/unit/contracts/test_layers.py::TestLayerMultipleContainers::test_no_illegal_imports_means_contract_is_kept", "tests/unit/contracts/test_layers.py::TestLayerMultipleContainers::test_imports_from_low_to_high_but_in_different_container_doesnt_break_contract", "tests/unit/contracts/test_layers.py::TestLayerMultipleContainers::test_illegal_grandchild_imports_means_contract_is_broken", "tests/unit/contracts/test_layers.py::TestLayerContractPopulatesMetadata::test_layer_contract_populates_metadata", "tests/unit/contracts/test_layers.py::TestLayerContractPopulatesMetadata::test_layer_contract_populates_extra_firsts_one_indirect", "tests/unit/contracts/test_layers.py::TestLayerContractPopulatesMetadata::test_layer_contract_populates_extra_firsts_two_indirects", "tests/unit/contracts/test_layers.py::TestLayerContractPopulatesMetadata::test_layer_contract_populates_extra_lasts_one_indirect", "tests/unit/contracts/test_layers.py::TestLayerContractPopulatesMetadata::test_layer_contract_populates_extra_lasts_two_indirects", "tests/unit/contracts/test_layers.py::TestLayerContractPopulatesMetadata::test_layer_contract_populates_firsts_and_lasts_three_indirects", "tests/unit/contracts/test_layers.py::TestIgnoreImports::test_one_ignored_from_each_chain_means_contract_is_kept", "tests/unit/contracts/test_layers.py::TestIgnoreImports::test_ignore_only_one_chain_should_fail_because_of_the_other", "tests/unit/contracts/test_layers.py::TestIgnoreImports::test_multiple_ignore_from_same_chain_should_not_error", "tests/unit/contracts/test_layers.py::TestIgnoreImports::test_ignore_from_nonexistent_importer_raises_missing_import", "tests/unit/contracts/test_layers.py::TestIgnoreImports::test_ignore_from_nonexistent_imported_raises_missing_import", "tests/unit/contracts/test_layers.py::TestIgnoreImports::test_ignore_imports_tolerates_duplicates", "tests/unit/contracts/test_layers.py::test_optional_layers[True-False]", "tests/unit/contracts/test_layers.py::test_missing_containerless_layers_raise_value_error", "tests/unit/contracts/test_layers.py::test_render_broken_contract", "tests/unit/contracts/test_layers.py::test_invalid_container[notingraph]", "tests/unit/contracts/test_layers.py::test_invalid_container[notingraph.foo]", "tests/unit/contracts/test_layers.py::test_invalid_container[notinpackage]", "tests/unit/contracts/test_layers.py::test_invalid_container[notinpackage.foo]", "tests/unit/contracts/test_layers.py::test_invalid_container[notinpackage.foo.one]", "tests/unit/contracts/test_layers.py::test_invalid_container[mypackagebeginscorrectly]", "tests/unit/contracts/test_layers.py::test_invalid_container_multiple_packages", "tests/unit/contracts/test_layers.py::TestLayerContractNoContainer::test_no_illegal_imports_means_contract_is_kept", "tests/unit/contracts/test_layers.py::TestLayerContractNoContainer::test_illegal_imports_means_contract_is_broken", "tests/unit/contracts/test_layers.py::TestLayerContractNoContainer::test_no_illegal_imports_across_multiple_root_packages_means_contract_is_kept", "tests/unit/contracts/test_layers.py::TestLayerContractNoContainer::test_illegal_imports_across_multiple_root_packages_means_contract_is_broken", "tests/unit/contracts/test_layers.py::TestGetIndirectCollapsedChains::test_no_chains", "tests/unit/contracts/test_layers.py::TestGetIndirectCollapsedChains::test_direct_imports_raises_value_error", "tests/unit/contracts/test_layers.py::TestGetIndirectCollapsedChains::test_chain_length_2_is_included", "tests/unit/contracts/test_layers.py::TestGetIndirectCollapsedChains::test_chain_length_3_is_included", "tests/unit/contracts/test_layers.py::TestGetIndirectCollapsedChains::test_multiple_chains_of_length_2_same_segment", "tests/unit/contracts/test_layers.py::TestGetIndirectCollapsedChains::test_multiple_chains_of_length_3_same_segment", "tests/unit/contracts/test_layers.py::TestPopDirectImports::test_direct_import_between_descendants", "tests/unit/contracts/test_layers.py::TestPopDirectImports::test_direct_import_between_roots", "tests/unit/contracts/test_layers.py::TestPopDirectImports::test_direct_import_root_to_descendant", "tests/unit/contracts/test_layers.py::TestPopDirectImports::test_direct_import_descendant_to_root", "tests/unit/domain/test_fields.py::TestStringField::test_field[Hello,", "tests/unit/domain/test_fields.py::TestStringField::test_field[raw_data1-expected_value1]", "tests/unit/domain/test_fields.py::TestModuleField::test_field[mypackage.foo.bar-expected_value0]", "tests/unit/domain/test_fields.py::TestModuleField::test_field[raw_data1-expected_value1]", "tests/unit/domain/test_fields.py::TestDirectImportField::test_field[mypackage.foo", "tests/unit/domain/test_fields.py::TestDirectImportField::test_field[raw_data1-expected_value1]", "tests/unit/domain/test_fields.py::TestListField::test_field[raw_data0-expected_value0]", "tests/unit/domain/test_fields.py::TestListField::test_field[raw_data1-expected_value1]", "tests/unit/domain/test_fields.py::TestListField::test_field[singlevalue-expected_value2]", "tests/unit/domain/test_fields.py::TestSetField::test_field[raw_data0-expected_value0]", "tests/unit/domain/test_fields.py::TestSetField::test_field[raw_data1-expected_value1]", "tests/unit/domain/test_fields.py::TestSetField::test_field[singlevalue-expected_value2]" ]
[]
{ "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 }
2020-07-26 10:23:27+00:00
bsd-2-clause
5,460
florimondmanca__fountain-lang-7
diff --git a/src/fountain/_ast/visitor.py b/src/fountain/_ast/visitor.py index 12308b0..7859e02 100644 --- a/src/fountain/_ast/visitor.py +++ b/src/fountain/_ast/visitor.py @@ -1,4 +1,4 @@ -from typing import Generic, TypeVar +from typing import Any, Generic, TypeVar from .nodes import Expr, Stmt @@ -12,11 +12,11 @@ class NodeVisitor(Generic[R]): ) return method(node) - def execute(self, node: Stmt) -> None: + def execute(self, node: Stmt) -> Any: method = getattr( self, f"execute_{node.__class__.__name__}", self.execute_default ) - method(node) + return method(node) def evaluate_default(self, expr: Expr) -> R: raise NotImplementedError(f"Unexpected node: {expr}") # pragma: no cover diff --git a/src/fountain/_cli.py b/src/fountain/_cli.py index 2f258fc..45778de 100644 --- a/src/fountain/_cli.py +++ b/src/fountain/_cli.py @@ -1,10 +1,11 @@ import argparse import pathlib import sys +from typing import Any from ._ast import parse, tokenize from ._exceptions import EvalError, ParseError, TokenizeError -from ._interpreter import Interpreter +from ._interpreter import Interpreter, stringify def main() -> None: @@ -32,28 +33,27 @@ class CLI: else: return self._run_prompt() + def evaluate(self, source: str) -> Any: + tokens = tokenize(source) + statements = parse(tokens) + return self._interpreter.interpret(statements) + def run(self, source: str) -> int: try: - tokens = tokenize(source) + self.evaluate(source) except TokenizeError as exc: self._report(exc.message, lineno=exc.lineno) return 65 - - try: - statements = parse(tokens) except ParseError as exc: where = "at end" if exc.at_eof else f"at {exc.token.lexeme!r}" self._report(exc.message, lineno=exc.token.lineno, where=where) return 65 - - try: - self._interpreter.interpret(statements) except EvalError as exc: where = f"at {exc.token.lexeme!r}" self._report(exc.message, lineno=exc.token.lineno, where=where) return 70 - - return 0 + else: + return 0 def _run_file(self, path: str) -> int: try: @@ -78,7 +78,9 @@ class CLI: if not line: break - _ = self.run(line) + value = self.evaluate(line) + if value is not None: + print(stringify(value)) return 0 diff --git a/src/fountain/_interpreter.py b/src/fountain/_interpreter.py index 566e332..112f810 100644 --- a/src/fountain/_interpreter.py +++ b/src/fountain/_interpreter.py @@ -40,21 +40,23 @@ class Interpreter(NodeVisitor[Any]): scope.assign(name, value) self._scope = scope - def interpret(self, statements: list[Stmt]) -> None: + def interpret(self, statements: list[Stmt]) -> Any: + value: Any = None try: for stmt in statements: - self.execute(stmt) + value = self.execute(stmt) except EvalError: raise + else: + return value def execute_Assign(self, stmt: Assign) -> None: name = stmt.target.lexeme value = self.evaluate(stmt.value) self._scope.assign(name, value) - def execute_Expression(self, stmt: Expression) -> None: - value = self.evaluate(stmt.expression) - print(stringify(value)) + def execute_Expression(self, stmt: Expression) -> Any: + return self.evaluate(stmt.expression) def execute_Print(self, stmt: Print) -> None: value = self.evaluate(stmt.expression)
florimondmanca/fountain-lang
4ca44d301117e2bd738aa98411d6eab7bb381b26
diff --git a/tests/test_cli.py b/tests/test_cli.py index b8a3bef..434a4fa 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -117,9 +117,7 @@ def test_cli_repl(monkeypatch: Any, capsys: Any) -> None: ), ( "fn f() print 'OK' end; f()", - # TODO: drop 'nil' after: - # https://github.com/florimondmanca/fountain-lang/issues/1 - "OK\nnil\n", + "OK\n", ), ( """
Handling of expression statements results in unwanted prints Currently, expression statements such as: ```lua "hello, world" some_func(a, b, c) ``` Result in printing the result to the console. In the REPL or via `fountain -c` this is what we want, but not when running from a file. We should move the "print the expression" behavour out of the `Interpreter` and to the `CLI`. Most likely: * Modify `Interpreter.execute()` to fit `() -> Any` (may return a value). * Modify `Interpreter.execute_Expression()` so that it _returns_ the value of the expression. * Modify `interpret` to be `(list[Stmt]) -> Any` so that it keeps track of the statement return values (in practice only `Expression` statements may return a value), and return the last one. * Add a new `CLI.evaluate(source: str) -> Any` method that returns the result from `interpret()`. * Update `CLI.run`, `CLI._run_file` and `CLI._run_prompt` so that they do the right thing, i.e. only show `stringify(value)` in the prompt.
0.0
4ca44d301117e2bd738aa98411d6eab7bb381b26
[ "tests/test_cli.py::test_cli_eval[fn" ]
[ "tests/test_cli.py::test_cli_repl", "tests/test_cli.py::test_cli_eval[print", "tests/test_cli.py::test_cli_eval[x", "tests/test_cli.py::test_cli_eval[\\n", "tests/test_cli.py::test_cli_eval[do", "tests/test_cli.py::test_cli_eval[assert", "tests/test_cli.py::test_cli_eval[--", "tests/test_cli.py::test_cli_eval[-]", "tests/test_cli.py::test_cli_eval_error[(3", "tests/test_cli.py::test_cli_eval_error['hello-[line", "tests/test_cli.py::test_cli_eval_error['hello\"-[line", "tests/test_cli.py::test_cli_eval_error['hello\\n-[line", "tests/test_cli.py::test_cli_eval_error[3", "tests/test_cli.py::test_cli_eval_error[\\n", "tests/test_cli.py::test_cli_eval_error[do", "tests/test_cli.py::test_cli_eval_error[break-[line", "tests/test_cli.py::test_cli_eval_error[continue-[line", "tests/test_cli.py::test_cli_eval_error[fn", "tests/test_cli.py::test_cli_eval_error[return", "tests/test_cli.py::test_cli_eval_error[1/0-[line", "tests/test_cli.py::test_cli_eval_error[1", "tests/test_cli.py::test_cli_eval_error['hello'", "tests/test_cli.py::test_cli_eval_error[print", "tests/test_cli.py::test_cli_eval_error[assert", "tests/test_cli.py::test_cli_eval_error[1()-[line" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-10-02 13:59:15+00:00
apache-2.0
2,356
ultrabug__py3status-1221
diff --git a/py3status/formatter.py b/py3status/formatter.py index e265819e..db2875de 100644 --- a/py3status/formatter.py +++ b/py3status/formatter.py @@ -268,7 +268,9 @@ class Placeholder: output = u'{%s%s}' % (self.key, self.format) value = value_ = output.format(**{self.key: value}) - if block.commands.not_zero: + if block.parent is None: + valid = True + elif block.commands.not_zero: valid = value_ not in ['', 'None', None, False, '0', '0.0', 0, 0.0] else: # '', None, and False are ignored
ultrabug/py3status
dcd3dda64b82e536cfd0233691d374a22e96aeac
diff --git a/tests/test_formatter.py b/tests/test_formatter.py index 0d1bf9b5..76febab4 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -296,10 +296,18 @@ def test_26(): def test_27(): - run_formatter({'format': '{None}', 'expected': '', }) + run_formatter({'format': '{None}', 'expected': 'None', }) def test_27a(): + run_formatter({'format': '{None} {no}', 'expected': 'None False', }) + + +def test_27b(): + run_formatter({'format': '[Hello {None}] {no}', 'expected': ' False', }) + + +def test_27c(): run_formatter({'format': '[Hi, my name is {None_str}]', 'expected': '', }) @@ -312,7 +320,7 @@ def test_29(): def test_30(): - run_formatter({'format': '{no}', 'expected': '', }) + run_formatter({'format': '{no}', 'expected': 'False', }) def test_31(): @@ -1134,7 +1142,7 @@ def test_module_true_value(): def test_module_false_value(): - run_formatter({'format': '{module_false}', 'expected': ''}) + run_formatter({'format': '{module_false}', 'expected': 'False'}) def test_zero_format_1():
Formatting returns empty when closing with a False or None placeholder Formatting returns empty when closing with a `False` or `None` placeholder. ```diff diff --git a/py3status/modules/static_string.py b/py3status/modules/static_string.py index dbcec8c6..593b3740 100644 --- a/py3status/modules/static_string.py +++ b/py3status/modules/static_string.py @@ -18,10 +18,17 @@ class Py3status: # available configuration parameters format = 'Hello, world!' + # format = 'A, B, C // {true}' # IS OK | A, B, C // True + # format = 'A, B, C // {false}' # IS NOT OK | + # format = 'A, B, C // {none}' # IS NOT OK | + # format = 'A, B, C // {false} ' # IS OK | A, B, C // False + # format = 'A, B, C // {none} ' # IS OK | A, B, C // None + def static_string(self): + new_dict = {'true': True, 'false': False, 'none': None} return { 'cached_until': self.py3.CACHE_FOREVER, - 'full_text': self.py3.safe_format(self.format), + 'full_text': self.py3.safe_format(self.format, new_dict), } ```
0.0
dcd3dda64b82e536cfd0233691d374a22e96aeac
[ "tests/test_formatter.py::test_27", "tests/test_formatter.py::test_27a", "tests/test_formatter.py::test_27b", "tests/test_formatter.py::test_30", "tests/test_formatter.py::test_module_false_value" ]
[ "tests/test_formatter.py::test_1", "tests/test_formatter.py::test_2", "tests/test_formatter.py::test_3", "tests/test_formatter.py::test_4", "tests/test_formatter.py::test_5", "tests/test_formatter.py::test_6", "tests/test_formatter.py::test_7", "tests/test_formatter.py::test_8", "tests/test_formatter.py::test_9", "tests/test_formatter.py::test_10", "tests/test_formatter.py::test_11", "tests/test_formatter.py::test_12", "tests/test_formatter.py::test_13", "tests/test_formatter.py::test_14", "tests/test_formatter.py::test_15", "tests/test_formatter.py::test_16", "tests/test_formatter.py::test_16a", "tests/test_formatter.py::test_16b", "tests/test_formatter.py::test_17", "tests/test_formatter.py::test_18", "tests/test_formatter.py::test_19", "tests/test_formatter.py::test_20", "tests/test_formatter.py::test_21", "tests/test_formatter.py::test_22", "tests/test_formatter.py::test_23", "tests/test_formatter.py::test_24", "tests/test_formatter.py::test_24a", "tests/test_formatter.py::test_24b", "tests/test_formatter.py::test_25", "tests/test_formatter.py::test_26", "tests/test_formatter.py::test_27c", "tests/test_formatter.py::test_28", "tests/test_formatter.py::test_29", "tests/test_formatter.py::test_31", "tests/test_formatter.py::test_32", "tests/test_formatter.py::test_33", "tests/test_formatter.py::test_34", "tests/test_formatter.py::test_35", "tests/test_formatter.py::test_36", "tests/test_formatter.py::test_37", "tests/test_formatter.py::test_38", "tests/test_formatter.py::test_39", "tests/test_formatter.py::test_40", "tests/test_formatter.py::test_41", "tests/test_formatter.py::test_42", "tests/test_formatter.py::test_43", "tests/test_formatter.py::test_44", "tests/test_formatter.py::test_45", "tests/test_formatter.py::test_46", "tests/test_formatter.py::test_47", "tests/test_formatter.py::test_48", "tests/test_formatter.py::test_49", "tests/test_formatter.py::test_50", "tests/test_formatter.py::test_51", "tests/test_formatter.py::test_52", "tests/test_formatter.py::test_53", "tests/test_formatter.py::test_54", "tests/test_formatter.py::test_55", "tests/test_formatter.py::test_56", "tests/test_formatter.py::test_57", "tests/test_formatter.py::test_58", "tests/test_formatter.py::test_58a", "tests/test_formatter.py::test_59", "tests/test_formatter.py::test_59a", "tests/test_formatter.py::test_60", "tests/test_formatter.py::test_61", "tests/test_formatter.py::test_62", "tests/test_formatter.py::test_63", "tests/test_formatter.py::test_64", "tests/test_formatter.py::test_65", "tests/test_formatter.py::test_66", "tests/test_formatter.py::test_67", "tests/test_formatter.py::test_68", "tests/test_formatter.py::test_69", "tests/test_formatter.py::test_70", "tests/test_formatter.py::test_70a", "tests/test_formatter.py::test_71", "tests/test_formatter.py::test_72", "tests/test_formatter.py::test_73", "tests/test_formatter.py::test_74", "tests/test_formatter.py::test_75", "tests/test_formatter.py::test_76", "tests/test_formatter.py::test_77", "tests/test_formatter.py::test_78", "tests/test_formatter.py::test_else_true", "tests/test_formatter.py::test_else_false", "tests/test_formatter.py::test_color_name_1", "tests/test_formatter.py::test_color_name_2", "tests/test_formatter.py::test_color_name_3", "tests/test_formatter.py::test_color_name_4", "tests/test_formatter.py::test_color_name_4a", "tests/test_formatter.py::test_color_name_5", "tests/test_formatter.py::test_color_name_5a", "tests/test_formatter.py::test_color_name_6", "tests/test_formatter.py::test_color_name_7", "tests/test_formatter.py::test_color_name_7a", "tests/test_formatter.py::test_color_1", "tests/test_formatter.py::test_color_1a", "tests/test_formatter.py::test_color_2", "tests/test_formatter.py::test_color_3", "tests/test_formatter.py::test_color_4", "tests/test_formatter.py::test_color_5", "tests/test_formatter.py::test_color_6", "tests/test_formatter.py::test_color_7", "tests/test_formatter.py::test_color_7a", "tests/test_formatter.py::test_color_8", "tests/test_formatter.py::test_color_8a", "tests/test_formatter.py::test_color_9", "tests/test_formatter.py::test_color_9a", "tests/test_formatter.py::test_composite_1", "tests/test_formatter.py::test_composite_2", "tests/test_formatter.py::test_composite_3", "tests/test_formatter.py::test_composite_4", "tests/test_formatter.py::test_composite_5", "tests/test_formatter.py::test_composite_6", "tests/test_formatter.py::test_attr_getter", "tests/test_formatter.py::test_min_length_1", "tests/test_formatter.py::test_min_length_2", "tests/test_formatter.py::test_min_length_3", "tests/test_formatter.py::test_min_length_4", "tests/test_formatter.py::test_min_length_5", "tests/test_formatter.py::test_min_length_6", "tests/test_formatter.py::test_numeric_strings_1", "tests/test_formatter.py::test_numeric_strings_2", "tests/test_formatter.py::test_numeric_strings_3", "tests/test_formatter.py::test_numeric_strings_4", "tests/test_formatter.py::test_numeric_strings_5", "tests/test_formatter.py::test_numeric_strings_6", "tests/test_formatter.py::test_not_zero_1", "tests/test_formatter.py::test_not_zero_2", "tests/test_formatter.py::test_not_zero_3", "tests/test_formatter.py::test_not_zero_4", "tests/test_formatter.py::test_not_zero_5", "tests/test_formatter.py::test_not_zero_6", "tests/test_formatter.py::test_not_zero_7", "tests/test_formatter.py::test_not_zero_8", "tests/test_formatter.py::test_not_zero_9", "tests/test_formatter.py::test_not_zero_10", "tests/test_formatter.py::test_not_zero_11", "tests/test_formatter.py::test_bad_composite_color", "tests/test_formatter.py::test_soft_1", "tests/test_formatter.py::test_soft_2", "tests/test_formatter.py::test_soft_3", "tests/test_formatter.py::test_soft_4", "tests/test_formatter.py::test_soft_5", "tests/test_formatter.py::test_soft_6", "tests/test_formatter.py::test_soft_7", "tests/test_formatter.py::test_module_true", "tests/test_formatter.py::test_module_false", "tests/test_formatter.py::test_module_true_value", "tests/test_formatter.py::test_zero_format_1", "tests/test_formatter.py::test_zero_format_2", "tests/test_formatter.py::test_zero_format_3", "tests/test_formatter.py::test_zero_format_4", "tests/test_formatter.py::test_inherit_not_zero_1", "tests/test_formatter.py::test_inherit_not_zero_2", "tests/test_formatter.py::test_inherit_not_zero_3", "tests/test_formatter.py::test_inherit_show_1", "tests/test_formatter.py::test_inherit_color_1", "tests/test_formatter.py::test_inherit_color_2", "tests/test_formatter.py::test_conditions_1", "tests/test_formatter.py::test_conditions_2", "tests/test_formatter.py::test_conditions_3", "tests/test_formatter.py::test_conditions_4", "tests/test_formatter.py::test_conditions_5", "tests/test_formatter.py::test_conditions_6", "tests/test_formatter.py::test_conditions_7", "tests/test_formatter.py::test_conditions_8", "tests/test_formatter.py::test_conditions_9", "tests/test_formatter.py::test_conditions_10", "tests/test_formatter.py::test_conditions_11", "tests/test_formatter.py::test_conditions_12", "tests/test_formatter.py::test_conditions_13", "tests/test_formatter.py::test_conditions_14", "tests/test_formatter.py::test_conditions_15", "tests/test_formatter.py::test_conditions_16", "tests/test_formatter.py::test_conditions_17", "tests/test_formatter.py::test_conditions_18", "tests/test_formatter.py::test_conditions_19", "tests/test_formatter.py::test_conditions_20", "tests/test_formatter.py::test_conditions_21", "tests/test_formatter.py::test_conditions_22", "tests/test_formatter.py::test_conditions_23", "tests/test_formatter.py::test_trailing_zeroes_1", "tests/test_formatter.py::test_trailing_zeroes_2", "tests/test_formatter.py::test_ceiling_numbers_1", "tests/test_formatter.py::test_ceiling_numbers_2" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-01-10 08:09:08+00:00
bsd-3-clause
6,156
tillahoffmann__localscope-10
diff --git a/README.rst b/README.rst index fee5d6c..b976dbc 100644 --- a/README.rst +++ b/README.rst @@ -20,7 +20,7 @@ Interactive python sessions, such as `Jupyter notebooks <https://jupyter.org/>`_ ... print(a) Traceback (most recent call last): ... - ValueError: `a` is not a permitted global + localscope.LocalscopeException: `a` is not a permitted global (file "...", line 1, in print_a) Motivation and detailed example ------------------------------- @@ -65,7 +65,7 @@ This example may seem contrived. But unintended information leakage from the glo ... return sum(((x - y) / sigma) ** 2 for x, y in zip(xs, ys)) Traceback (most recent call last): ... - ValueError: `sigma` is not a permitted global + localscope.LocalscopeException: `sigma` is not a permitted global (file "...", line 3, in <genexpr>) Interface --------- diff --git a/localscope/__init__.py b/localscope/__init__.py index ff876da..bec61c5 100644 --- a/localscope/__init__.py +++ b/localscope/__init__.py @@ -16,7 +16,6 @@ def localscope( predicate: Optional[Callable] = None, allowed: Optional[Set[str]] = None, allow_closure: bool = False, - _globals: Optional[Dict[str, Any]] = None, ): """ Restrict the scope of a callable to local variables to avoid unintentional @@ -27,8 +26,6 @@ def localscope( predicate : Predicate to determine whether a global variable is allowed in the scope. Defaults to allow any module. allowed: Names of globals that are allowed to enter the scope. - _globals : Globals associated with the root callable which are passed to - dependent code blocks for analysis. Attributes: mfc: Decorator allowing *m*\\ odules, *f*\\ unctions, and *c*\\ lasses to enter @@ -44,7 +41,8 @@ def localscope( ... print(a) Traceback (most recent call last): ... - ValueError: `a` is not a permitted global + localscope.LocalscopeException: `a` is not a permitted global (file "...", + line 1, in print_a) The scope of a function can be extended by providing a list of allowed exceptions. @@ -85,53 +83,111 @@ def localscope( blocks) at the time of declaration because static analysis has a minimal impact on performance and it is easier to implement. """ - # Set defaults - predicate = predicate or inspect.ismodule + # Set defaults and construct partial if the callable has not yet been provided for + # parameterized decorators, e.g., @localscope(allowed={"foo", "bar"}). This is a + # thin wrapper around the actual implementation `_localscope`. The wrapper + # reconstructs an informative traceback. allowed = set(allowed) if allowed else set() - if func is None: + predicate = predicate or inspect.ismodule + if not func: return ft.partial( localscope, allow_closure=allow_closure, - predicate=predicate, allowed=allowed, + predicate=predicate, ) + return _localscope( + func, + allow_closure=allow_closure, + allowed=allowed, + predicate=predicate, + _globals={}, + ) + + +class LocalscopeException(RuntimeError): + """ + Raised when a callable tries to access a non-local variable. + """ + + def __init__( + self, + message: str, + code: types.CodeType, + instruction: Optional[dis.Instruction] = None, + ) -> None: + if instruction and instruction.starts_line: + lineno = instruction.starts_line + else: + lineno = code.co_firstlineno + details = f'file "{code.co_filename}", line {lineno}, in {code.co_name}' + super().__init__(f"{message} ({details})") + + +def _localscope( + func: Union[types.FunctionType, types.CodeType], + *, + predicate: Callable, + allowed: Set[str], + allow_closure: bool, + _globals: Dict[str, Any], +): + """ + Args: + ...: Same as for the wrapper :func:`localscope`. + _globals : Globals associated with the root callable which are passed to + dependent code blocks for analysis. + """ + + # Extract global variables from a function + # (https://docs.python.org/3/library/types.html#types.FunctionType) or keep the + # explicitly provided globals for code objects + # (https://docs.python.org/3/library/types.html#types.CodeType). if isinstance(func, types.FunctionType): code = func.__code__ _globals = {**func.__globals__, **inspect.getclosurevars(func).nonlocals} else: code = func - _globals = _globals or {} - # Add function arguments to the list of allowed exceptions + # Add function arguments to the list of allowed exceptions. allowed.update(code.co_varnames[: code.co_argcount]) - opnames = {"LOAD_GLOBAL"} + # Construct set of forbidden operations. The first accesses global variables. The + # second accesses variables from the outer scope. + forbidden_opnames = {"LOAD_GLOBAL"} if not allow_closure: - opnames.add("LOAD_DEREF") + forbidden_opnames.add("LOAD_DEREF") LOGGER.info("analysing instructions for %s...", func) for instruction in dis.get_instructions(code): LOGGER.info(instruction) name = instruction.argval - if instruction.opname in opnames: - # Explicitly allowed + if instruction.opname in forbidden_opnames: + # Variable explicitly allowed by name or in `builtins`. if name in allowed or hasattr(builtins, name): continue - # Complain if the variable is not available + # Complain if the variable is not available. if name not in _globals: - raise NameError(f"`{name}` is not in globals") - # Get the value of the variable and check it against the predicate + raise LocalscopeException( + f"`{name}` is not in globals", code, instruction + ) + # Check if variable is allowed by value. value = _globals[name] if not predicate(value): - raise ValueError(f"`{name}` is not a permitted global") + raise LocalscopeException( + f"`{name}` is not a permitted global", code, instruction + ) elif instruction.opname == "STORE_DEREF": + # Store a new allowed variable which has been created in the scope of the + # function. allowed.add(name) + # Deal with code objects recursively after adding the current arguments to the # allowed exceptions for const in code.co_consts: if isinstance(const, types.CodeType): - localscope( + _localscope( const, _globals=_globals, allow_closure=True,
tillahoffmann/localscope
fe4334355ea6e7bd1af0a15509b1f7a65f9da3b0
diff --git a/tests/test_localscope.py b/tests/test_localscope.py index 41bc69c..232a966 100644 --- a/tests/test_localscope.py +++ b/tests/test_localscope.py @@ -1,4 +1,4 @@ -from localscope import localscope +from localscope import localscope, LocalscopeException import uuid import pytest @@ -16,15 +16,24 @@ def test_vanilla_function(): def test_missing_global(): - with pytest.raises(NameError): + def func(): + return never_declared # noqa: F821 - @localscope - def func(): - return never_ever_declared # noqa: F821 + with pytest.raises(LocalscopeException, match="`never_declared` is not in globals"): + localscope(func) + + # IMPORTANT! This function can be executed, but localscope complains because the + # global variable is not defined at the time when the function is analysed. This + # could be improved, but, most likely, one shouldn't write functions that rely on + # future globals in the first place. + """ + never_declared = 123 + assert func() == 123 + """ def test_forbidden_global(): - with pytest.raises(ValueError): + with pytest.raises(LocalscopeException, match="`forbidden_global` is not a perm"): @localscope def return_forbidden_global(): @@ -57,7 +66,7 @@ def test_closure(): return return_forbidden_closure() - with pytest.raises(ValueError): + with pytest.raises(LocalscopeException, match="`forbidden_closure` is not a perm"): wrapper() @@ -76,7 +85,7 @@ def test_allow_any_closure(): def test_allow_custom_predicate(): decorator = localscope(predicate=lambda x: isinstance(x, int)) - with pytest.raises(ValueError): + with pytest.raises(LocalscopeException, match="`forbidden_global` is not a perm"): @decorator def return_forbidden_global(): @@ -90,7 +99,7 @@ def test_allow_custom_predicate(): def test_comprehension(): - with pytest.raises(ValueError): + with pytest.raises(LocalscopeException, match="`integer_global` is not a perm"): @localscope def evaluate_mse(xs, ys): # missing argument integer_global @@ -98,7 +107,7 @@ def test_comprehension(): def test_recursive(): - with pytest.raises(ValueError): + with pytest.raises(LocalscopeException, match="`forbidden_global` is not a perm"): @localscope def wrapper(): @@ -108,6 +117,17 @@ def test_recursive(): return return_forbidden_global() +def test_recursive_without_call(): + # We even raise an exception if we don't call a function. That's necessary because + # we can't trace all possible execution paths without actually running the function. + with pytest.raises(LocalscopeException, match="`forbidden_global` is not a perm"): + + @localscope + def wrapper(): + def return_forbidden_global(): + return forbidden_global + + def test_recursive_local_closure(): @localscope def wrapper(): @@ -134,7 +154,7 @@ def test_mfc(): x = 1 - with pytest.raises(ValueError): + with pytest.raises(LocalscopeException, match="`x` is not a permitted"): @localscope.mfc def breakit():
Add hints for where the offending variable is used... ... to make debugging easier.
0.0
fe4334355ea6e7bd1af0a15509b1f7a65f9da3b0
[ "[", "[100%]", "tests/test_localscope.py::test_vanilla_function", "tests/test_localscope.py::test_missing_global", "tests/test_localscope.py::test_forbidden_global", "tests/test_localscope.py::test_builtin", "tests/test_localscope.py::test_allowed", "tests/test_localscope.py::test_closure", "tests/test_localscope.py::test_allow_any_closure", "tests/test_localscope.py::test_allow_custom_predicate", "tests/test_localscope.py::test_comprehension", "tests/test_localscope.py::test_recursive", "tests/test_localscope.py::test_recursive_without_call", "tests/test_localscope.py::test_recursive_local_closure", "tests/test_localscope.py::test_mfc", "tests/test_localscope.py::test_comprehension_with_argument", "tests/test_localscope.py::test_comprehension_with_closure", "tests/test_localscope.py::test_argument", "tests/test_localscope.py::test_argument_with_closure", "tests/test_localscope.py::test_local_deref" ]
[]
{ "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 }
2024-02-17 01:12:54+00:00
mit
5,912
hynek__argon2-cffi-174
diff --git a/CHANGELOG.md b/CHANGELOG.md index e3fe7fb..46c0765 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,12 @@ What explicitly *may* change over time are the default hashing parameters and th ## [Unreleased](https://github.com/hynek/argon2-cffi/compare/23.1.0...HEAD) +### Changed + +- `argon2.PasswordHasher.check_needs_rehash()` now also accepts bytes like the rest of the API. + [#174](https://github.com/hynek/argon2-cffi/pull/174) + + ## [23.1.0](https://github.com/hynek/argon2-cffi/compare/21.3.0...23.1.0) - 2023-08-15 ### Removed diff --git a/src/argon2/_password_hasher.py b/src/argon2/_password_hasher.py index 125149b..ef940b3 100644 --- a/src/argon2/_password_hasher.py +++ b/src/argon2/_password_hasher.py @@ -244,7 +244,7 @@ class PasswordHasher: hash, _ensure_bytes(password, self.encoding), hash_type ) - def check_needs_rehash(self, hash: str) -> bool: + def check_needs_rehash(self, hash: str | bytes) -> bool: """ Check whether *hash* was created using the instance's parameters. @@ -264,5 +264,9 @@ class PasswordHasher: Whether *hash* was created using the instance's parameters. .. versionadded:: 18.2.0 + .. versionchanged:: 24.1.0 Accepts bytes for *hash*. """ + if isinstance(hash, bytes): + hash = hash.decode("ascii") + return self._parameters != extract_parameters(hash)
hynek/argon2-cffi
abd0cf90d665f0b709ecccefe4b6187d14d60ffa
diff --git a/tests/test_password_hasher.py b/tests/test_password_hasher.py index d6fa626..17f9410 100644 --- a/tests/test_password_hasher.py +++ b/tests/test_password_hasher.py @@ -109,22 +109,32 @@ class TestPasswordHasher: with pytest.raises(InvalidHash): PasswordHasher().verify("tiger", "does not matter") - def test_check_needs_rehash_no(self): + @pytest.mark.parametrize("use_bytes", [True, False]) + def test_check_needs_rehash_no(self, use_bytes): """ Return False if the hash has the correct parameters. """ ph = PasswordHasher(1, 8, 1, 16, 16) - assert not ph.check_needs_rehash(ph.hash("foo")) + hash = ph.hash("foo") + if use_bytes: + hash = hash.encode() - def test_check_needs_rehash_yes(self): + assert not ph.check_needs_rehash(hash) + + @pytest.mark.parametrize("use_bytes", [True, False]) + def test_check_needs_rehash_yes(self, use_bytes): """ Return True if any of the parameters changes. """ ph = PasswordHasher(1, 8, 1, 16, 16) ph_old = PasswordHasher(1, 8, 1, 8, 8) - assert ph.check_needs_rehash(ph_old.hash("foo")) + hash = ph_old.hash("foo") + if use_bytes: + hash = hash.encode() + + assert ph.check_needs_rehash(hash) def test_type_is_configurable(self): """
Make PasswordHasher.check_needs_rehash() accept bytes hash `PasswordHasher.check_needs_rehash()` should also accept bytes hashes to be consistent with the rest of the API.
0.0
abd0cf90d665f0b709ecccefe4b6187d14d60ffa
[ "tests/test_password_hasher.py::TestPasswordHasher::test_check_needs_rehash_no[True]", "tests/test_password_hasher.py::TestPasswordHasher::test_check_needs_rehash_yes[True]" ]
[ "tests/test_password_hasher.py::TestEnsureBytes::test_is_bytes", "tests/test_password_hasher.py::TestEnsureBytes::test_is_str", "tests/test_password_hasher.py::TestPasswordHasher::test_hash[p\\xe4ssword0]", "tests/test_password_hasher.py::TestPasswordHasher::test_hash[p\\xe4ssword1]", "tests/test_password_hasher.py::TestPasswordHasher::test_custom_salt", "tests/test_password_hasher.py::TestPasswordHasher::test_verify_agility[p\\xe4ssword0]", "tests/test_password_hasher.py::TestPasswordHasher::test_verify_agility[p\\xe4ssword1]", "tests/test_password_hasher.py::TestPasswordHasher::test_hash_verify[p\\xe4ssword0]", "tests/test_password_hasher.py::TestPasswordHasher::test_hash_verify[p\\xe4ssword1]", "tests/test_password_hasher.py::TestPasswordHasher::test_check", "tests/test_password_hasher.py::TestPasswordHasher::test_verify_invalid_hash_error", "tests/test_password_hasher.py::TestPasswordHasher::test_verify_invalid_hash", "tests/test_password_hasher.py::TestPasswordHasher::test_check_needs_rehash_no[False]", "tests/test_password_hasher.py::TestPasswordHasher::test_check_needs_rehash_yes[False]", "tests/test_password_hasher.py::TestPasswordHasher::test_type_is_configurable" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-04-16 06:36:03+00:00
mit
2,768
unit8co__darts-1435
diff --git a/darts/timeseries.py b/darts/timeseries.py index fc757f58..b629aa4f 100644 --- a/darts/timeseries.py +++ b/darts/timeseries.py @@ -2604,10 +2604,6 @@ class TimeSeries: attrs=self._xa.attrs, ) - # new_xa = xr.concat(objs=[self._xa, other_xa], dim=str(self._time_dim)) - if not self._has_datetime_index: - new_xa = new_xa.reset_index(dims_or_levels=new_xa.dims[0]) - return self.__class__.from_xarray( new_xa, fill_missing_dates=True, freq=self._freq_str ) @@ -2626,7 +2622,6 @@ class TimeSeries: TimeSeries A new TimeSeries with the new values appended """ - if self._has_datetime_index: idx = pd.DatetimeIndex( [self.end_time() + i * self._freq for i in range(1, len(values) + 1)], @@ -2634,9 +2629,10 @@ class TimeSeries: ) else: idx = pd.RangeIndex( - len(self), len(self) + self.freq * len(values), step=self.freq + start=self.end_time() + self._freq, + stop=self.end_time() + (len(values) + 1) * self._freq, + step=self._freq, ) - return self.append( self.__class__.from_times_and_values( values=values,
unit8co/darts
9a40ca61ad34a7087bcfb27b01f0ea845a9fa4ae
diff --git a/darts/tests/test_timeseries.py b/darts/tests/test_timeseries.py index c4414a13..61688bd2 100644 --- a/darts/tests/test_timeseries.py +++ b/darts/tests/test_timeseries.py @@ -621,15 +621,53 @@ class TimeSeriesTestCase(DartsBaseTestClass): def test_append(self): TimeSeriesTestCase.helper_test_append(self, self.series1) + # Check `append` deals with `RangeIndex` series correctly: + series_1 = linear_timeseries(start=1, length=5, freq=2) + series_2 = linear_timeseries(start=11, length=2, freq=2) + appended = series_1.append(series_2) + expected_vals = np.concatenate( + [series_1.all_values(), series_2.all_values()], axis=0 + ) + expected_idx = pd.RangeIndex(start=1, stop=15, step=2) + self.assertTrue(np.allclose(appended.all_values(), expected_vals)) + self.assertTrue(appended.time_index.equals(expected_idx)) def test_append_values(self): TimeSeriesTestCase.helper_test_append_values(self, self.series1) + # Check `append_values` deals with `RangeIndex` series correctly: + series = linear_timeseries(start=1, length=5, freq=2) + appended = series.append_values(np.ones((2, 1, 1))) + expected_vals = np.concatenate( + [series.all_values(), np.ones((2, 1, 1))], axis=0 + ) + expected_idx = pd.RangeIndex(start=1, stop=15, step=2) + self.assertTrue(np.allclose(appended.all_values(), expected_vals)) + self.assertTrue(appended.time_index.equals(expected_idx)) def test_prepend(self): TimeSeriesTestCase.helper_test_prepend(self, self.series1) + # Check `prepend` deals with `RangeIndex` series correctly: + series_1 = linear_timeseries(start=1, length=5, freq=2) + series_2 = linear_timeseries(start=11, length=2, freq=2) + prepended = series_2.prepend(series_1) + expected_vals = np.concatenate( + [series_1.all_values(), series_2.all_values()], axis=0 + ) + expected_idx = pd.RangeIndex(start=1, stop=15, step=2) + self.assertTrue(np.allclose(prepended.all_values(), expected_vals)) + self.assertTrue(prepended.time_index.equals(expected_idx)) def test_prepend_values(self): TimeSeriesTestCase.helper_test_prepend_values(self, self.series1) + # Check `prepend_values` deals with `RangeIndex` series correctly: + series = linear_timeseries(start=1, length=5, freq=2) + prepended = series.prepend_values(np.ones((2, 1, 1))) + expected_vals = np.concatenate( + [np.ones((2, 1, 1)), series.all_values()], axis=0 + ) + expected_idx = pd.RangeIndex(start=-3, stop=11, step=2) + self.assertTrue(np.allclose(prepended.all_values(), expected_vals)) + self.assertTrue(prepended.time_index.equals(expected_idx)) def test_with_values(self): vals = np.random.rand(5, 10, 3)
[BUG] `append_values` incorrectly extends `time_index` of `pd.RangeIndex`-typed `TimeSeries` **Describe the bug** When `append_values` is used to add new values to a `pd.RangeIndex`-typed `TimeSeries` , the `time_index` of the entire series is 'reset' so that each value is labeled with its index position. This is particularly unexpected if the `TimeSeries` in question does not have a frequency of `1` and/or does not start with a `time_index` of `0`. **To Reproduce** Consider the following example: ```python from darts.utils.timeseries_generation import linear_timeseries import numpy as np series = linear_timeseries(start=1, length=5, freq=2) print('Before `append_values`:') print(list(series.time_index)) new_values = np.ones((1,)) print('After `append_values`:') print(list(series.append_values(new_values).time_index)) ``` This yields: ``` Before `append_values`: [1, 3, 5, 7, 9] After `append_values`: [0, 1, 2, 3, 4, 5] ``` Notice how the `time_index` now starts at `0` instead of `1` **and** has a frequency of `1` instead of `2`. **Expected behavior** Instead of resetting the `time_index` of `pd.RangeIndex`-typed `TimeSeries`, `append_values` should 'extend' the `time_index`. More explicitly, for the previous example, one should expect the output: ``` Before `append_values`: [1, 3, 5, 7, 9] After `append_values`: [1, 3, 5, 7, 9, 11] ``` Indeed, this is the [behaviour that's advertised by `append_values`' docstring](https://unit8co.github.io/darts/generated_api/darts.timeseries.html#darts.timeseries.TimeSeries.append_values) and, additionally, is how it behaves when dealing with `pd.DatetimeIndex`-typed `TimeSeries`. To see this, consider the following example: ```python from darts.utils.timeseries_generation import linear_timeseries import numpy as np import pandas as pd series = linear_timeseries(start=pd.Timestamp('1/1/2000'), length=2, freq='2d') print('Before `append_values`:') print(list(series.time_index)) new_values = np.ones((1,)) print('After `append_values`:') print(list(series.append_values(new_values).time_index)) ``` This prints: ``` Before `append_values`: [Timestamp('2000-01-01 00:00:00', freq='2D'), Timestamp('2000-01-03 00:00:00', freq='2D')] After `append_values`: [Timestamp('2000-01-01 00:00:00', freq='2D'), Timestamp('2000-01-03 00:00:00', freq='2D'), Timestamp('2000-01-05 00:00:00', freq='2D')] ``` Notice how the `append_values` has simply added the date `2000-01-05` to the `time_index` of `series`. In cases where the user really wants 'reset' the `time_index` of a `TimeSeries` after appending values, this should probably be achieved by implementing a separate `TimeSeries.reset_index()` method. **System (please complete the following information):** - Python version: 3.10.6 - darts version: 0.22.0 **Additional context** N/A
0.0
9a40ca61ad34a7087bcfb27b01f0ea845a9fa4ae
[ "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_append", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_append_values", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_prepend", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_prepend_values" ]
[ "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_alt_creation", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_column_names", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_creation", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_dates", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_diff", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_drop", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_eq", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_fill_missing_dates", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_fillna_value", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_from_csv", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_gaps", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_getitem", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_index_creation", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_integer_indexing", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_intersect", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_longest_contiguous_slice", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_map", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_map_with_timestamp", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_map_wrong_fn", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_ops", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_quantiles", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_quantiles_df", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_rescale", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_shift", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_short_series_slice", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_slice", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_split", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_to_csv_deterministic", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_to_csv_probabilistic_ts", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_to_csv_stochastic", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_univariate_component", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_with_columns_renamed", "darts/tests/test_timeseries.py::TimeSeriesTestCase::test_with_values", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_component_different_time_axes_no_force", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_component_different_time_axes_with_force", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_component_different_time_axes_with_force_uneven_series", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_component_sunny_day", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_sample_sunny_day", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_time_different_time_axes_force", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_time_different_time_axes_no_force", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_time_different_time_axes_no_force_2_day_freq", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_time_same_time_force", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_time_same_time_no_force", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_time_sunny_day", "darts/tests/test_timeseries.py::TimeSeriesConcatenateTestCase::test_concatenate_timeseries_method", "darts/tests/test_timeseries.py::TimeSeriesHierarchyTestCase::test_concat", "darts/tests/test_timeseries.py::TimeSeriesHierarchyTestCase::test_creation_with_hierarchy_sunny_day", "darts/tests/test_timeseries.py::TimeSeriesHierarchyTestCase::test_hierarchy_processing", "darts/tests/test_timeseries.py::TimeSeriesHierarchyTestCase::test_ops", "darts/tests/test_timeseries.py::TimeSeriesHierarchyTestCase::test_with_hierarchy_rainy_day", "darts/tests/test_timeseries.py::TimeSeriesHierarchyTestCase::test_with_hierarchy_sunny_day", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_head_numeric_time_index", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_head_overshot_component_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_head_overshot_sample_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_head_overshot_time_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_head_sunny_day_component_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_head_sunny_day_sample_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_head_sunny_day_time_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_tail_numeric_time_index", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_tail_overshot_component_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_tail_overshot_sample_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_tail_overshot_time_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_tail_sunny_day_component_axis", "darts/tests/test_timeseries.py::TimeSeriesHeadTailTestCase::test_tail_sunny_day_time_axis", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_fail_with_bad_integer_time_col", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_from_dataframe_sunny_day", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_time_col_convert_datetime", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_time_col_convert_datetime_strings", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_time_col_convert_garbage", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_time_col_convert_integers", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_time_col_convert_rangeindex", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_time_col_convert_string_integers", "darts/tests/test_timeseries.py::TimeSeriesFromDataFrameTestCase::test_time_col_with_tz", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_kurtosis", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_max", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_mean", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_median", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_min", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_quantile", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_skew", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_std", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_sum", "darts/tests/test_timeseries.py::SimpleStatisticsTestCase::test_var" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-12-18 03:42:10+00:00
apache-2.0
6,165
scikit-build__scikit-build-105
diff --git a/skbuild/cmaker.py b/skbuild/cmaker.py index 9030c1e..2c7d7f5 100644 --- a/skbuild/cmaker.py +++ b/skbuild/cmaker.py @@ -9,6 +9,8 @@ import shlex import sys import sysconfig +from subprocess import CalledProcessError + from .platform_specifics import get_platform from .exceptions import SKBuildError @@ -62,10 +64,11 @@ def _touch_init(folder): class CMaker(object): def __init__(self, **defines): - if platform.system() != 'Windows': - rtn = subprocess.call(['which', 'cmake']) - if rtn != 0: - sys.exit('CMake is not installed, aborting build.') + # verify that CMake is installed + try: + subprocess.check_call(['cmake', '--version']) + except (OSError, CalledProcessError): + raise SKBuildError('CMake is not installed, aborting build.') self.platform = get_platform() @@ -93,8 +96,9 @@ class CMaker(object): generator_id = self.platform.get_best_generator(generator_id) if generator_id is None: - sys.exit("Could not get working generator for your system." - " Aborting build.") + raise SKBuildError( + "Could not get working generator for your system." + " Aborting build.") if not os.path.exists(CMAKE_BUILD_DIR): os.makedirs(CMAKE_BUILD_DIR) @@ -137,11 +141,20 @@ class CMaker(object): # changes dir to cmake_build and calls cmake's configure step # to generate makefile - rtn = subprocess.check_call(cmd, cwd=CMAKE_BUILD_DIR) + rtn = subprocess.call(cmd, cwd=CMAKE_BUILD_DIR) if rtn != 0: - raise RuntimeError("Could not successfully configure " - "your project. Please see CMake's " - "output for more information.") + raise SKBuildError( + "An error occurred while configuring with CMake.\n" + " Command:\n" + " {}\n" + " Source directory:\n" + " {}\n" + " Working directory:\n" + " {}\n" + "Please see CMake's output for more information.".format( + self._formatArgsForDisplay(cmd), + os.path.abspath(cwd), + os.path.abspath(CMAKE_BUILD_DIR))) CMaker.check_for_bad_installs() @@ -335,7 +348,6 @@ class CMaker(object): if bad_installs: raise SKBuildError("\n".join(( - "", " CMake-installed files must be within the project root.", " Project Root:", " " + install_dir, @@ -349,7 +361,7 @@ class CMaker(object): """ clargs, config = pop_arg('--config', clargs, config) if not os.path.exists(CMAKE_BUILD_DIR): - raise RuntimeError(("CMake build folder ({}) does not exist. " + raise SKBuildError(("CMake build folder ({}) does not exist. " "Did you forget to run configure before " "make?").format(CMAKE_BUILD_DIR)) @@ -361,8 +373,20 @@ class CMaker(object): shlex.split(os.environ.get("SKBUILD_BUILD_OPTIONS", ""))) ) - rtn = subprocess.check_call(cmd, cwd=CMAKE_BUILD_DIR) - return rtn + rtn = subprocess.call(cmd, cwd=CMAKE_BUILD_DIR) + if rtn != 0: + raise SKBuildError( + "An error occurred while building with CMake.\n" + " Command:\n" + " {}\n" + " Source directory:\n" + " {}\n" + " Working directory:\n" + " {}\n" + "Please see CMake's output for more information.".format( + self._formatArgsForDisplay(cmd), + os.path.abspath(source_dir), + os.path.abspath(CMAKE_BUILD_DIR))) def install(self): """Returns a list of tuples of (install location, file list) to install @@ -377,3 +401,14 @@ class CMaker(object): return [_remove_cwd_prefix(path) for path in manifest] return [] + + @staticmethod + def _formatArgsForDisplay(args): + """Format a list of arguments appropriately for display. When formatting + a command and its arguments, the user should be able to execute the + command by copying and pasting the output directly into a shell. + + Currently, the only formatting is naively surrounding each argument with + quotation marks. + """ + return ' '.join("\"{}\"".format(arg) for arg in args) diff --git a/skbuild/exceptions.py b/skbuild/exceptions.py index 4a0e074..2b8f8b1 100644 --- a/skbuild/exceptions.py +++ b/skbuild/exceptions.py @@ -1,3 +1,6 @@ -class SKBuildError(Exception): +class SKBuildError(RuntimeError): + """Exception raised when an error occurs while configuring or building a + project. + """ pass diff --git a/skbuild/setuptools_wrap.py b/skbuild/setuptools_wrap.py index 0fbd86f..54efdb3 100644 --- a/skbuild/setuptools_wrap.py +++ b/skbuild/setuptools_wrap.py @@ -131,12 +131,56 @@ def setup(*args, **kw): reverse=True )) - cmkr = cmaker.CMaker() - cmkr.configure(cmake_args) - cmkr.make(make_args) + try: + cmkr = cmaker.CMaker() + cmkr.configure(cmake_args) + cmkr.make(make_args) + except SKBuildError as e: + import traceback + print("Traceback (most recent call last):") + traceback.print_tb(sys.exc_info()[2]) + print() + sys.exit(e) + + _classify_files(cmkr.install(), package_data, package_prefixes, py_modules, + scripts, new_scripts, data_files) + + kw['package_data'] = package_data + kw['package_dir'] = { + package: os.path.join(cmaker.CMAKE_INSTALL_DIR, prefix) + for prefix, package in package_prefixes + } + + kw['py_modules'] = py_modules + + kw['scripts'] = [ + os.path.join(cmaker.CMAKE_INSTALL_DIR, script) if mask else script + for script, mask in new_scripts.items() + ] + + kw['data_files'] = [ + (parent_dir, list(file_set)) + for parent_dir, file_set in data_files.items() + ] + + # work around https://bugs.python.org/issue1011113 + # (patches provided, but no updates since 2014) + cmdclass = kw.get('cmdclass', {}) + cmdclass['build'] = cmdclass.get('build', build.build) + cmdclass['install'] = cmdclass.get('install', install.install) + cmdclass['clean'] = cmdclass.get('clean', clean.clean) + cmdclass['bdist'] = cmdclass.get('bdist', bdist.bdist) + cmdclass['bdist_wheel'] = cmdclass.get( + 'bdist_wheel', bdist_wheel.bdist_wheel) + kw['cmdclass'] = cmdclass + + return upstream_setup(*args, **kw) + +def _classify_files(install_paths, package_data, package_prefixes, py_modules, + scripts, new_scripts, data_files): install_root = os.path.join(os.getcwd(), cmaker.CMAKE_INSTALL_DIR) - for path in cmkr.install(): + for path in install_paths: found_package = False found_module = False found_script = False @@ -204,34 +248,3 @@ def setup(*args, **kw): data_files[parent_dir] = file_set file_set.add(os.path.join(cmaker.CMAKE_INSTALL_DIR, path)) del parent_dir, file_set - - kw['package_data'] = package_data - kw['package_dir'] = { - package: os.path.join(cmaker.CMAKE_INSTALL_DIR, prefix) - for prefix, package in package_prefixes - } - - kw['py_modules'] = py_modules - - kw['scripts'] = [ - os.path.join(cmaker.CMAKE_INSTALL_DIR, script) if mask else script - for script, mask in new_scripts.items() - ] - - kw['data_files'] = [ - (parent_dir, list(file_set)) - for parent_dir, file_set in data_files.items() - ] - - # work around https://bugs.python.org/issue1011113 - # (patches provided, but no updates since 2014) - cmdclass = kw.get('cmdclass', {}) - cmdclass['build'] = cmdclass.get('build', build.build) - cmdclass['install'] = cmdclass.get('install', install.install) - cmdclass['clean'] = cmdclass.get('clean', clean.clean) - cmdclass['bdist'] = cmdclass.get('bdist', bdist.bdist) - cmdclass['bdist_wheel'] = cmdclass.get( - 'bdist_wheel', bdist_wheel.bdist_wheel) - kw['cmdclass'] = cmdclass - - return upstream_setup(*args, **kw)
scikit-build/scikit-build
abaaeee43e0456ef9da7d4878f0310c569bd6525
diff --git a/tests/test_outside_project_root.py b/tests/test_outside_project_root.py index 9500a4d..d67baa4 100644 --- a/tests/test_outside_project_root.py +++ b/tests/test_outside_project_root.py @@ -5,7 +5,8 @@ ---------------------------------- Tries to build the `fail-outside-project-root` sample project. Ensures that the -attempt fails with an SKBuildError exception. +attempt fails with a SystemExit exception that has an SKBuildError exception as +its value. """ from skbuild.exceptions import SKBuildError @@ -23,10 +24,10 @@ def test_outside_project_root_fails(): def should_fail(): pass - exception_thrown = False + failed = False try: should_fail() - except SKBuildError: - exception_thrown = True + except SystemExit as e: + failed = isinstance(e.code, SKBuildError) - assert exception_thrown + assert failed
Improve cmaker exception When there is a problem building python module, report "human-friendly" error
0.0
abaaeee43e0456ef9da7d4878f0310c569bd6525
[ "tests/test_outside_project_root.py::test_outside_project_root_fails" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-07-22 19:35:31+00:00
mit
5,355
pythonprofilers__memory_profiler-280
diff --git a/README.rst b/README.rst index b52b6f2..79d1c6b 100644 --- a/README.rst +++ b/README.rst @@ -64,14 +64,14 @@ this would result in:: Output will follow:: - Line # Mem usage Increment Line Contents - ============================================== - 3 @profile - 4 5.97 MB 0.00 MB def my_func(): - 5 13.61 MB 7.64 MB a = [1] * (10 ** 6) - 6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7) - 7 13.61 MB -152.59 MB del b - 8 13.61 MB 0.00 MB return a + Line # Mem usage Increment Occurences Line Contents + ============================================================ + 3 38.816 MiB 38.816 MiB 1 @profile + 4 def my_func(): + 5 46.492 MiB 7.676 MiB 1 a = [1] * (10 ** 6) + 6 199.117 MiB 152.625 MiB 1 b = [2] * (2 * 10 ** 7) + 7 46.629 MiB -152.488 MiB 1 del b + 8 46.629 MiB 0.000 MiB 1 return a The first column represents the line number of the code that has been diff --git a/memory_profiler.py b/memory_profiler.py index cd4ba4f..632bee3 100644 --- a/memory_profiler.py +++ b/memory_profiler.py @@ -280,10 +280,10 @@ def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False, to this file instead of stored in memory and returned at the end of the subprocess. Useful for long-running processes. Implies timestamps=True. - + max_iterations : int Limits the number of iterations (calls to the process being monitored). Relevent - when the process is a python function. + when the process is a python function. Returns ------- @@ -357,7 +357,7 @@ def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False, raise p.join(5 * interval) - + if (n_measurements > 4) or (current_iter == max_iter) or (interval < 1e-6): break interval /= 10. @@ -643,7 +643,12 @@ class CodeMap(dict): prev_line_value = self[code].get(prev_lineno, None) if prev_lineno else None prev_line_memory = prev_line_value[1] if prev_line_value else 0 - self[code][lineno] = (max(previous_inc, memory-prev_line_memory), max(memory, previous_memory)) + occ_count = self[code][lineno][2] + 1 if lineno in self[code] else 1 + self[code][lineno] = ( + previous_inc + (memory - prev_line_memory), + max(memory, previous_memory), + occ_count, + ) def items(self): """Iterate on the toplevel code blocks.""" @@ -800,10 +805,10 @@ class LineProfiler(object): def show_results(prof, stream=None, precision=1): if stream is None: stream = sys.stdout - template = '{0:>6} {1:>12} {2:>12} {3:<}' + template = '{0:>6} {1:>12} {2:>12} {3:>10} {4:<}' for (filename, lines) in prof.code_map.items(): - header = template.format('Line #', 'Mem usage', 'Increment', + header = template.format('Line #', 'Mem usage', 'Increment', 'Occurences', 'Line Contents') stream.write(u'Filename: ' + filename + '\n\n') @@ -817,13 +822,15 @@ def show_results(prof, stream=None, precision=1): for (lineno, mem) in lines: if mem: inc = mem[0] - mem = mem[1] - mem = template_mem.format(mem) + total_mem = mem[1] + total_mem = template_mem.format(total_mem) + occurences = mem[2] inc = template_mem.format(inc) else: - mem = u'' + total_mem = u'' inc = u'' - tmp = template.format(lineno, mem, inc, all_lines[lineno - 1]) + occurences = u'' + tmp = template.format(lineno, total_mem, inc, occurences, all_lines[lineno - 1]) stream.write(to_str(tmp)) stream.write(u'\n\n')
pythonprofilers/memory_profiler
8a8a40252cccc09dc469445596742dc6b47ed6e3
diff --git a/test/test_increment_display.py b/test/test_increment_display.py new file mode 100644 index 0000000..b0dbe51 --- /dev/null +++ b/test/test_increment_display.py @@ -0,0 +1,81 @@ +import unittest + +from memory_profiler import LineProfiler, profile, show_results +from io import StringIO + + +class TestIncrementDisplay(unittest.TestCase): + """Tests memory incrementation / decrementation display""" + + def test_loop_count(self): + + def some_loop(): + for i in range(12): # line -2 + a = 1 # line -1 + + profiler = LineProfiler() + wrapped = profiler(some_loop) + wrapped() + show_results(profiler) + for_line = list(list(profiler.code_map.values())[0].values())[-2] + looped_instruction = list(list(profiler.code_map.values())[0].values())[-1] + + self.assertEqual(for_line[2], 13) + self.assertEqual(looped_instruction[2], 12) + + def test_normal_incr(self): + + def normal_incr(): + use_some_memory = [1] * (10 ** 6) + + profiler = LineProfiler() + wrapped = profiler(normal_incr) + wrapped() + + show_results(profiler) + results = list(list(profiler.code_map.values())[0].values())[-1] + + self.assertGreater(results[0], 0) + self.assertGreater(results[1], results[0]) + self.assertEqual(results[2], 1) + + def test_loop_incr(self): + + def loop_incr(): + a = [] + b = [2] * (2 * 10 ** 7) # line -4 + for i in range(3): + c = [2] * (2 * 10 ** 7) # line -2 + a.append(c) + + profiler = LineProfiler() + wrapped = profiler(loop_incr) + wrapped() + + show_results(profiler) + b_line = list(list(profiler.code_map.values())[0].values())[-4] + c_line = list(list(profiler.code_map.values())[0].values())[-2] + self.assertAlmostEqual(b_line[2] * 3, c_line[2], delta=1) + self.assertEqual(c_line[2], 3) + + def test_decr(self): + + def del_stuff(): + b = [2] * (2 * 10 ** 7) + del b + + profiler = LineProfiler() + wrapped = profiler(del_stuff) + wrapped() + + show_results(profiler) + b_line = list(list(profiler.code_map.values())[0].values())[-2] + del_line = list(list(profiler.code_map.values())[0].values())[-1] + + self.assertGreater(0, del_line[0]) + self.assertGreater(del_line[1], 0) + self.assertAlmostEqual(-del_line[0], b_line[0], delta=1) + + +if __name__ == '__main__': + unittest.main()
The first example in readme not working correctly Here's what I get on both windows and linux. ``` Line # Mem usage Increment Line Contents ================================================ 1 37.754 MiB 37.754 MiB @profile 2 def my_func(): 3 45.195 MiB 7.441 MiB a = [1] * (10 ** 6) 4 197.820 MiB 152.625 MiB b = [2] * (2 * 10 ** 7) 5 45.449 MiB 0.000 MiB del b 6 45.449 MiB 0.000 MiB return a ``` I would expect it to show released memory after `del b` as it is described in the readme file.
0.0
8a8a40252cccc09dc469445596742dc6b47ed6e3
[ "test/test_increment_display.py::TestIncrementDisplay::test_decr", "test/test_increment_display.py::TestIncrementDisplay::test_loop_count", "test/test_increment_display.py::TestIncrementDisplay::test_loop_incr", "test/test_increment_display.py::TestIncrementDisplay::test_normal_incr" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-05-10 03:07:05+00:00
bsd-3-clause
5,119
megajanlott__cbor-decoder-47
diff --git a/cbor/MajorType.py b/cbor/MajorType.py index d9b0d34..2f43a8c 100644 --- a/cbor/MajorType.py +++ b/cbor/MajorType.py @@ -3,6 +3,7 @@ from cbor.State import State from cbor.type.ByteString import ByteString from cbor.type.TextString import TextString from cbor.type.Array import ArrayInfo +from cbor.type.Map import MapInfo MAJOR_TYPE_MASK = 0b11100000 MAJOR_TYPE_SIZE = 3 @@ -26,5 +27,7 @@ class MajorType(State): return TextString() elif t == 4: return ArrayInfo() + elif t == 5: + return MapInfo() return diff --git a/cbor/type/Map.py b/cbor/type/Map.py new file mode 100644 index 0000000..e46f64e --- /dev/null +++ b/cbor/type/Map.py @@ -0,0 +1,84 @@ +import cbor.CBORStream +import cbor.MajorType +import cbor.State + + +class MapInfo(cbor.State.State): + + def run(self, stream: cbor.CBORStream.CBORStream, handler): + info = stream.read(1) + length = ord(info) & 0b00011111 + handler('{') + if length == 0: + handler('}') + elif length < 24: + return [MapReadValue(length), cbor.MajorType.MajorType()] + elif length == 24: + return [MapLen(1)] + elif length == 25: + return [MapLen(2)] + elif length == 26: + return [MapLen(4)] + elif length == 27: + return [MapLen(8)] + elif length == 31: + return [MapInfValue(), cbor.MajorType.MajorType()] + return [] + + +class MapLen(cbor.State.State): + + def __eq__(self, other): + return self.n == other.n + + def __init__(self, n: int): + self.n = n + + def run(self, stream: cbor.CBORStream.CBORStream, handler): + info = stream.read(self.n) + length = int.from_bytes(info, byteorder='big') + return [MapReadValue(length), cbor.MajorType.MajorType()] + + +class MapReadKey(cbor.State.State): + + def __eq__(self, other): + return self.n == other.n + + def __init__(self, n: int): + self.n = n + + def run(self, stream: cbor.CBORStream.CBORStream, handler): + if self.n == 0: + handler('}') + return [] + if self.n > 0: + handler(',') + return [MapReadValue(self.n), cbor.MajorType.MajorType()] + + +class MapReadValue(cbor.State.State): + + def __eq__(self, other): + return self.n == other.n + + def __init__(self, n: int): + self.n = n + + def run(self, stream: cbor.CBORStream.CBORStream, handler): + handler(':') + return [MapReadKey(self.n-1), cbor.MajorType.MajorType()] + + +class MapInfKey(cbor.State.State): + + def run(self, stream: cbor.CBORStream.CBORStream, handler): + handler(',') + return [MapInfValue(), cbor.MajorType.MajorType()] + + +class MapInfValue(cbor.State.State): + + def run(self, stream: cbor.CBORStream.CBORStream, handler): + handler(':') + return [MapInfKey(), cbor.MajorType.MajorType()]
megajanlott/cbor-decoder
c2af49e12ad7fe36433ec013b176f4dda89a4b2e
diff --git a/tests/test_Map.py b/tests/test_Map.py new file mode 100644 index 0000000..7497c8d --- /dev/null +++ b/tests/test_Map.py @@ -0,0 +1,147 @@ +from io import BytesIO +from cbor.MajorType import MajorType +from cbor.CBORStream import CBORStream +from cbor.type.Map import * +from tests.MockHandler import MockHandler +from cbor.Decoder import Decoder + + +def ignore_handler(v): + return + + +def test_run_map_probe(): + data = CBORStream(BytesIO(bytes([0b10100001]))) + assert type(MajorType().run(data, None)) == MapInfo + + +def test_run_map_length(): + # Map length lower than 24. + data = CBORStream(BytesIO(bytes([0b10100011]))) + stack = MapInfo().run(data, ignore_handler) + assert len(stack) == 2 + assert type(stack[0]) == MapReadValue + assert stack[0] == MapReadValue(3) + assert type(stack[1]) == MajorType + + +def test_run_map_length_multibyte(): + # Map length on 1 byte. + data = CBORStream(BytesIO(bytes([ + 0b10111000, 0b1 + ]))) + stack = MapInfo().run(data, ignore_handler) + assert len(stack) == 1 + assert type(stack[0]) == MapLen + assert stack[0] == MapLen(1) + stack2 = stack[0].run(data, ignore_handler) + assert len(stack2) == 2 + assert type(stack2[0]) == MapReadValue + assert stack2[0] == MapReadValue(1) + assert type(stack2[1]) == MajorType + + # Map length on 2 bytes. + data = CBORStream(BytesIO(bytes([ + 0b10111001, 0b1, 0b0 + ]))) + stack = MapInfo().run(data, ignore_handler) + assert len(stack) == 1 + assert type(stack[0]) == MapLen + assert stack[0] == MapLen(2) + stack2 = stack[0].run(data, ignore_handler) + assert len(stack2) == 2 + assert type(stack2[0]) == MapReadValue + assert stack2[0] == MapReadValue(1 << 8) + assert type(stack2[1]) == MajorType + + # Map length on 4 bytes. + data = CBORStream(BytesIO(bytes([ + 0b10111010, 0b1, 0b0, 0b0, 0b0 + ]))) + stack = MapInfo().run(data, ignore_handler) + assert len(stack) == 1 + assert type(stack[0]) == MapLen + assert stack[0] == MapLen(4) + stack2 = stack[0].run(data, ignore_handler) + assert len(stack2) == 2 + assert type(stack2[0]) == MapReadValue + assert stack2[0] == MapReadValue(1 << 24) + assert type(stack2[1]) == MajorType + + # Map length on 8 bytes. + data = CBORStream(BytesIO(bytes([ + 0b10111011, 0b1, 0b0, 0b0, 0b0, 0b0, 0b0, 0b0, 0b0 + ]))) + stack = MapInfo().run(data, ignore_handler) + assert len(stack) == 1 + assert type(stack[0]) == MapLen + assert stack[0] == MapLen(8) + stack2 = stack[0].run(data, ignore_handler) + assert len(stack2) == 2 + assert type(stack2[0]) == MapReadValue + assert stack2[0] == MapReadValue(1 << 56) + assert type(stack2[1]) == MajorType + + +def test_run_map_inf(): + # Map with infinite length. + data = CBORStream(BytesIO(bytes([0b10111111]))) + stack = MapInfo().run(data, ignore_handler) + assert len(stack) == 2 + assert type(stack[0]) == MapInfValue + assert type(stack[1]) == MajorType + + +def test_run_map_inf_key(): + # Map with infinite length. + data = CBORStream(BytesIO(bytes([]))) + stack = MapInfKey().run(data, ignore_handler) + assert len(stack) == 2 + assert type(stack[0]) == MapInfValue + assert type(stack[1]) == MajorType + + +def test_run_map_inf_value(): + # Map with infinite length. + data = CBORStream(BytesIO(bytes([]))) + stack = MapInfValue().run(data, ignore_handler) + assert len(stack) == 2 + assert type(stack[0]) == MapInfKey + assert type(stack[1]) == MajorType + + +def test_run_map_info_empty(): + handler = MockHandler() + + # Empty array. + data = CBORStream(BytesIO(bytes([0b10100000]))) + stack = MapInfo().run(data, handler.handler) + assert len(stack) == 0 + handler.assert_data('{}') + + +def test_run_map_single_element(): + handler = MockHandler() + + # Empty array. + d = Decoder() + data = bytes([0b10100001, 0b10100000, 0b10100000]) + d.decode_array(data, handler.handler) + print(handler.data) + handler.assert_data('{{}:{}}') + + +def test_run_map_two_elements(): + handler = MockHandler() + + # Empty array. + d = Decoder() + data = bytes([ + 0b10100010, + 0b10100000, + 0b10100000, + 0b10100000, + 0b10100000]) + d.decode_array(data, handler.handler) + print(handler.data) + handler.assert_data('{{}:{},{}:{}}')
Map Map states: - [ ] Implement MapInfo - [ ] Implement MapReadKey(n) - [ ] Implement MapReadValue(n) - [ ] Implement MapLen(n) - [ ] Implement MapInfKey() - [ ] Implement MapInfValue() Additional info about states can be found here: https://docs.google.com/document/d/1tvQJtJbYUcM2vI5H0RDukWqNYsLxjczZ30PiBFFVsV8/edit#
0.0
c2af49e12ad7fe36433ec013b176f4dda89a4b2e
[ "tests/test_Map.py::test_run_map_probe", "tests/test_Map.py::test_run_map_length", "tests/test_Map.py::test_run_map_length_multibyte", "tests/test_Map.py::test_run_map_inf", "tests/test_Map.py::test_run_map_inf_key", "tests/test_Map.py::test_run_map_inf_value", "tests/test_Map.py::test_run_map_info_empty", "tests/test_Map.py::test_run_map_single_element", "tests/test_Map.py::test_run_map_two_elements" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2017-05-02 10:56:59+00:00
mit
3,858
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
34