instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
stringclasses 1
value | environment_setup_commit
stringlengths 40
40
| FAIL_TO_PASS
listlengths 1
4.94k
| PASS_TO_PASS
listlengths 0
7.82k
| meta
dict | created_at
stringlengths 25
25
| license
stringclasses 8
values | __index_level_0__
int64 0
6.41k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pystorm__pystorm-31
|
diff --git a/pystorm/bolt.py b/pystorm/bolt.py
index 4e60879..c6a1538 100644
--- a/pystorm/bolt.py
+++ b/pystorm/bolt.py
@@ -128,7 +128,7 @@ class Bolt(Component):
pass
def emit(self, tup, stream=None, anchors=None, direct_task=None,
- need_task_ids=True):
+ need_task_ids=False):
"""Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
@@ -146,13 +146,13 @@ class Bolt(Component):
:param direct_task: the task to send the Tuple to.
:type direct_task: int
:param need_task_ids: indicate whether or not you'd like the task IDs
- the Tuple was emitted (default: ``True``).
+ the Tuple was emitted (default: ``False``).
:type need_task_ids: bool
- :returns: a ``list`` of task IDs that the Tuple was sent to. Note that
- when specifying direct_task, this will be equal to
- ``[direct_task]``. If you specify ``need_task_ids=False``,
- this function will return ``None``.
+ :returns: ``None``, unless ``need_task_ids=True``, in which case it will
+ be a ``list`` of task IDs that the Tuple was sent to if. Note
+ that when specifying direct_task, this will be equal to
+ ``[direct_task]``.
"""
if anchors is None:
anchors = self._current_tups if self.auto_anchor else []
diff --git a/pystorm/component.py b/pystorm/component.py
index e4b3764..757767f 100644
--- a/pystorm/component.py
+++ b/pystorm/component.py
@@ -364,7 +364,7 @@ class Component(object):
'level': level})
def emit(self, tup, tup_id=None, stream=None, anchors=None,
- direct_task=None, need_task_ids=True):
+ direct_task=None, need_task_ids=False):
"""Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
@@ -385,13 +385,13 @@ class Component(object):
:param direct_task: the task to send the Tuple to.
:type direct_task: int
:param need_task_ids: indicate whether or not you'd like the task IDs
- the Tuple was emitted (default: ``True``).
+ the Tuple was emitted (default: ``False``).
:type need_task_ids: bool
- :returns: a ``list`` of task IDs that the Tuple was sent to. Note that
- when specifying direct_task, this will be equal to
- ``[direct_task]``. If you specify ``need_task_ids=False``,
- this function will return ``None``.
+ :returns: ``None``, unless ``need_task_ids=True``, in which case it will
+ be a ``list`` of task IDs that the Tuple was sent to if. Note
+ that when specifying direct_task, this will be equal to
+ ``[direct_task]``.
"""
if not isinstance(tup, (list, tuple)):
raise TypeError('All Tuples must be either lists or tuples, '
diff --git a/pystorm/spout.py b/pystorm/spout.py
index 5290c9a..cc21903 100644
--- a/pystorm/spout.py
+++ b/pystorm/spout.py
@@ -54,7 +54,7 @@ class Spout(Component):
raise NotImplementedError()
def emit(self, tup, tup_id=None, stream=None, direct_task=None,
- need_task_ids=True):
+ need_task_ids=False):
"""Emit a spout Tuple message.
:param tup: the Tuple to send to Storm, should contain only
@@ -70,14 +70,13 @@ class Spout(Component):
direct emit.
:type direct_task: int
:param need_task_ids: indicate whether or not you'd like the task IDs
- the Tuple was emitted (default:
- ``True``).
+ the Tuple was emitted (default: ``False``).
:type need_task_ids: bool
- :returns: a ``list`` of task IDs that the Tuple was sent to. Note that
- when specifying direct_task, this will be equal to
- ``[direct_task]``. If you specify ``need_task_ids=False``,
- this function will return ``None``.
+ :returns: ``None``, unless ``need_task_ids=True``, in which case it will
+ be a ``list`` of task IDs that the Tuple was sent to if. Note
+ that when specifying direct_task, this will be equal to
+ ``[direct_task]``.
"""
return super(Spout, self).emit(tup, tup_id=tup_id, stream=stream,
direct_task=direct_task,
|
pystorm/pystorm
|
506568d7033169811423a08f3af83c15abe5fd3e
|
diff --git a/test/pystorm/test_bolt.py b/test/pystorm/test_bolt.py
index 277ac1a..24cb868 100644
--- a/test/pystorm/test_bolt.py
+++ b/test/pystorm/test_bolt.py
@@ -110,7 +110,8 @@ class BoltTests(unittest.TestCase):
send_message_mock.assert_called_with(self.bolt, {'command': 'emit',
'anchors': [],
'tuple': [1, 2, 3],
- 'task': 'other_bolt'})
+ 'task': 'other_bolt',
+ 'need_task_ids': False})
@patch.object(Bolt, 'send_message', autospec=True)
def test_ack_id(self, send_message_mock):
diff --git a/test/pystorm/test_spout.py b/test/pystorm/test_spout.py
index 2b4e1a9..a3d7a15 100644
--- a/test/pystorm/test_spout.py
+++ b/test/pystorm/test_spout.py
@@ -49,7 +49,8 @@ class SpoutTests(unittest.TestCase):
self.spout.emit([1, 2, 3], direct_task='other_spout')
send_message_mock.assert_called_with(self.spout, {'command': 'emit',
'tuple': [1, 2, 3],
- 'task': 'other_spout'})
+ 'task': 'other_spout',
+ 'need_task_ids': False})
# Reliable emit
self.spout.emit([1, 2, 3], tup_id='foo', need_task_ids=False)
send_message_mock.assert_called_with(self.spout, {'command': 'emit',
@@ -62,7 +63,8 @@ class SpoutTests(unittest.TestCase):
send_message_mock.assert_called_with(self.spout, {'command': 'emit',
'tuple': [1, 2, 3],
'task': 'other_spout',
- 'id': 'foo'})
+ 'id': 'foo',
+ 'need_task_ids': False})
@patch.object(Spout, 'read_command', autospec=True,
return_value={'command': 'ack', 'id': 1234})
|
need_task_ids should default to False
We currently default to True for backward compatibility reasons, but I would venture to guess that vast majority of users do not care about the IDs of the tasks that their emitted tuples went to. Disabling is a nice free speedup, but if we made it disabled by default, we would be cutting out extra work for most users.
|
0.0
|
506568d7033169811423a08f3af83c15abe5fd3e
|
[
"test/pystorm/test_bolt.py::BoltTests::test_emit_direct",
"test/pystorm/test_spout.py::SpoutTests::test_emit"
] |
[
"test/pystorm/test_bolt.py::BoltTests::test_ack_id",
"test/pystorm/test_bolt.py::BoltTests::test_ack_tuple",
"test/pystorm/test_bolt.py::BoltTests::test_auto_ack_off",
"test/pystorm/test_bolt.py::BoltTests::test_auto_ack_on",
"test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_off",
"test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_on",
"test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_override",
"test/pystorm/test_bolt.py::BoltTests::test_auto_fail_off",
"test/pystorm/test_bolt.py::BoltTests::test_auto_fail_on",
"test/pystorm/test_bolt.py::BoltTests::test_emit_basic",
"test/pystorm/test_bolt.py::BoltTests::test_emit_stream_anchors",
"test/pystorm/test_bolt.py::BoltTests::test_fail_id",
"test/pystorm/test_bolt.py::BoltTests::test_fail_tuple",
"test/pystorm/test_bolt.py::BoltTests::test_heartbeat_response",
"test/pystorm/test_bolt.py::BoltTests::test_process_tick",
"test/pystorm/test_bolt.py::BoltTests::test_read_tuple",
"test/pystorm/test_bolt.py::BoltTests::test_read_tuple_named_fields",
"test/pystorm/test_bolt.py::BoltTests::test_run",
"test/pystorm/test_bolt.py::BoltTests::test_setup_component",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_ack_off",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_ack_on",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_off",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_on",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_partial",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_batching",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_group_key",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_heartbeat_response",
"test/pystorm/test_bolt.py::BatchingBoltTests::test_process_tick",
"test/pystorm/test_spout.py::SpoutTests::test_ack",
"test/pystorm/test_spout.py::SpoutTests::test_fail",
"test/pystorm/test_spout.py::SpoutTests::test_next_tuple"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-04-15 18:03:37+00:00
|
apache-2.0
| 5,035 |
|
pytest-dev__pytest-mock-273
|
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index f8840c0..6969d9d 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -10,17 +10,17 @@ jobs:
strategy:
fail-fast: false
matrix:
- python: ["3.6", "3.7", "3.8", "3.9"]
+ python: ["3.7", "3.8", "3.9", "3.10"]
os: [ubuntu-latest, windows-latest]
include:
- - python: "3.6"
- tox_env: "py36"
- python: "3.7"
tox_env: "py37"
- python: "3.8"
tox_env: "py38"
- python: "3.9"
tox_env: "py39"
+ - python: "3.10"
+ tox_env: "py310"
steps:
- uses: actions/checkout@v1
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 0f88309..6e1eafd 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,3 +1,9 @@
+3.7.0 (UNRELEASED)
+------------------
+
+* Python 3.10 now officially supported.
+* Dropped support for Python 3.6.
+
3.6.1 (2021-05-06)
------------------
diff --git a/HOWTORELEASE.rst b/RELEASING.rst
similarity index 100%
rename from HOWTORELEASE.rst
rename to RELEASING.rst
diff --git a/mypy.ini b/mypy.ini
index 2b6bae7..2daaec5 100644
--- a/mypy.ini
+++ b/mypy.ini
@@ -2,6 +2,7 @@
disallow_any_generics = True
disallow_incomplete_defs = True
disallow_subclassing_any = True
+ignore_missing_imports = True
no_implicit_optional = True
pretty = True
show_error_codes = True
diff --git a/setup.py b/setup.py
index 96db74f..7de0ab4 100644
--- a/setup.py
+++ b/setup.py
@@ -12,7 +12,7 @@ setup(
package_data={
"pytest_mock": ["py.typed"],
},
- python_requires=">=3.6",
+ python_requires=">=3.7",
install_requires=["pytest>=5.0"],
use_scm_version={"write_to": "src/pytest_mock/_version.py"},
setup_requires=["setuptools_scm"],
@@ -31,10 +31,10 @@ setup(
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Software Development :: Testing",
],
diff --git a/tox.ini b/tox.ini
index 5a2030a..2af93bf 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,6 +1,6 @@
[tox]
minversion = 3.5.3
-envlist = py{35,36,37,38,39}, linting, norewrite
+envlist = py{37,38,39,310}, linting, norewrite
[testenv]
passenv = USER USERNAME
@@ -28,6 +28,7 @@ commands = mypy {posargs:src tests}
[pytest]
addopts = -r a
+asyncio_mode = auto
[flake8]
max-line-length = 88
|
pytest-dev/pytest-mock
|
3ca933aa93bf72877063e82c7f549879c6f34ddb
|
diff --git a/tests/test_pytest_mock.py b/tests/test_pytest_mock.py
index 6d8feda..cca50ad 100644
--- a/tests/test_pytest_mock.py
+++ b/tests/test_pytest_mock.py
@@ -211,7 +211,7 @@ class TestMockerStub:
def test_repr_with_name(self, mocker: MockerFixture) -> None:
test_name = "funny walk"
stub = mocker.stub(name=test_name)
- assert "name={!r}".format(test_name) in repr(stub)
+ assert f"name={test_name!r}" in repr(stub)
def __test_failure_message(self, mocker: MockerFixture, **kwargs: Any) -> None:
expected_name = kwargs.get("name") or "mock"
@@ -267,19 +267,19 @@ def test_instance_method_spy_exception(
) -> None:
class Foo:
def bar(self, arg):
- raise exc_cls("Error with {}".format(arg))
+ raise exc_cls(f"Error with {arg}")
foo = Foo()
spy = mocker.spy(foo, "bar")
expected_calls = []
for i, v in enumerate([10, 20]):
- with pytest.raises(exc_cls, match="Error with {}".format(v)):
+ with pytest.raises(exc_cls, match=f"Error with {v}"):
foo.bar(arg=v)
expected_calls.append(mocker.call(arg=v))
assert foo.bar.call_args_list == expected_calls # type:ignore[attr-defined]
- assert str(spy.spy_exception) == "Error with {}".format(v)
+ assert str(spy.spy_exception) == f"Error with {v}"
def test_instance_method_spy_autospec_true(mocker: MockerFixture) -> None:
@@ -296,7 +296,7 @@ def test_instance_method_spy_autospec_true(mocker: MockerFixture) -> None:
def test_spy_reset(mocker: MockerFixture) -> None:
- class Foo(object):
+ class Foo:
def bar(self, x):
if x == 0:
raise ValueError("invalid x")
@@ -475,7 +475,6 @@ def test_callable_like_spy(testdir: Any, mocker: MockerFixture) -> None:
assert spy.spy_return == 20
[email protected]
async def test_instance_async_method_spy(mocker: MockerFixture) -> None:
class Foo:
async def bar(self, arg):
@@ -728,6 +727,12 @@ def test_standalone_mock(testdir: Any) -> None:
@pytest.mark.usefixtures("needs_assert_rewrite")
def test_detailed_introspection(testdir: Any) -> None:
"""Check that the "mock_use_standalone" is being used."""
+ testdir.makeini(
+ """
+ [pytest]
+ asyncio_mode=auto
+ """
+ )
testdir.makepyfile(
"""
def test(mocker):
@@ -769,11 +774,16 @@ def test_detailed_introspection(testdir: Any) -> None:
@pytest.mark.usefixtures("needs_assert_rewrite")
def test_detailed_introspection_async(testdir: Any) -> None:
"""Check that the "mock_use_standalone" is being used."""
+ testdir.makeini(
+ """
+ [pytest]
+ asyncio_mode=auto
+ """
+ )
testdir.makepyfile(
"""
import pytest
- @pytest.mark.asyncio
async def test(mocker):
m = mocker.AsyncMock()
await m('fo')
@@ -824,6 +834,12 @@ def test_assert_called_with_unicode_arguments(mocker: MockerFixture) -> None:
def test_plain_stopall(testdir: Any) -> None:
"""patch.stopall() in a test should not cause an error during unconfigure (#137)"""
+ testdir.makeini(
+ """
+ [pytest]
+ asyncio_mode=auto
+ """
+ )
testdir.makepyfile(
"""
import random
@@ -958,6 +974,12 @@ def test_abort_patch_context_manager_with_stale_pyc(testdir: Any) -> None:
def test_used_with_class_scope(testdir: Any) -> None:
+ testdir.makeini(
+ """
+ [pytest]
+ asyncio_mode=auto
+ """
+ )
testdir.makepyfile(
"""
import pytest
@@ -982,6 +1004,12 @@ def test_used_with_class_scope(testdir: Any) -> None:
def test_used_with_module_scope(testdir: Any) -> None:
+ testdir.makeini(
+ """
+ [pytest]
+ asyncio_mode=auto
+ """
+ )
testdir.makepyfile(
"""
import pytest
@@ -1004,7 +1032,12 @@ def test_used_with_module_scope(testdir: Any) -> None:
def test_used_with_package_scope(testdir: Any) -> None:
- """..."""
+ testdir.makeini(
+ """
+ [pytest]
+ asyncio_mode=auto
+ """
+ )
testdir.makepyfile(
"""
import pytest
@@ -1027,7 +1060,12 @@ def test_used_with_package_scope(testdir: Any) -> None:
def test_used_with_session_scope(testdir: Any) -> None:
- """..."""
+ testdir.makeini(
+ """
+ [pytest]
+ asyncio_mode=auto
+ """
+ )
testdir.makepyfile(
"""
import pytest
|
Tests fail with pytest-asyncio 0.17 due to asyncio-mode legacy warning
pytest-asyncio introduced a new mode parameter and warns if it is set to legacy:
```
[ 5s] =================================== FAILURES ===================================
[ 5s] ______________________________ test_plain_stopall ______________________________
[ 5s]
[ 5s] testdir = <Testdir local('/tmp/pytest-of-abuild/pytest-77/test_plain_stopall0')>
[ 5s]
[ 5s] def test_plain_stopall(testdir: Any) -> None:
[ 5s] """patch.stopall() in a test should not cause an error during unconfigure (#137)"""
[ 5s] testdir.makepyfile(
[ 5s] """
[ 5s] import random
[ 5s]
[ 5s] def get_random_number():
[ 5s] return random.randint(0, 100)
[ 5s]
[ 5s] def test_get_random_number(mocker):
[ 5s] patcher = mocker.mock_module.patch("random.randint", lambda x, y: 5)
[ 5s] patcher.start()
[ 5s] assert get_random_number() == 5
[ 5s] mocker.mock_module.patch.stopall()
[ 5s] """
[ 5s] )
[ 5s] result = testdir.runpytest_subprocess()
[ 5s] > result.stdout.fnmatch_lines("* 1 passed in *")
[ 5s] E Failed: nomatch: '* 1 passed in *'
[ 5s] E and: '============================= test session starts =============================='
[ 5s] E and: 'platform linux -- Python 3.9.9, pytest-6.2.5, py-1.10.0, pluggy-1.0.0'
[ 5s] E and: 'rootdir: /tmp/pytest-of-abuild/pytest-77/test_plain_stopall0'
[ 5s] E and: 'plugins: mock-3.6.1, asyncio-0.17.2'
[ 5s] E and: 'asyncio: mode=legacy'
[ 5s] E and: 'collected 1 item'
[ 5s] E and: ''
[ 5s] E and: 'test_plain_stopall.py . [100%]'
[ 5s] E and: ''
[ 5s] E and: '=============================== warnings summary ==============================='
[ 5s] E and: '../../../../usr/lib/python3.9/site-packages/pytest_asyncio/plugin.py:191'
[ 5s] E and: " /usr/lib/python3.9/site-packages/pytest_asyncio/plugin.py:191: DeprecationWarning: The 'asyncio_mode' default value will change to 'strict' in future, please explicitly use 'asyncio_mode=strict' or 'asyncio_mode=auto' in pytest configuration file."
[ 5s] E and: ' config.issue_config_time_warning(LEGACY_MODE, stacklevel=2)'
[ 5s] E and: ''
[ 5s] E and: 'test_plain_stopall.py::test_get_random_number'
[ 5s] E and: " /usr/lib/python3.9/site-packages/pytest_asyncio/plugin.py:317: DeprecationWarning: '@pytest.fixture' is applied to <fixture _mocker, file=/home/abuild/rpmbuild/BUILDROOT/python-pytest-mock-3.6.1-0.x86_64/usr/lib/python3.9/site-packages/pytest_mock/plugin.py, line=388> in 'legacy' mode, please replace it with '@pytest_asyncio.fixture' as a preparation for switching to 'strict' mode (or use 'auto' mode to seamlessly handle all these fixtures as asyncio-driven)."
[ 5s] E and: ' warnings.warn('
[ 5s] E and: ''
[ 5s] E and: '-- Docs: https://docs.pytest.org/en/stable/warnings.html'
[ 5s] E and: '======================== 1 passed, 2 warnings in 0.01s ========================='
[ 5s] E remains unmatched: '* 1 passed in *'
[ 5s]
[ 5s] /home/abuild/rpmbuild/BUILD/pytest-mock-3.6.1/tests/test_pytest_mock.py:842: Failed
[ 5s] ----------------------------- Captured stdout call -----------------------------
[ 5s] running: /usr/bin/python3.9 -mpytest --basetemp=/tmp/pytest-of-abuild/pytest-77/test_plain_stopall0/runpytest-0
[ 5s] in: /tmp/pytest-of-abuild/pytest-77/test_plain_stopall0
[ 5s] ============================= test session starts ==============================
[ 5s] platform linux -- Python 3.9.9, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
[ 5s] rootdir: /tmp/pytest-of-abuild/pytest-77/test_plain_stopall0
[ 5s] plugins: mock-3.6.1, asyncio-0.17.2
[ 5s] asyncio: mode=legacy
[ 5s] collected 1 item
[ 5s]
[ 5s] test_plain_stopall.py . [100%]
[ 5s]
[ 5s] =============================== warnings summary ===============================
[ 5s] ../../../../usr/lib/python3.9/site-packages/pytest_asyncio/plugin.py:191
[ 5s] /usr/lib/python3.9/site-packages/pytest_asyncio/plugin.py:191: DeprecationWarning: The 'asyncio_mode' default value will change to 'strict' in future, please explicitly use 'asyncio_mode=strict' or 'asyncio_mode=auto' in pytest configuration file.
[ 5s] config.issue_config_time_warning(LEGACY_MODE, stacklevel=2)
[ 5s]
[ 5s] test_plain_stopall.py::test_get_random_number
[ 5s] /usr/lib/python3.9/site-packages/pytest_asyncio/plugin.py:317: DeprecationWarning: '@pytest.fixture' is applied to <fixture _mocker, file=/home/abuild/rpmbuild/BUILDROOT/python-pytest-mock-3.6.1-0.x86_64/usr/lib/python3.9/site-packages/pytest_mock/plugin.py, line=388> in 'legacy' mode, please replace it with '@pytest_asyncio.fixture' as a preparation for switching to 'strict' mode (or use 'auto' mode to seamlessly handle all these fixtures as asyncio-driven).
[ 5s] warnings.warn(
[ 5s]
[ 5s] -- Docs: https://docs.pytest.org/en/stable/warnings.html
[ 5s] ======================== 1 passed, 2 warnings in 0.01s =========================
...
[ 5s] =========================== short test summary info ============================
[ 5s] SKIPPED [4] tests/test_pytest_mock.py:38: this test needs assertion rewrite to work but current option is "plain"
[ 5s] FAILED tests/test_pytest_mock.py::test_plain_stopall - Failed: nomatch: '* 1 ...
[ 5s] FAILED tests/test_pytest_mock.py::test_used_with_class_scope - Failed: nomatc...
[ 5s] FAILED tests/test_pytest_mock.py::test_used_with_module_scope - Failed: nomat...
[ 5s] FAILED tests/test_pytest_mock.py::test_used_with_package_scope - Failed: noma...
[ 5s] FAILED tests/test_pytest_mock.py::test_used_with_session_scope - Failed: noma...
[ 5s] =================== 5 failed, 63 passed, 4 skipped in 2.07s ====================
```
These tests expect a testdir.pytest_subprocess run without warnings.
The easiest way is to patch the matching assertion
```diff
- result.stdout.fnmatch_lines("* 1 passed in *")
+ result.stdout.fnmatch_lines("* 1 passed")
```
but I think it would be better to provide an explicit asyncio mode configuration to the testdir/pytester fixture.
|
0.0
|
3ca933aa93bf72877063e82c7f549879c6f34ddb
|
[
"tests/test_pytest_mock.py::test_instance_async_method_spy"
] |
[
"tests/test_pytest_mock.py::test_mock_patches[mock_using_patch_object]",
"tests/test_pytest_mock.py::test_mock_patches[mock_using_patch]",
"tests/test_pytest_mock.py::test_mock_patches[mock_using_patch_multiple]",
"tests/test_pytest_mock.py::test_mock_patch_dict",
"tests/test_pytest_mock.py::test_mock_patch_dict_resetall",
"tests/test_pytest_mock.py::test_mocker_aliases[ANY]",
"tests/test_pytest_mock.py::test_mocker_aliases[call]",
"tests/test_pytest_mock.py::test_mocker_aliases[create_autospec]",
"tests/test_pytest_mock.py::test_mocker_aliases[MagicMock]",
"tests/test_pytest_mock.py::test_mocker_aliases[Mock]",
"tests/test_pytest_mock.py::test_mocker_aliases[mock_open]",
"tests/test_pytest_mock.py::test_mocker_aliases[NonCallableMock]",
"tests/test_pytest_mock.py::test_mocker_aliases[PropertyMock]",
"tests/test_pytest_mock.py::test_mocker_aliases[sentinel]",
"tests/test_pytest_mock.py::test_mocker_aliases[seal]",
"tests/test_pytest_mock.py::test_mocker_resetall",
"tests/test_pytest_mock.py::TestMockerStub::test_call",
"tests/test_pytest_mock.py::TestMockerStub::test_repr_with_no_name",
"tests/test_pytest_mock.py::TestMockerStub::test_repr_with_name",
"tests/test_pytest_mock.py::TestMockerStub::test_failure_message_with_no_name",
"tests/test_pytest_mock.py::TestMockerStub::test_failure_message_with_name[None]",
"tests/test_pytest_mock.py::TestMockerStub::test_failure_message_with_name[]",
"tests/test_pytest_mock.py::TestMockerStub::test_failure_message_with_name[f]",
"tests/test_pytest_mock.py::TestMockerStub::test_failure_message_with_name[The",
"tests/test_pytest_mock.py::test_instance_method_spy",
"tests/test_pytest_mock.py::test_instance_method_spy_exception[BaseException]",
"tests/test_pytest_mock.py::test_instance_method_spy_exception[Exception]",
"tests/test_pytest_mock.py::test_instance_method_spy_exception[GeneratorExit]",
"tests/test_pytest_mock.py::test_instance_method_spy_exception[KeyboardInterrupt]",
"tests/test_pytest_mock.py::test_instance_method_spy_exception[RuntimeError]",
"tests/test_pytest_mock.py::test_instance_method_spy_exception[SystemExit]",
"tests/test_pytest_mock.py::test_instance_method_spy_autospec_true",
"tests/test_pytest_mock.py::test_spy_reset",
"tests/test_pytest_mock.py::test_instance_method_by_class_spy",
"tests/test_pytest_mock.py::test_instance_method_by_subclass_spy",
"tests/test_pytest_mock.py::test_class_method_spy",
"tests/test_pytest_mock.py::test_class_method_spy_autospec_false",
"tests/test_pytest_mock.py::test_class_method_subclass_spy",
"tests/test_pytest_mock.py::test_class_method_with_metaclass_spy",
"tests/test_pytest_mock.py::test_static_method_spy",
"tests/test_pytest_mock.py::test_static_method_subclass_spy",
"tests/test_pytest_mock.py::test_callable_like_spy",
"tests/test_pytest_mock.py::test_assert_not_called_wrapper",
"tests/test_pytest_mock.py::test_assert_called_with_wrapper",
"tests/test_pytest_mock.py::test_assert_called_once_with_wrapper",
"tests/test_pytest_mock.py::test_assert_called_once_wrapper",
"tests/test_pytest_mock.py::test_assert_called_wrapper",
"tests/test_pytest_mock.py::test_assert_any_call_wrapper",
"tests/test_pytest_mock.py::test_assert_has_calls",
"tests/test_pytest_mock.py::test_parse_ini_boolean",
"tests/test_pytest_mock.py::test_patched_method_parameter_name",
"tests/test_pytest_mock.py::test_monkeypatch_native",
"tests/test_pytest_mock.py::test_monkeypatch_no_terminal",
"tests/test_pytest_mock.py::test_standalone_mock",
"tests/test_pytest_mock.py::test_missing_introspection",
"tests/test_pytest_mock.py::test_assert_called_with_unicode_arguments",
"tests/test_pytest_mock.py::test_plain_stopall",
"tests/test_pytest_mock.py::test_warn_patch_object_context_manager",
"tests/test_pytest_mock.py::test_warn_patch_context_manager",
"tests/test_pytest_mock.py::test_context_manager_patch_example",
"tests/test_pytest_mock.py::test_abort_patch_context_manager_with_stale_pyc",
"tests/test_pytest_mock.py::test_used_with_class_scope",
"tests/test_pytest_mock.py::test_used_with_module_scope",
"tests/test_pytest_mock.py::test_used_with_package_scope",
"tests/test_pytest_mock.py::test_used_with_session_scope"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-01-25 11:34:22+00:00
|
mit
| 5,036 |
|
pytest-dev__pytest-xdist-651
|
diff --git a/changelog/650.feature.rst b/changelog/650.feature.rst
new file mode 100644
index 0000000..ce6dc39
--- /dev/null
+++ b/changelog/650.feature.rst
@@ -0,0 +1,1 @@
+Added new ``pytest_handlecrashitem`` hook to allow handling and rescheduling crashed items.
diff --git a/src/xdist/dsession.py b/src/xdist/dsession.py
index ab927fa..ccd5e20 100644
--- a/src/xdist/dsession.py
+++ b/src/xdist/dsession.py
@@ -343,6 +343,12 @@ class DSession:
nodeid, (fspath, None, fspath), (), "failed", msg, "???"
)
rep.node = worker
+
+ self.config.hook.pytest_handlecrashitem(
+ crashitem=nodeid,
+ report=rep,
+ sched=self.sched,
+ )
self.config.hook.pytest_runtest_logreport(report=rep)
diff --git a/src/xdist/newhooks.py b/src/xdist/newhooks.py
index da0f22a..a6443f3 100644
--- a/src/xdist/newhooks.py
+++ b/src/xdist/newhooks.py
@@ -64,3 +64,20 @@ def pytest_xdist_auto_num_workers(config):
.. versionadded:: 2.1
"""
+
+
[email protected]
+def pytest_handlecrashitem(crashitem, report, sched):
+ """
+ Handle a crashitem, modifying the report if necessary.
+
+ The scheduler is provided as a parameter to reschedule the test if desired with
+ `sched.mark_test_pending`.
+
+ def pytest_handlecrashitem(crashitem, report, sched):
+ if should_rerun(crashitem):
+ sched.mark_test_pending(crashitem)
+ report.outcome = "rerun"
+
+ .. versionadded:: 2.2.1
+ """
diff --git a/src/xdist/scheduler/each.py b/src/xdist/scheduler/each.py
index b2a0442..cfe99e7 100644
--- a/src/xdist/scheduler/each.py
+++ b/src/xdist/scheduler/each.py
@@ -101,6 +101,14 @@ class EachScheduling:
def mark_test_complete(self, node, item_index, duration=0):
self.node2pending[node].remove(item_index)
+ def mark_test_pending(self, item):
+ self.pending.insert(
+ 0,
+ self.collection.index(item),
+ )
+ for node in self.node2pending:
+ self.check_schedule(node)
+
def remove_node(self, node):
# KeyError if we didn't get an add_node() yet
pending = self.node2pending.pop(node)
diff --git a/src/xdist/scheduler/load.py b/src/xdist/scheduler/load.py
index e378d9a..f32caa5 100644
--- a/src/xdist/scheduler/load.py
+++ b/src/xdist/scheduler/load.py
@@ -151,6 +151,14 @@ class LoadScheduling:
self.node2pending[node].remove(item_index)
self.check_schedule(node, duration=duration)
+ def mark_test_pending(self, item):
+ self.pending.insert(
+ 0,
+ self.collection.index(item),
+ )
+ for node in self.node2pending:
+ self.check_schedule(node)
+
def check_schedule(self, node, duration=0):
"""Maybe schedule new items on the node
diff --git a/src/xdist/scheduler/loadscope.py b/src/xdist/scheduler/loadscope.py
index 31dbe26..c25e476 100644
--- a/src/xdist/scheduler/loadscope.py
+++ b/src/xdist/scheduler/loadscope.py
@@ -243,6 +243,9 @@ class LoadScopeScheduling:
self.assigned_work[node][scope][nodeid] = True
self._reschedule(node)
+ def mark_test_pending(self, item):
+ raise NotImplementedError()
+
def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
|
pytest-dev/pytest-xdist
|
f5665436e9c25fd17de2f86b53a3f100bf5813e7
|
diff --git a/testing/test_newhooks.py b/testing/test_newhooks.py
index 0318442..d2c2878 100644
--- a/testing/test_newhooks.py
+++ b/testing/test_newhooks.py
@@ -60,3 +60,37 @@ class TestHooks:
["*HOOK: gw0 test_a, test_b, test_c", "*HOOK: gw1 test_a, test_b, test_c"]
)
res.stdout.fnmatch_lines(["*3 passed*"])
+
+
+class TestCrashItem:
+ @pytest.fixture(autouse=True)
+ def create_test_file(self, testdir):
+ testdir.makepyfile(
+ """
+ import os
+ def test_a(): pass
+ def test_b(): os._exit(1)
+ def test_c(): pass
+ def test_d(): pass
+ """
+ )
+
+ def test_handlecrashitem(self, testdir):
+ """Test pytest_handlecrashitem hook."""
+ testdir.makeconftest(
+ """
+ test_runs = 0
+
+ def pytest_handlecrashitem(crashitem, report, sched):
+ global test_runs
+
+ if test_runs == 0:
+ sched.mark_test_pending(crashitem)
+ test_runs = 1
+ else:
+ print("HOOK: pytest_handlecrashitem")
+ """
+ )
+ res = testdir.runpytest("-n2", "-s")
+ res.stdout.fnmatch_lines_random(["*HOOK: pytest_handlecrashitem"])
+ res.stdout.fnmatch_lines(["*3 passed*"])
|
pytest-rerunfailures for crashed nodes
There's a hook for crashed nodes, but it doesn't let you clean-up the test failure. I'm looking for a way to contain a crashed test and rerun it.
|
0.0
|
f5665436e9c25fd17de2f86b53a3f100bf5813e7
|
[
"testing/test_newhooks.py::TestCrashItem::test_handlecrashitem"
] |
[
"testing/test_newhooks.py::TestHooks::test_runtest_logreport",
"testing/test_newhooks.py::TestHooks::test_node_collection_finished"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-17 23:52:52+00:00
|
mit
| 5,037 |
|
pytest-dev__pytest-xdist-667
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 21418d0..19f2f10 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/psf/black
- rev: 21.5b2
+ rev: 21.6b0
hooks:
- id: black
args: [--safe, --quiet, --target-version, py35]
@@ -17,7 +17,7 @@ repos:
hooks:
- id: flake8
- repo: https://github.com/asottile/pyupgrade
- rev: v2.19.0
+ rev: v2.19.4
hooks:
- id: pyupgrade
args: [--py3-plus]
diff --git a/changelog/421.bugfix.rst b/changelog/421.bugfix.rst
new file mode 100644
index 0000000..121c69c
--- /dev/null
+++ b/changelog/421.bugfix.rst
@@ -0,0 +1,1 @@
+Copy the parent process sys.path into local workers, to work around execnet's python -c adding the current directory to sys.path.
diff --git a/changelog/646.feature.rst b/changelog/646.feature.rst
new file mode 100644
index 0000000..210c73e
--- /dev/null
+++ b/changelog/646.feature.rst
@@ -0,0 +1,3 @@
+Add ``--numprocesses=logical`` flag, which automatically uses the number of logical CPUs available, instead of physical CPUs with ``auto``.
+
+This is very useful for test suites which are not CPU-bound.
diff --git a/src/xdist/plugin.py b/src/xdist/plugin.py
index 1eba32b..12b3a0e 100644
--- a/src/xdist/plugin.py
+++ b/src/xdist/plugin.py
@@ -1,17 +1,21 @@
import os
import uuid
+import sys
import py
import pytest
+_sys_path = list(sys.path) # freeze a copy of sys.path at interpreter startup
-def pytest_xdist_auto_num_workers():
+
+def pytest_xdist_auto_num_workers(config):
try:
import psutil
except ImportError:
pass
else:
- count = psutil.cpu_count(logical=False) or psutil.cpu_count()
+ use_logical = config.option.numprocesses == "logical"
+ count = psutil.cpu_count(logical=use_logical) or psutil.cpu_count()
if count:
return count
try:
@@ -36,8 +40,8 @@ def pytest_xdist_auto_num_workers():
def parse_numprocesses(s):
- if s == "auto":
- return "auto"
+ if s in ("auto", "logical"):
+ return s
elif s is not None:
return int(s)
@@ -51,9 +55,10 @@ def pytest_addoption(parser):
metavar="numprocesses",
action="store",
type=parse_numprocesses,
- help="shortcut for '--dist=load --tx=NUM*popen', "
- "you can use 'auto' here for auto detection CPUs number on "
- "host system and it will be 0 when used with --pdb",
+ help="Shortcut for '--dist=load --tx=NUM*popen'. With 'auto', attempt "
+ "to detect physical CPU count. With 'logical', detect logical CPU "
+ "count. If physical CPU count cannot be found, falls back to logical "
+ "count. This will be 0 when used with --pdb.",
)
group.addoption(
"--maxprocesses",
@@ -190,7 +195,7 @@ def pytest_configure(config):
@pytest.mark.tryfirst
def pytest_cmdline_main(config):
usepdb = config.getoption("usepdb", False) # a core option
- if config.option.numprocesses == "auto":
+ if config.option.numprocesses in ("auto", "logical"):
if usepdb:
config.option.numprocesses = 0
config.option.dist = "no"
diff --git a/src/xdist/remote.py b/src/xdist/remote.py
index 7f95b5c..d79f0b3 100644
--- a/src/xdist/remote.py
+++ b/src/xdist/remote.py
@@ -219,12 +219,14 @@ if __name__ == "__channelexec__":
channel = channel # noqa
workerinput, args, option_dict, change_sys_path = channel.receive()
- if change_sys_path:
+ if change_sys_path is None:
importpath = os.getcwd()
sys.path.insert(0, importpath)
os.environ["PYTHONPATH"] = (
importpath + os.pathsep + os.environ.get("PYTHONPATH", "")
)
+ else:
+ sys.path = change_sys_path
os.environ["PYTEST_XDIST_TESTRUNUID"] = workerinput["testrunuid"]
os.environ["PYTEST_XDIST_WORKER"] = workerinput["workerid"]
diff --git a/src/xdist/workermanage.py b/src/xdist/workermanage.py
index 8fed077..2c4f1a6 100644
--- a/src/xdist/workermanage.py
+++ b/src/xdist/workermanage.py
@@ -9,6 +9,7 @@ import pytest
import execnet
import xdist.remote
+from xdist.plugin import _sys_path
def parse_spec_config(config):
@@ -261,7 +262,8 @@ class WorkerController:
remote_module = self.config.hook.pytest_xdist_getremotemodule()
self.channel = self.gateway.remote_exec(remote_module)
# change sys.path only for remote workers
- change_sys_path = not self.gateway.spec.popen
+ # restore sys.path from a frozen copy for local workers
+ change_sys_path = _sys_path if self.gateway.spec.popen else None
self.channel.send((self.workerinput, args, option_dict, change_sys_path))
if self.putevent:
|
pytest-dev/pytest-xdist
|
7f2426b11d2c7890e5637fdaa3aa1c75b4f31758
|
diff --git a/testing/test_plugin.py b/testing/test_plugin.py
index c1aac65..5870676 100644
--- a/testing/test_plugin.py
+++ b/testing/test_plugin.py
@@ -69,6 +69,12 @@ def test_auto_detect_cpus(testdir, monkeypatch):
assert config.getoption("numprocesses") == 0
assert config.getoption("dist") == "no"
+ config = testdir.parseconfigure("-nlogical", "--pdb")
+ check_options(config)
+ assert config.getoption("usepdb")
+ assert config.getoption("numprocesses") == 0
+ assert config.getoption("dist") == "no"
+
monkeypatch.delattr(os, "sched_getaffinity", raising=False)
monkeypatch.setenv("TRAVIS", "true")
config = testdir.parseconfigure("-nauto")
@@ -81,12 +87,16 @@ def test_auto_detect_cpus_psutil(testdir, monkeypatch):
psutil = pytest.importorskip("psutil")
- monkeypatch.setattr(psutil, "cpu_count", lambda logical=True: 42)
+ monkeypatch.setattr(psutil, "cpu_count", lambda logical=True: 84 if logical else 42)
config = testdir.parseconfigure("-nauto")
check_options(config)
assert config.getoption("numprocesses") == 42
+ config = testdir.parseconfigure("-nlogical")
+ check_options(config)
+ assert config.getoption("numprocesses") == 84
+
def test_hook_auto_num_workers(testdir, monkeypatch):
from xdist.plugin import pytest_cmdline_main as check_options
@@ -101,6 +111,10 @@ def test_hook_auto_num_workers(testdir, monkeypatch):
check_options(config)
assert config.getoption("numprocesses") == 42
+ config = testdir.parseconfigure("-nlogical")
+ check_options(config)
+ assert config.getoption("numprocesses") == 42
+
def test_boxed_with_collect_only(testdir):
from xdist.plugin import pytest_cmdline_main as check_options
diff --git a/testing/test_remote.py b/testing/test_remote.py
index 2f6e222..31a6a2a 100644
--- a/testing/test_remote.py
+++ b/testing/test_remote.py
@@ -292,3 +292,17 @@ def test_remote_usage_prog(testdir, request):
result = testdir.runpytest_subprocess("-n1")
assert result.ret == 1
result.stdout.fnmatch_lines(["*usage: *", "*error: my_usage_error"])
+
+
+def test_remote_sys_path(testdir):
+ """Work around sys.path differences due to execnet using `python -c`."""
+ testdir.makepyfile(
+ """
+ import sys
+
+ def test_sys_path():
+ assert "" not in sys.path
+ """
+ )
+ result = testdir.runpytest("-n1")
+ assert result.ret == 0
|
xdist adds current directory to sys.path
With 1.26.1.
```python
import sys
def test_path():
assert "" not in sys.path
```
```
$ pytest test_path.py
<OK>
$ pytest test_path.py -n 1
E AssertionError....
```
Obviously this can cause problems/change behaviour depending on where you are running the tests from.
Possibly related to #376?
|
0.0
|
7f2426b11d2c7890e5637fdaa3aa1c75b4f31758
|
[
"testing/test_plugin.py::test_auto_detect_cpus",
"testing/test_plugin.py::test_hook_auto_num_workers",
"testing/test_remote.py::test_remote_sys_path"
] |
[
"testing/test_plugin.py::test_dist_incompatibility_messages",
"testing/test_plugin.py::test_dist_options",
"testing/test_plugin.py::test_boxed_with_collect_only",
"testing/test_plugin.py::test_dsession_with_collect_only",
"testing/test_plugin.py::test_testrunuid_provided",
"testing/test_plugin.py::test_testrunuid_generated",
"testing/test_plugin.py::TestDistOptions::test_getxspecs",
"testing/test_plugin.py::TestDistOptions::test_xspecs_multiplied",
"testing/test_plugin.py::TestDistOptions::test_getrsyncdirs",
"testing/test_plugin.py::TestDistOptions::test_getrsyncignore",
"testing/test_plugin.py::TestDistOptions::test_getrsyncdirs_with_conftest",
"testing/test_remote.py::TestWorkerInteractor::test_process_from_remote_error_handling",
"testing/test_remote.py::test_remote_env_vars",
"testing/test_remote.py::test_remote_inner_argv",
"testing/test_remote.py::test_remote_mainargv",
"testing/test_remote.py::test_remote_usage_prog"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-03 20:07:43+00:00
|
mit
| 5,038 |
|
pytest-dev__pytest-xdist-857
|
diff --git a/changelog/855.feature b/changelog/855.feature
new file mode 100644
index 0000000..9a04b48
--- /dev/null
+++ b/changelog/855.feature
@@ -0,0 +1,2 @@
+Users can now configure ``load`` scheduling precision using ``--maxschedchunk`` command
+line option.
diff --git a/src/xdist/plugin.py b/src/xdist/plugin.py
index 8c22f9b..9bbbae7 100644
--- a/src/xdist/plugin.py
+++ b/src/xdist/plugin.py
@@ -153,6 +153,19 @@ def pytest_addoption(parser):
"on every test run."
),
)
+ group.addoption(
+ "--maxschedchunk",
+ action="store",
+ type=int,
+ help=(
+ "Maximum number of tests scheduled in one step for --dist=load. "
+ "Setting it to 1 will force pytest to send tests to workers one by "
+ "one - might be useful for a small number of slow tests. "
+ "Larger numbers will allow the scheduler to submit consecutive "
+ "chunks of tests to workers - allows reusing fixtures. "
+ "Unlimited if not set."
+ ),
+ )
parser.addini(
"rsyncdirs",
diff --git a/src/xdist/scheduler/load.py b/src/xdist/scheduler/load.py
index 11d5309..ccca68b 100644
--- a/src/xdist/scheduler/load.py
+++ b/src/xdist/scheduler/load.py
@@ -64,6 +64,7 @@ class LoadScheduling:
else:
self.log = log.loadsched
self.config = config
+ self.maxschedchunk = self.config.getoption("maxschedchunk")
@property
def nodes(self):
@@ -185,7 +186,9 @@ class LoadScheduling:
# so let's rather wait with sending new items
return
num_send = items_per_node_max - len(node_pending)
- self._send_tests(node, num_send)
+ # keep at least 2 tests pending even if --maxschedchunk=1
+ maxschedchunk = max(2 - len(node_pending), self.maxschedchunk)
+ self._send_tests(node, min(num_send, maxschedchunk))
else:
node.shutdown()
@@ -245,6 +248,9 @@ class LoadScheduling:
if not self.collection:
return
+ if self.maxschedchunk is None:
+ self.maxschedchunk = len(self.collection)
+
# Send a batch of tests to run. If we don't have at least two
# tests per node, we have to send them all so that we can send
# shutdown signals and get all nodes working.
@@ -265,7 +271,8 @@ class LoadScheduling:
# how many items per node do we have about?
items_per_node = len(self.collection) // len(self.node2pending)
# take a fraction of tests for initial distribution
- node_chunksize = max(items_per_node // 4, 2)
+ node_chunksize = min(items_per_node // 4, self.maxschedchunk)
+ node_chunksize = max(node_chunksize, 2)
# and initialize each node with a chunk of tests
for node in self.nodes:
self._send_tests(node, node_chunksize)
|
pytest-dev/pytest-xdist
|
7faa69a04b2a0df20f977245830ef62f06a280c9
|
diff --git a/testing/test_dsession.py b/testing/test_dsession.py
index 86273b8..24ec4ae 100644
--- a/testing/test_dsession.py
+++ b/testing/test_dsession.py
@@ -129,6 +129,56 @@ class TestLoadScheduling:
assert node1.sent == [0, 1, 4, 5]
assert not sched.pending
+ def test_schedule_maxchunk_none(self, pytester: pytest.Pytester) -> None:
+ config = pytester.parseconfig("--tx=2*popen")
+ sched = LoadScheduling(config)
+ sched.add_node(MockNode())
+ sched.add_node(MockNode())
+ node1, node2 = sched.nodes
+ col = [f"test{i}" for i in range(16)]
+ sched.add_node_collection(node1, col)
+ sched.add_node_collection(node2, col)
+ sched.schedule()
+ assert node1.sent == [0, 1]
+ assert node2.sent == [2, 3]
+ assert sched.pending == list(range(4, 16))
+ assert sched.node2pending[node1] == node1.sent
+ assert sched.node2pending[node2] == node2.sent
+ sched.mark_test_complete(node1, 0)
+ assert node1.sent == [0, 1, 4, 5]
+ assert sched.pending == list(range(6, 16))
+ sched.mark_test_complete(node1, 1)
+ assert node1.sent == [0, 1, 4, 5]
+ assert sched.pending == list(range(6, 16))
+
+ for i in range(7, 16):
+ sched.mark_test_complete(node1, i - 3)
+ assert node1.sent == [0, 1] + list(range(4, i))
+ assert node2.sent == [2, 3]
+ assert sched.pending == list(range(i, 16))
+
+ def test_schedule_maxchunk_1(self, pytester: pytest.Pytester) -> None:
+ config = pytester.parseconfig("--tx=2*popen", "--maxschedchunk=1")
+ sched = LoadScheduling(config)
+ sched.add_node(MockNode())
+ sched.add_node(MockNode())
+ node1, node2 = sched.nodes
+ col = [f"test{i}" for i in range(16)]
+ sched.add_node_collection(node1, col)
+ sched.add_node_collection(node2, col)
+ sched.schedule()
+ assert node1.sent == [0, 1]
+ assert node2.sent == [2, 3]
+ assert sched.pending == list(range(4, 16))
+ assert sched.node2pending[node1] == node1.sent
+ assert sched.node2pending[node2] == node2.sent
+
+ for complete_index, first_pending in enumerate(range(5, 16)):
+ sched.mark_test_complete(node1, node1.sent[complete_index])
+ assert node1.sent == [0, 1] + list(range(4, first_pending))
+ assert node2.sent == [2, 3]
+ assert sched.pending == list(range(first_pending, 16))
+
def test_schedule_fewer_tests_than_nodes(self, pytester: pytest.Pytester) -> None:
config = pytester.parseconfig("--tx=2*popen")
sched = LoadScheduling(config)
|
New `LoadScheduling` batch distribution logic doesn't work for long-running tests
The PR https://github.com/pytest-dev/pytest-xdist/pull/812 that implemented new batch distribution logic (and that is now released in 3.0.2) disregards long-running tests.
I have several modules with long-running tests and many of these tests are now scheduled on single worker, instead of being distributed evenly across multiple workers. As a result, total runtime of my testsuite more than doubled from ~ 2.5 hours to 5+ hours.
Are there any workarounds to bring back the original round-robin scheduling?
cc @amezin
|
0.0
|
7faa69a04b2a0df20f977245830ef62f06a280c9
|
[
"testing/test_dsession.py::TestLoadScheduling::test_schedule_maxchunk_1"
] |
[
"testing/test_dsession.py::TestEachScheduling::test_schedule_load_simple",
"testing/test_dsession.py::TestEachScheduling::test_schedule_remove_node",
"testing/test_dsession.py::TestLoadScheduling::test_schedule_load_simple",
"testing/test_dsession.py::TestLoadScheduling::test_schedule_batch_size",
"testing/test_dsession.py::TestLoadScheduling::test_schedule_maxchunk_none",
"testing/test_dsession.py::TestLoadScheduling::test_schedule_fewer_tests_than_nodes",
"testing/test_dsession.py::TestLoadScheduling::test_schedule_fewer_than_two_tests_per_node",
"testing/test_dsession.py::TestLoadScheduling::test_add_remove_node",
"testing/test_dsession.py::TestLoadScheduling::test_different_tests_collected",
"testing/test_dsession.py::test_report_collection_diff_equal",
"testing/test_dsession.py::test_default_max_worker_restart",
"testing/test_dsession.py::test_report_collection_diff_different"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-20 01:40:28+00:00
|
mit
| 5,039 |
|
pythological__etuples-7
|
diff --git a/etuples/core.py b/etuples/core.py
index e7bf476..e275cf6 100644
--- a/etuples/core.py
+++ b/etuples/core.py
@@ -1,9 +1,8 @@
import inspect
import reprlib
-import toolz
-
-from collections.abc import Sequence
+from collections import deque
+from collections.abc import Sequence, Generator
etuple_repr = reprlib.Repr()
@@ -11,6 +10,41 @@ etuple_repr.maxstring = 100
etuple_repr.maxother = 100
+def trampoline_eval(z, res_filter=None):
+ """Evaluate a stream of generators.
+
+ This implementation consists of a deque that simulates an evaluation stack
+ of generator-produced operations. We're able to overcome `RecursionError`s
+ this way.
+ """
+
+ if not isinstance(z, Generator): # pragma: no cover
+ return z
+
+ stack = deque()
+ z_args, z_out = None, None
+ stack.append(z)
+
+ while stack:
+ z = stack[-1]
+ try:
+ z_out = z.send(z_args)
+
+ if res_filter: # pragma: no cover
+ _ = res_filter(z, z_out)
+
+ if isinstance(z_out, Generator):
+ stack.append(z_out)
+ z_args = None
+ else:
+ z_args = z_out
+
+ except StopIteration:
+ _ = stack.pop()
+
+ return z_out
+
+
class InvalidExpression(Exception):
"""An exception indicating that an `ExpressionTuple` is not a valid [S-]expression.
@@ -35,9 +69,13 @@ class KwdPair(object):
self.arg = arg
self.value = value
- @property
- def eval_obj(self):
- return KwdPair(self.arg, getattr(self.value, "eval_obj", self.value))
+ def _eval_step(self):
+ if isinstance(self.value, (ExpressionTuple, KwdPair)):
+ value = yield self.value._eval_step()
+ else:
+ value = self.value
+
+ yield KwdPair(self.arg, value)
def __repr__(self):
return f"{self.__class__.__name__}({repr(self.arg)}, {repr(self.value)})"
@@ -111,28 +149,36 @@ class ExpressionTuple(Sequence):
@property
def eval_obj(self):
- """Return the evaluation of this expression tuple.
+ """Return the evaluation of this expression tuple."""
+ return trampoline_eval(self._eval_step())
- Warning: If the evaluation value isn't cached, it will be evaluated
- recursively.
-
- """
+ def _eval_step(self):
if len(self._tuple) == 0:
- raise InvalidExpression()
+ raise InvalidExpression("Empty expression.")
if self._eval_obj is not self.null:
- return self._eval_obj
+ yield self._eval_obj
else:
op = self._tuple[0]
- op = getattr(op, "eval_obj", op)
+
+ if isinstance(op, (ExpressionTuple, KwdPair)):
+ op = yield op._eval_step()
if not callable(op):
- raise InvalidExpression()
+ raise InvalidExpression(
+ "ExpressionTuple does not have a callable operator."
+ )
- evaled_args = [getattr(i, "eval_obj", i) for i in self._tuple[1:]]
- arg_grps = toolz.groupby(lambda x: isinstance(x, KwdPair), evaled_args)
- evaled_args = arg_grps.get(False, [])
- evaled_kwargs = arg_grps.get(True, [])
+ evaled_args = []
+ evaled_kwargs = []
+ for i in self._tuple[1:]:
+ if isinstance(i, (ExpressionTuple, KwdPair)):
+ i = yield i._eval_step()
+
+ if isinstance(i, KwdPair):
+ evaled_kwargs.append(i)
+ else:
+ evaled_args.append(i)
try:
op_sig = inspect.signature(op)
@@ -150,7 +196,7 @@ class ExpressionTuple(Sequence):
# assert not isinstance(_eval_obj, ExpressionTuple)
self._eval_obj = _eval_obj
- return self._eval_obj
+ yield self._eval_obj
@eval_obj.setter
def eval_obj(self, obj):
@@ -221,9 +267,32 @@ class ExpressionTuple(Sequence):
p.pretty(item)
def __eq__(self, other):
- return self._tuple == other
+
+ # Built-in `==` won't work in CPython for deeply nested structures.
+
+ # TODO: We could track the level of `ExpressionTuple`-only nesting and
+ # apply TCO only when it reaches a certain level.
+
+ if not isinstance(other, Sequence):
+ return NotImplemented
+
+ if len(other) != len(self):
+ return False
+
+ queue = deque(zip(self._tuple, other))
+
+ while queue:
+ i_s, i_o = queue.pop()
+
+ if isinstance(i_s, ExpressionTuple) or isinstance(i_o, ExpressionTuple):
+ queue.extend(zip(i_s, i_o))
+ elif i_s != i_o:
+ return False
+
+ return True
def __hash__(self):
+ # XXX: CPython fails for deeply nested tuples!
return hash(self._tuple)
diff --git a/etuples/dispatch.py b/etuples/dispatch.py
index d8fa06e..b9bb262 100644
--- a/etuples/dispatch.py
+++ b/etuples/dispatch.py
@@ -4,7 +4,7 @@ from multipledispatch import dispatch
from cons.core import ConsError, ConsNull, ConsPair, car, cdr, cons
-from .core import etuple, ExpressionTuple
+from .core import etuple, ExpressionTuple, trampoline_eval
try:
from packaging import version
@@ -103,30 +103,46 @@ def etuplize(x, shallow=False, return_bad_args=False, convert_ConsPairs=True):
of raising an exception.
"""
- if isinstance(x, ExpressionTuple):
- return x
- elif convert_ConsPairs and x is not None and isinstance(x, (ConsNull, ConsPair)):
- return etuple(*x)
-
- try:
- op, args = rator(x), rands(x)
- except ConsError:
- op, args = None, None
-
- if not callable(op) or not isinstance(args, (ConsNull, ConsPair)):
- if return_bad_args:
- return x
+
+ def etuplize_step(
+ x,
+ shallow=shallow,
+ return_bad_args=return_bad_args,
+ convert_ConsPairs=convert_ConsPairs,
+ ):
+ if isinstance(x, ExpressionTuple):
+ yield x
+ return
+ elif (
+ convert_ConsPairs and x is not None and isinstance(x, (ConsNull, ConsPair))
+ ):
+ yield etuple(*x)
+ return
+
+ try:
+ op, args = rator(x), rands(x)
+ except ConsError:
+ op, args = None, None
+
+ if not callable(op) or not isinstance(args, (ConsNull, ConsPair)):
+ if return_bad_args:
+ yield x
+ return
+ else:
+ raise TypeError(f"x is neither a non-str Sequence nor term: {type(x)}")
+
+ if shallow:
+ et_op = op
+ et_args = args
else:
- raise TypeError(f"x is neither a non-str Sequence nor term: {type(x)}")
-
- if shallow:
- et_op = op
- et_args = args
- else:
- et_op = etuplize(op, return_bad_args=True)
- et_args = tuple(
- etuplize(a, return_bad_args=True, convert_ConsPairs=False) for a in args
- )
+ et_op = yield etuplize_step(op, return_bad_args=True)
+ et_args = []
+ for a in args:
+ e = yield etuplize_step(
+ a, return_bad_args=True, convert_ConsPairs=False
+ )
+ et_args.append(e)
+
+ yield etuple(et_op, *et_args, eval_obj=x)
- res = etuple(et_op, *et_args, eval_obj=x)
- return res
+ return trampoline_eval(etuplize_step(x))
diff --git a/setup.py b/setup.py
index 437f2da..3d0e3e0 100644
--- a/setup.py
+++ b/setup.py
@@ -13,7 +13,7 @@ setup(
maintainer="Brandon T. Willard",
maintainer_email="[email protected]",
packages=["etuples"],
- install_requires=["toolz", "cons", "multipledispatch",],
+ install_requires=["cons", "multipledispatch",],
long_description=open("README.md").read() if exists("README.md") else "",
long_description_content_type="text/markdown",
python_requires=">=3.6",
|
pythological/etuples
|
67093a4bb4f0326156ad379d5ef0f0337642ff3d
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 9e106b7..e1a2577 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,3 +1,5 @@
+import sys
+
import pytest
from operator import add
@@ -11,6 +13,12 @@ def test_ExpressionTuple(capsys):
assert hash(e0) == hash((add, 1, 2))
assert e0 == ExpressionTuple(e0)
+ e5 = ExpressionTuple((1, ExpressionTuple((2, 3))))
+ e6 = ExpressionTuple((1, ExpressionTuple((2, 3))))
+
+ assert e5 == e6
+ assert hash(e5) == hash(e6)
+
# Not sure if we really want this; it's more
# common to have a copy constructor, no?
assert e0 is ExpressionTuple(e0)
@@ -51,6 +59,10 @@ def test_ExpressionTuple(capsys):
with pytest.raises(InvalidExpression):
e4.eval_obj
+ assert ExpressionTuple((ExpressionTuple((lambda: add,)), 1, 1)).eval_obj == 2
+ assert ExpressionTuple((1, 2)) != ExpressionTuple((1,))
+ assert ExpressionTuple((1, 2)) != ExpressionTuple((1, 3))
+
def test_etuple():
"""Test basic `etuple` functionality."""
@@ -183,3 +195,48 @@ def test_pprint():
pretty_mod.pretty(et)
== "e(\n 1,\n e('a', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19),\n e(3, 'b'),\n blah=e(c, 0))"
)
+
+
+def gen_long_add_chain(N=None, num=1):
+ b_struct = num
+ if N is None:
+ N = sys.getrecursionlimit()
+ for i in range(0, N):
+ b_struct = etuple(add, num, b_struct)
+ return b_struct
+
+
+def test_reify_recursion_limit():
+
+ a = gen_long_add_chain(10)
+ assert a.eval_obj == 11
+
+ r_limit = sys.getrecursionlimit()
+
+ try:
+ sys.setrecursionlimit(100)
+
+ a = gen_long_add_chain(200)
+ assert a.eval_obj == 201
+
+ b = gen_long_add_chain(200, num=2)
+ assert b.eval_obj == 402
+
+ c = gen_long_add_chain(200)
+ assert a == c
+
+ finally:
+ sys.setrecursionlimit(r_limit)
+
+
[email protected](strict=True)
+def test_reify_recursion_limit_hash():
+ r_limit = sys.getrecursionlimit()
+
+ try:
+ sys.setrecursionlimit(100)
+ a = gen_long_add_chain(200)
+ # CPython uses the call stack and fails
+ assert hash(a)
+ finally:
+ sys.setrecursionlimit(r_limit)
|
Use trampolining for evaluation and etuplization
`ExpressionTuple.eval_obj` and `etuplize` are recursive and not scalable, so we should use some sort of TCO/trampolining (e.g. https://github.com/pythological/unification/pull/16).
|
0.0
|
67093a4bb4f0326156ad379d5ef0f0337642ff3d
|
[
"tests/test_core.py::test_reify_recursion_limit"
] |
[
"tests/test_core.py::test_ExpressionTuple",
"tests/test_core.py::test_etuple",
"tests/test_core.py::test_etuple_kwargs",
"tests/test_core.py::test_str",
"tests/test_core.py::test_pprint"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-21 18:06:49+00:00
|
apache-2.0
| 5,040 |
|
python-adaptive__adaptive-229
|
diff --git a/adaptive/runner.py b/adaptive/runner.py
index 71e3401..c0adebb 100644
--- a/adaptive/runner.py
+++ b/adaptive/runner.py
@@ -712,6 +712,46 @@ def replay_log(learner, log):
getattr(learner, method)(*args)
+# --- Useful runner goals
+
+
+def stop_after(*, seconds=0, minutes=0, hours=0):
+ """Stop a runner after a specified time.
+
+ For example, to specify a runner that should stop after
+ 5 minutes, one could do the following:
+
+ >>> runner = Runner(learner, goal=stop_after(minutes=5))
+
+ To stop a runner after 2 hours, 10 minutes and 3 seconds,
+ one could do the following:
+
+ >>> runner = Runner(learner, goal=stop_after(hours=2, minutes=10, seconds=3))
+
+ Parameters
+ ----------
+ seconds, minutes, hours : float, default: 0
+ If more than one is specified, then they are added together
+
+ Returns
+ -------
+ goal : callable
+ Can be used as the ``goal`` parameter when constructing
+ a `Runner`.
+
+ Notes
+ -----
+ The duration specified is only a *lower bound* on the time that the
+ runner will run for, because the runner only checks its goal when
+ it adds points to its learner
+ """
+ stop_time = time.time() + seconds + 60 * minutes + 3600 * hours
+ return lambda _: time.time() > stop_time
+
+
+# -- Internal executor-related, things
+
+
class SequentialExecutor(concurrent.Executor):
"""A trivial executor that runs functions synchronously.
diff --git a/docs/source/reference/adaptive.runner.extras.rst b/docs/source/reference/adaptive.runner.extras.rst
index 90786f4..5b1680e 100644
--- a/docs/source/reference/adaptive.runner.extras.rst
+++ b/docs/source/reference/adaptive.runner.extras.rst
@@ -1,6 +1,17 @@
Runner extras
=============
+Stopping Criteria
+-----------------
+
+Runners allow you to specify the stopping criterion by providing
+a ``goal`` as a function that takes the learner and returns a boolean: ``False``
+for "continue running" and ``True`` for "stop". This gives you a lot of flexibility
+for defining your own stopping conditions, however we also provide some common
+stopping conditions as a convenience.
+
+.. autofunction:: adaptive.runner.stop_after
+
Simple executor
---------------
|
python-adaptive/adaptive
|
59459cbc590916168c2afa5e352327602d14b870
|
diff --git a/adaptive/tests/test_runner.py b/adaptive/tests/test_runner.py
index 9ded38a..7bbc56b 100644
--- a/adaptive/tests/test_runner.py
+++ b/adaptive/tests/test_runner.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import asyncio
+import time
import pytest
@@ -10,6 +11,7 @@ from adaptive.runner import (
BlockingRunner,
SequentialExecutor,
simple,
+ stop_after,
with_distributed,
with_ipyparallel,
)
@@ -103,6 +105,14 @@ def test_concurrent_futures_executor():
)
+def test_stop_after_goal():
+ seconds_to_wait = 0.2 # don't make this too large or the test will take ages
+ start_time = time.time()
+ BlockingRunner(Learner1D(linear, (-1, 1)), stop_after(seconds=seconds_to_wait))
+ stop_time = time.time()
+ assert stop_time - start_time > seconds_to_wait
+
+
@pytest.mark.skipif(not with_ipyparallel, reason="IPyparallel is not installed")
def test_ipyparallel_executor(ipyparallel_executor):
learner = Learner1D(linear, (-1, 1))
|
Time-based stop
Hey guys,
Adaptive is great.
A feature request. I want to have the runner quit after a certain time. Say, something like
`
runner = adaptive.BlockingRunner(learner, goal=time_elapsed > 6 hours)
`
This is useful when you submit the runner itself as a job to a cluster with a finite time of execution. With runner.save and runner.load one can then stage, look at the data and decide whether it needs to submitted again. How can I do that?
|
0.0
|
59459cbc590916168c2afa5e352327602d14b870
|
[
"adaptive/tests/test_runner.py::test_simple[simple]",
"adaptive/tests/test_runner.py::test_simple[blocking_runner]",
"adaptive/tests/test_runner.py::test_simple[async_runner]",
"adaptive/tests/test_runner.py::test_aync_def_function",
"adaptive/tests/test_runner.py::test_concurrent_futures_executor",
"adaptive/tests/test_runner.py::test_stop_after_goal"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-21 11:59:01+00:00
|
bsd-3-clause
| 5,041 |
|
python-adaptive__adaptive-276
|
diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py
index ba7deb1..b571c19 100644
--- a/adaptive/learner/average_learner.py
+++ b/adaptive/learner/average_learner.py
@@ -118,9 +118,11 @@ class AverageLearner(BaseLearner):
if n < self.min_npoints:
return np.inf
standard_error = self.std / sqrt(n)
- return max(
- standard_error / self.atol, standard_error / abs(self.mean) / self.rtol
- )
+ aloss = standard_error / self.atol
+ rloss = standard_error / self.rtol
+ if self.mean != 0:
+ rloss /= abs(self.mean)
+ return max(aloss, rloss)
def _loss_improvement(self, n):
loss = self.loss()
|
python-adaptive/adaptive
|
4e34aba8cf52b22d642a85a5da15d41be8fa86a3
|
diff --git a/adaptive/tests/test_average_learner.py b/adaptive/tests/test_average_learner.py
index 42d4726..f35794a 100644
--- a/adaptive/tests/test_average_learner.py
+++ b/adaptive/tests/test_average_learner.py
@@ -59,3 +59,11 @@ def test_min_npoints():
)
simple(learner, lambda l: l.loss() < 1)
assert learner.npoints >= max(2, min_npoints)
+
+
+def test_zero_mean():
+ # see https://github.com/python-adaptive/adaptive/issues/275
+ learner = AverageLearner(None, rtol=0.01)
+ learner.tell(0, -1)
+ learner.tell(1, 1)
+ learner.loss()
|
AverageLearner doesn't work with 0 mean
```python
from adaptive import AverageLearner
l = AverageLearner(None, rtol=0.01)
l.tell(0, -1)
l.tell(1, 1)
l.ask(1)
```
raises
```
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-9-03494c6327ae> in <module>
4 l.tell(0, -1)
5 l.tell(1, 1)
----> 6 l.ask(1)
~/Work/adaptive/adaptive/learner/average_learner.py in ask(self, n, tell_pending)
67 )[:n]
68
---> 69 loss_improvements = [self._loss_improvement(n) / n] * n
70 if tell_pending:
71 for p in points:
~/Work/adaptive/adaptive/learner/average_learner.py in _loss_improvement(self, n)
119
120 def _loss_improvement(self, n):
--> 121 loss = self.loss()
122 if np.isfinite(loss):
123 return loss - self.loss(n=self.npoints + n)
~/Work/adaptive/adaptive/utils.py in wrapper(*args, **kwargs)
35 if not hasattr(self, "_cache"):
36 self._cache = {}
---> 37 self._cache[f.__name__] = f(*args, **kwargs)
38 return self._cache[f.__name__]
39
~/Work/adaptive/adaptive/learner/average_learner.py in loss(self, real, n)
115 standard_error = self.std / sqrt(n)
116 return max(
--> 117 standard_error / self.atol, standard_error / abs(self.mean) / self.rtol
118 )
119
ZeroDivisionError: float division by zero
```
@akhmerov, how do you think we should solve this?
|
0.0
|
4e34aba8cf52b22d642a85a5da15d41be8fa86a3
|
[
"adaptive/tests/test_average_learner.py::test_zero_mean"
] |
[
"adaptive/tests/test_average_learner.py::test_avg_std_and_npoints",
"adaptive/tests/test_average_learner.py::test_min_npoints",
"adaptive/tests/test_average_learner.py::test_only_returns_new_points"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-05-14 14:03:55+00:00
|
bsd-3-clause
| 5,042 |
|
python-babel__babel-1015
|
diff --git a/babel/messages/extract.py b/babel/messages/extract.py
index b6dce6f..4fc3da7 100644
--- a/babel/messages/extract.py
+++ b/babel/messages/extract.py
@@ -55,7 +55,8 @@ if TYPE_CHECKING:
def seek(self, __offset: int, __whence: int = ...) -> int: ...
def tell(self) -> int: ...
- _Keyword: TypeAlias = tuple[int | tuple[int, int] | tuple[int, str], ...] | None
+ _SimpleKeyword: TypeAlias = tuple[int | tuple[int, int] | tuple[int, str], ...] | None
+ _Keyword: TypeAlias = dict[int | None, _SimpleKeyword] | _SimpleKeyword
# 5-tuple of (filename, lineno, messages, comments, context)
_FileExtractionResult: TypeAlias = tuple[str, int, str | tuple[str, ...], list[str], str | None]
@@ -315,6 +316,47 @@ def extract_from_file(
options, strip_comment_tags))
+def _match_messages_against_spec(lineno: int, messages: list[str|None], comments: list[str],
+ fileobj: _FileObj, spec: tuple[int|tuple[int, str], ...]):
+ translatable = []
+ context = None
+
+ # last_index is 1 based like the keyword spec
+ last_index = len(messages)
+ for index in spec:
+ if isinstance(index, tuple): # (n, 'c')
+ context = messages[index[0] - 1]
+ continue
+ if last_index < index:
+ # Not enough arguments
+ return
+ message = messages[index - 1]
+ if message is None:
+ return
+ translatable.append(message)
+
+ # keyword spec indexes are 1 based, therefore '-1'
+ if isinstance(spec[0], tuple):
+ # context-aware *gettext method
+ first_msg_index = spec[1] - 1
+ else:
+ first_msg_index = spec[0] - 1
+ # An empty string msgid isn't valid, emit a warning
+ if not messages[first_msg_index]:
+ filename = (getattr(fileobj, "name", None) or "(unknown)")
+ sys.stderr.write(
+ f"{filename}:{lineno}: warning: Empty msgid. It is reserved by GNU gettext: gettext(\"\") "
+ f"returns the header entry with meta information, not the empty string.\n"
+ )
+ return
+
+ translatable = tuple(translatable)
+ if len(translatable) == 1:
+ translatable = translatable[0]
+
+ return lineno, translatable, comments, context
+
+
def extract(
method: _ExtractionMethod,
fileobj: _FileObj,
@@ -400,56 +442,30 @@ def extract(
options=options or {})
for lineno, funcname, messages, comments in results:
- spec = keywords[funcname] or (1,) if funcname else (1,)
if not isinstance(messages, (list, tuple)):
messages = [messages]
if not messages:
continue
- # Validate the messages against the keyword's specification
- context = None
- msgs = []
- invalid = False
- # last_index is 1 based like the keyword spec
- last_index = len(messages)
- for index in spec:
- if isinstance(index, tuple):
- context = messages[index[0] - 1]
- continue
- if last_index < index:
- # Not enough arguments
- invalid = True
- break
- message = messages[index - 1]
- if message is None:
- invalid = True
- break
- msgs.append(message)
- if invalid:
- continue
-
- # keyword spec indexes are 1 based, therefore '-1'
- if isinstance(spec[0], tuple):
- # context-aware *gettext method
- first_msg_index = spec[1] - 1
- else:
- first_msg_index = spec[0] - 1
- if not messages[first_msg_index]:
- # An empty string msgid isn't valid, emit a warning
- filename = (getattr(fileobj, "name", None) or "(unknown)")
- sys.stderr.write(
- f"{filename}:{lineno}: warning: Empty msgid. It is reserved by GNU gettext: gettext(\"\") "
- f"returns the header entry with meta information, not the empty string.\n"
- )
- continue
-
- messages = tuple(msgs)
- if len(messages) == 1:
- messages = messages[0]
+ specs = keywords[funcname] or None if funcname else None
+ # {None: x} may be collapsed into x for backwards compatibility.
+ if not isinstance(specs, dict):
+ specs = {None: specs}
if strip_comment_tags:
_strip_comment_tags(comments, comment_tags)
- yield lineno, messages, comments, context
+
+ # None matches all arities.
+ for arity in (None, len(messages)):
+ try:
+ spec = specs[arity]
+ except KeyError:
+ continue
+ if spec is None:
+ spec = (1,)
+ result = _match_messages_against_spec(lineno, messages, comments, fileobj, spec)
+ if result is not None:
+ yield result
def extract_nothing(
diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py
index 6ed1fe5..0008a9b 100644
--- a/babel/messages/frontend.py
+++ b/babel/messages/frontend.py
@@ -8,6 +8,8 @@
:license: BSD, see LICENSE for more details.
"""
+from __future__ import annotations
+
import datetime
import fnmatch
import logging
@@ -1111,34 +1113,63 @@ def parse_mapping(fileobj, filename=None):
return method_map, options_map
+def _parse_spec(s: str) -> tuple[int | None, tuple[int|tuple[int, str], ...]]:
+ inds = []
+ number = None
+ for x in s.split(','):
+ if x[-1] == 't':
+ number = int(x[:-1])
+ elif x[-1] == 'c':
+ inds.append((int(x[:-1]), 'c'))
+ else:
+ inds.append(int(x))
+ return number, tuple(inds)
def parse_keywords(strings: Iterable[str] = ()):
"""Parse keywords specifications from the given list of strings.
- >>> kw = sorted(parse_keywords(['_', 'dgettext:2', 'dngettext:2,3', 'pgettext:1c,2']).items())
- >>> for keyword, indices in kw:
- ... print((keyword, indices))
- ('_', None)
- ('dgettext', (2,))
- ('dngettext', (2, 3))
- ('pgettext', ((1, 'c'), 2))
+ >>> import pprint
+ >>> keywords = ['_', 'dgettext:2', 'dngettext:2,3', 'pgettext:1c,2',
+ ... 'polymorphic:1', 'polymorphic:2,2t', 'polymorphic:3c,3t']
+ >>> pprint.pprint(parse_keywords(keywords))
+ {'_': None,
+ 'dgettext': (2,),
+ 'dngettext': (2, 3),
+ 'pgettext': ((1, 'c'), 2),
+ 'polymorphic': {None: (1,), 2: (2,), 3: ((3, 'c'),)}}
+
+ The input keywords are in GNU Gettext style; see :doc:`cmdline` for details.
+
+ The output is a dictionary mapping keyword names to a dictionary of specifications.
+ Keys in this dictionary are numbers of arguments, where ``None`` means that all numbers
+ of arguments are matched, and a number means only calls with that number of arguments
+ are matched (which happens when using the "t" specifier). However, as a special
+ case for backwards compatibility, if the dictionary of specifications would
+ be ``{None: x}``, i.e., there is only one specification and it matches all argument
+ counts, then it is collapsed into just ``x``.
+
+ A specification is either a tuple or None. If a tuple, each element can be either a number
+ ``n``, meaning that the nth argument should be extracted as a message, or the tuple
+ ``(n, 'c')``, meaning that the nth argument should be extracted as context for the
+ messages. A ``None`` specification is equivalent to ``(1,)``, extracting the first
+ argument.
"""
keywords = {}
for string in strings:
if ':' in string:
- funcname, indices = string.split(':')
+ funcname, spec_str = string.split(':')
+ number, spec = _parse_spec(spec_str)
else:
- funcname, indices = string, None
- if funcname not in keywords:
- if indices:
- inds = []
- for x in indices.split(','):
- if x[-1] == 'c':
- inds.append((int(x[:-1]), 'c'))
- else:
- inds.append(int(x))
- indices = tuple(inds)
- keywords[funcname] = indices
+ funcname = string
+ number = None
+ spec = None
+ keywords.setdefault(funcname, {})[number] = spec
+
+ # For best backwards compatibility, collapse {None: x} into x.
+ for k, v in keywords.items():
+ if set(v) == {None}:
+ keywords[k] = v[None]
+
return keywords
diff --git a/docs/cmdline.rst b/docs/cmdline.rst
index 8d9742f..e1328fe 100644
--- a/docs/cmdline.rst
+++ b/docs/cmdline.rst
@@ -133,6 +133,45 @@ a collection of source files::
header comment for the catalog
+The meaning of ``--keyword`` values is as follows:
+
+- Pass a simple identifier like ``_`` to extract the first (and only the first)
+ argument of all function calls to ``_``,
+
+- To extract other arguments than the first, add a colon and the argument
+ indices separated by commas. For example, the ``dngettext`` function
+ typically expects translatable strings as second and third arguments,
+ so you could pass ``dngettext:2,3``.
+
+- Some arguments should not be interpreted as translatable strings, but
+ context strings. For that, append "c" to the argument index. For example:
+ ``pgettext:1c,2``.
+
+- In C++ and Python, you may have functions that behave differently
+ depending on how many arguments they take. For this use case, you can
+ add an integer followed by "t" after the colon. In this case, the
+ keyword will only match a function invocation if it has the specified
+ total number of arguments. For example, if you have a function
+ ``foo`` that behaves as ``gettext`` (argument is a message) or
+ ``pgettext`` (arguments are a context and a message) depending on
+ whether it takes one or two arguments, you can pass
+ ``--keyword=foo:1,1t --keyword=foo:1c,2,2t``.
+
+The default keywords are equivalent to passing ::
+
+ --keyword=_
+ --keyword=gettext
+ --keyword=ngettext:1,2
+ --keyword=ugettext
+ --keyword=ungettext:1,2
+ --keyword=dgettext:2
+ --keyword=dngettext:2,3
+ --keyword=N_
+ --keyword=pgettext:1c,2
+ --keyword=npgettext:1c,2,3
+
+
+
init
====
|
python-babel/babel
|
9ef53c6a6ab5fc604b58ccb19dc63ebcf8edd28b
|
diff --git a/tests/messages/test_frontend.py b/tests/messages/test_frontend.py
index 821738d..b28cb0d 100644
--- a/tests/messages/test_frontend.py
+++ b/tests/messages/test_frontend.py
@@ -17,7 +17,7 @@ import sys
import time
import unittest
from datetime import datetime, timedelta
-from io import StringIO
+from io import BytesIO, StringIO
import pytest
from freezegun import freeze_time
@@ -25,7 +25,7 @@ from setuptools import Distribution
from babel import __version__ as VERSION
from babel.dates import format_datetime
-from babel.messages import Catalog, frontend
+from babel.messages import Catalog, extract, frontend
from babel.messages.frontend import (
BaseError,
CommandLineInterface,
@@ -1422,6 +1422,35 @@ def test_parse_keywords():
}
+def test_parse_keywords_with_t():
+ kw = frontend.parse_keywords(['_:1', '_:2,2t', '_:2c,3,3t'])
+
+ assert kw == {
+ '_': {
+ None: (1,),
+ 2: (2,),
+ 3: ((2, 'c'), 3),
+ }
+ }
+
+def test_extract_messages_with_t():
+ content = rb"""
+_("1 arg, arg 1")
+_("2 args, arg 1", "2 args, arg 2")
+_("3 args, arg 1", "3 args, arg 2", "3 args, arg 3")
+_("4 args, arg 1", "4 args, arg 2", "4 args, arg 3", "4 args, arg 4")
+"""
+ kw = frontend.parse_keywords(['_:1', '_:2,2t', '_:2c,3,3t'])
+ result = list(extract.extract("python", BytesIO(content), kw))
+ expected = [(2, '1 arg, arg 1', [], None),
+ (3, '2 args, arg 1', [], None),
+ (3, '2 args, arg 2', [], None),
+ (4, '3 args, arg 1', [], None),
+ (4, '3 args, arg 3', [], '3 args, arg 2'),
+ (5, '4 args, arg 1', [], None)]
+ assert result == expected
+
+
def configure_cli_command(cmdline):
"""
Helper to configure a command class, but not run it just yet.
|
Feature request: Support gettext-like "t" specifier in keywords
The full description of xgettext's `--keyword` option is [here](https://www.gnu.org/software/gettext/manual/html_node/xgettext-Invocation.html#Language-specific-options).
`pybabel extract` supports a similar syntax, but it does not support the trailing "*n*t" to indicate that this keyword only applies when there are *n* arguments. This can be useful in some Python projects ([example](https://github.com/frescobaldi/frescobaldi)) where the `_` function is variadic for convenience. (In this particular project, it behaves like `gettext` with 1 arg, `pgettext` with 2 args, `ngettext` with 3 args and `npgettext` with 4 args, i.e., `_(message)`, `_(context, message)`, `_(singular, plural, number)` or `_(context, singular, plural, number)`.)
|
0.0
|
9ef53c6a6ab5fc604b58ccb19dc63ebcf8edd28b
|
[
"tests/messages/test_frontend.py::test_parse_keywords_with_t",
"tests/messages/test_frontend.py::test_extract_messages_with_t"
] |
[
"tests/messages/test_frontend.py::CompileCatalogTestCase::test_no_directory_or_input_file_specified",
"tests/messages/test_frontend.py::CompileCatalogTestCase::test_no_directory_or_output_file_specified",
"tests/messages/test_frontend.py::ExtractMessagesTestCase::test_both_sort_output_and_sort_by_file",
"tests/messages/test_frontend.py::ExtractMessagesTestCase::test_input_dirs_is_alias_for_input_paths",
"tests/messages/test_frontend.py::ExtractMessagesTestCase::test_input_dirs_is_mutually_exclusive_with_input_paths",
"tests/messages/test_frontend.py::ExtractMessagesTestCase::test_input_paths_handle_spaces_after_comma",
"tests/messages/test_frontend.py::ExtractMessagesTestCase::test_invalid_file_or_dir_input_path",
"tests/messages/test_frontend.py::ExtractMessagesTestCase::test_neither_default_nor_custom_keywords",
"tests/messages/test_frontend.py::ExtractMessagesTestCase::test_no_output_file_specified",
"tests/messages/test_frontend.py::InitCatalogTestCase::test_no_input_file",
"tests/messages/test_frontend.py::InitCatalogTestCase::test_no_locale",
"tests/messages/test_frontend.py::CommandLineInterfaceTestCase::test_help",
"tests/messages/test_frontend.py::CommandLineInterfaceTestCase::test_usage",
"tests/messages/test_frontend.py::test_parse_mapping",
"tests/messages/test_frontend.py::test_parse_keywords",
"tests/messages/test_frontend.py::test_extract_keyword_args_384[-k-False]",
"tests/messages/test_frontend.py::test_extract_keyword_args_384[-k-True]",
"tests/messages/test_frontend.py::test_extract_keyword_args_384[--keyword-False]",
"tests/messages/test_frontend.py::test_extract_keyword_args_384[--keyword-True]",
"tests/messages/test_frontend.py::test_extract_keyword_args_384[--keywords-False]",
"tests/messages/test_frontend.py::test_extract_keyword_args_384[--keywords-True]",
"tests/messages/test_frontend.py::test_extract_distutils_keyword_arg_388[LW_-expected0]",
"tests/messages/test_frontend.py::test_extract_distutils_keyword_arg_388[LW_",
"tests/messages/test_frontend.py::test_extract_distutils_keyword_arg_388[yiy",
"tests/messages/test_frontend.py::test_extract_cli_knows_dash_s",
"tests/messages/test_frontend.py::test_extract_add_location"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-06-16 15:43:19+00:00
|
bsd-3-clause
| 5,043 |
|
python-babel__babel-585
|
diff --git a/babel/numbers.py b/babel/numbers.py
index 564d7ce..cc825c8 100644
--- a/babel/numbers.py
+++ b/babel/numbers.py
@@ -157,6 +157,36 @@ def get_currency_precision(currency):
return precisions.get(currency, precisions['DEFAULT'])[0]
+def get_currency_unit_pattern(currency, count=None, locale=LC_NUMERIC):
+ """
+ Return the unit pattern used for long display of a currency value
+ for a given locale.
+ This is a string containing ``{0}`` where the numeric part
+ should be substituted and ``{1}`` where the currency long display
+ name should be substituted.
+
+ >>> get_currency_unit_pattern('USD', locale='en_US', count=10)
+ u'{0} {1}'
+
+ .. versionadded:: 2.7.0
+
+ :param currency: the currency code.
+ :param count: the optional count. If provided the unit
+ pattern for that number will be returned.
+ :param locale: the `Locale` object or locale identifier.
+ """
+ loc = Locale.parse(locale)
+ if count is not None:
+ plural_form = loc.plural_form(count)
+ try:
+ return loc._data['currency_unit_patterns'][plural_form]
+ except LookupError:
+ # Fall back to 'other'
+ pass
+
+ return loc._data['currency_unit_patterns']['other']
+
+
def get_territory_currencies(territory, start_date=None, end_date=None,
tender=True, non_tender=False,
include_details=False):
@@ -442,6 +472,17 @@ def format_currency(
...
UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
+ You can also pass format_type='name' to use long display names. The order of
+ the number and currency name, along with the correct localized plural form
+ of the currency name, is chosen according to locale:
+
+ >>> format_currency(1, 'USD', locale='en_US', format_type='name')
+ u'1.00 US dollar'
+ >>> format_currency(1099.98, 'USD', locale='en_US', format_type='name')
+ u'1,099.98 US dollars'
+ >>> format_currency(1099.98, 'USD', locale='ee', format_type='name')
+ u'us ga dollar 1,099.98'
+
By default the locale is allowed to truncate and round a high-precision
number by forcing its format pattern onto the decimal part. You can bypass
this behavior with the `decimal_quantization` parameter:
@@ -459,7 +500,12 @@ def format_currency(
:param format_type: the currency format type to use
:param decimal_quantization: Truncate and round high-precision numbers to
the format pattern. Defaults to `True`.
+
"""
+ if format_type == 'name':
+ return _format_currency_long_name(number, currency, format=format,
+ locale=locale, currency_digits=currency_digits,
+ decimal_quantization=decimal_quantization)
locale = Locale.parse(locale)
if format:
pattern = parse_pattern(format)
@@ -475,6 +521,42 @@ def format_currency(
decimal_quantization=decimal_quantization)
+def _format_currency_long_name(
+ number, currency, format=None, locale=LC_NUMERIC, currency_digits=True,
+ format_type='standard', decimal_quantization=True):
+ # Algorithm described here:
+ # https://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies
+ locale = Locale.parse(locale)
+ # Step 1.
+ # There are no examples of items with explicit count (0 or 1) in current
+ # locale data. So there is no point implementing that.
+ # Step 2.
+
+ # Correct number to numeric type, important for looking up plural rules:
+ if isinstance(number, string_types):
+ number_n = float(number)
+ else:
+ number_n = number
+
+ # Step 3.
+ unit_pattern = get_currency_unit_pattern(currency, count=number_n, locale=locale)
+
+ # Step 4.
+ display_name = get_currency_name(currency, count=number_n, locale=locale)
+
+ # Step 5.
+ if not format:
+ format = locale.decimal_formats.get(format)
+
+ pattern = parse_pattern(format)
+
+ number_part = pattern.apply(
+ number, locale, currency=currency, currency_digits=currency_digits,
+ decimal_quantization=decimal_quantization)
+
+ return unit_pattern.format(number_part, display_name)
+
+
def format_percent(
number, format=None, locale=LC_NUMERIC, decimal_quantization=True):
"""Return formatted percent value for a specific locale.
diff --git a/docs/api/numbers.rst b/docs/api/numbers.rst
index 1b21425..758ceba 100644
--- a/docs/api/numbers.rst
+++ b/docs/api/numbers.rst
@@ -38,6 +38,8 @@ Data Access
.. autofunction:: get_currency_symbol
+.. autofunction:: get_currency_unit_pattern
+
.. autofunction:: get_decimal_symbol
.. autofunction:: get_plus_sign_symbol
diff --git a/scripts/import_cldr.py b/scripts/import_cldr.py
index 60aa6c2..f1dd391 100755
--- a/scripts/import_cldr.py
+++ b/scripts/import_cldr.py
@@ -423,6 +423,7 @@ def _process_local_datas(sup, srcdir, destdir, force=False, dump_json=False):
parse_percent_formats(data, tree)
parse_currency_formats(data, tree)
+ parse_currency_unit_patterns(data, tree)
parse_currency_names(data, tree)
parse_unit_patterns(data, tree)
parse_date_fields(data, tree)
@@ -903,6 +904,17 @@ def parse_currency_formats(data, tree):
currency_formats[type] = numbers.parse_pattern(pattern)
+def parse_currency_unit_patterns(data, tree):
+ currency_unit_patterns = data.setdefault('currency_unit_patterns', {})
+ for currency_formats_elem in tree.findall('.//currencyFormats'):
+ if _should_skip_number_elem(data, currency_formats_elem): # TODO: Support other number systems
+ continue
+ for unit_pattern_elem in currency_formats_elem.findall('./unitPattern'):
+ count = unit_pattern_elem.attrib['count']
+ pattern = text_type(unit_pattern_elem.text)
+ currency_unit_patterns[count] = pattern
+
+
def parse_day_period_rules(tree):
"""
Parse dayPeriodRule data into a dict.
|
python-babel/babel
|
a5ecaa321817d3705cbda1476f6e9f06daa1e847
|
diff --git a/tests/test_numbers.py b/tests/test_numbers.py
index 493c1a7..32f4280 100644
--- a/tests/test_numbers.py
+++ b/tests/test_numbers.py
@@ -19,7 +19,7 @@ from datetime import date
from babel import Locale, localedata, numbers
from babel.numbers import (
list_currencies, validate_currency, UnknownCurrencyError, is_currency, normalize_currency,
- get_currency_precision, get_decimal_precision)
+ get_currency_precision, get_decimal_precision, get_currency_unit_pattern)
from babel.localedata import locale_identifiers
from babel._compat import decimal
@@ -228,6 +228,17 @@ def test_get_currency_precision():
assert get_currency_precision('JPY') == 0
+def test_get_currency_unit_pattern():
+ assert get_currency_unit_pattern('USD', locale='en_US') == '{0} {1}'
+ assert get_currency_unit_pattern('USD', locale='es_GT') == '{1} {0}'
+
+ # 'ro' locale various pattern according to count
+ assert get_currency_unit_pattern('USD', locale='ro', count=1) == '{0} {1}'
+ assert get_currency_unit_pattern('USD', locale='ro', count=2) == '{0} {1}'
+ assert get_currency_unit_pattern('USD', locale='ro', count=100) == '{0} de {1}'
+ assert get_currency_unit_pattern('USD', locale='ro') == '{0} de {1}'
+
+
def test_get_territory_currencies():
assert numbers.get_territory_currencies('AT', date(1995, 1, 1)) == ['ATS']
assert numbers.get_territory_currencies('AT', date(2011, 1, 1)) == ['EUR']
@@ -415,6 +426,52 @@ def test_format_currency_quantization():
'0.9999999999', 'USD', locale=locale_code, decimal_quantization=False).find('9999999999') > -1
+def test_format_currency_long_display_name():
+ assert (numbers.format_currency(1099.98, 'USD', locale='en_US', format_type='name')
+ == u'1,099.98 US dollars')
+ assert (numbers.format_currency(1.00, 'USD', locale='en_US', format_type='name')
+ == u'1.00 US dollar')
+ assert (numbers.format_currency(1.00, 'EUR', locale='en_US', format_type='name')
+ == u'1.00 euro')
+ assert (numbers.format_currency(2, 'EUR', locale='en_US', format_type='name')
+ == u'2.00 euros')
+ # This tests that '{1} {0}' unitPatterns are found:
+ assert (numbers.format_currency(1, 'USD', locale='sw', format_type='name')
+ == u'dola ya Marekani 1.00')
+ # This tests unicode chars:
+ assert (numbers.format_currency(1099.98, 'USD', locale='es_GT', format_type='name')
+ == u'dólares estadounidenses 1,099.98')
+ # Test for completely unknown currency, should fallback to currency code
+ assert (numbers.format_currency(1099.98, 'XAB', locale='en_US', format_type='name')
+ == u'1,099.98 XAB')
+
+ # Test for finding different unit patterns depending on count
+ assert (numbers.format_currency(1, 'USD', locale='ro', format_type='name')
+ == u'1,00 dolar american')
+ assert (numbers.format_currency(2, 'USD', locale='ro', format_type='name')
+ == u'2,00 dolari americani')
+ assert (numbers.format_currency(100, 'USD', locale='ro', format_type='name')
+ == u'100,00 de dolari americani')
+
+
+def test_format_currency_long_display_name_all():
+ for locale_code in localedata.locale_identifiers():
+ assert numbers.format_currency(
+ 1, 'USD', locale=locale_code, format_type='name').find('1') > -1
+ assert numbers.format_currency(
+ '1', 'USD', locale=locale_code, format_type='name').find('1') > -1
+
+
+def test_format_currency_long_display_name_custom_format():
+ assert (numbers.format_currency(1099.98, 'USD', locale='en_US',
+ format_type='name', format='##0')
+ == '1099.98 US dollars')
+ assert (numbers.format_currency(1099.98, 'USD', locale='en_US',
+ format_type='name', format='##0',
+ currency_digits=False)
+ == '1100 US dollars')
+
+
def test_format_percent():
assert numbers.format_percent(0.34, locale='en_US') == u'34%'
assert numbers.format_percent(0, locale='en_US') == u'0%'
|
Implement currency formatting with long display names.
Namely, things like:
"123,456.78 US dollars"
(en locale)
or
"dólares estadounidenses 123,456.78"
(es-GT locale)
The algorithm for doing this is described here: https://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies and CLDR contains the data.
I'd be happy to attempt to implement this myself. Two issues I'm aware of:
1) What should the API be? An extra parameter to `format_currency`? A new `format_type` (this risks clashing with other format types already defined)?
2) It looks like this would require data not currently available in the pickled locale data. Specifically it requires the `unitPattern` data. I'm not sure how to go about adding this - apart from the `import_cldr.py` script, is there a specific process to follow?
For comparison, browsers currently implement this as part of [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat) using options `{currencyDisplay: "name"}`. In a browser console you can do:
> Intl.NumberFormat("en", {currencyDisplay:"name", style:"currency", currency:"USD"}).format(123456.78)
"123,456.78 US dollars"
|
0.0
|
a5ecaa321817d3705cbda1476f6e9f06daa1e847
|
[
"tests/test_numbers.py::test_decimal_precision",
"tests/test_numbers.py::test_format_decimal_quantization",
"tests/test_numbers.py::test_format_currency_quantization",
"tests/test_numbers.py::test_format_currency_long_display_name_all",
"tests/test_numbers.py::test_format_percent_quantization",
"tests/test_numbers.py::test_format_scientific_quantization",
"tests/test_numbers.py::test_parse_grouping",
"tests/test_numbers.py::test_parse_pattern",
"tests/test_numbers.py::test_parse_pattern_negative",
"tests/test_numbers.py::test_numberpattern_repr",
"tests/test_numbers.py::test_parse_static_pattern"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-04 17:57:26+00:00
|
bsd-3-clause
| 5,044 |
|
python-babel__babel-646
|
diff --git a/babel/messages/pofile.py b/babel/messages/pofile.py
index fe37631..9eb3a5c 100644
--- a/babel/messages/pofile.py
+++ b/babel/messages/pofile.py
@@ -16,8 +16,7 @@ import re
from babel.messages.catalog import Catalog, Message
from babel.util import wraptext
-from babel._compat import text_type
-
+from babel._compat import text_type, cmp
def unescape(string):
@@ -99,6 +98,36 @@ class _NormalizedString(object):
def __nonzero__(self):
return bool(self._strs)
+ __bool__ = __nonzero__
+
+ def __repr__(self):
+ return os.linesep.join(self._strs)
+
+ def __cmp__(self, other):
+ if not other:
+ return 1
+
+ return cmp(text_type(self), text_type(other))
+
+ def __gt__(self, other):
+ return self.__cmp__(other) > 0
+
+ def __lt__(self, other):
+ return self.__cmp__(other) < 0
+
+ def __ge__(self, other):
+ return self.__cmp__(other) >= 0
+
+ def __le__(self, other):
+ return self.__cmp__(other) <= 0
+
+ def __eq__(self, other):
+ return self.__cmp__(other) == 0
+
+ def __ne__(self, other):
+ return self.__cmp__(other) != 0
+
+
class PoFileParser(object):
"""Support class to read messages from a ``gettext`` PO (portable object) file
@@ -552,7 +581,16 @@ def write_po(fileobj, catalog, width=76, no_location=False, omit_header=False,
if not no_location:
locs = []
- for filename, lineno in sorted(message.locations):
+
+ # Attempt to sort the locations. If we can't do that, for instance
+ # because there are mixed integers and Nones or whatnot (see issue #606)
+ # then give up, but also don't just crash.
+ try:
+ locations = sorted(message.locations)
+ except TypeError: # e.g. "TypeError: unorderable types: NoneType() < int()"
+ locations = message.locations
+
+ for filename, lineno in locations:
if lineno and include_lineno:
locs.append(u'%s:%d' % (filename.replace(os.sep, '/'), lineno))
else:
|
python-babel/babel
|
4fa0c6e5a2d3ae4c10ca160dabe4e3d169dace81
|
diff --git a/tests/messages/test_normalized_string.py b/tests/messages/test_normalized_string.py
new file mode 100644
index 0000000..9c95672
--- /dev/null
+++ b/tests/messages/test_normalized_string.py
@@ -0,0 +1,17 @@
+from babel.messages.pofile import _NormalizedString
+
+
+def test_normalized_string():
+ ab1 = _NormalizedString('a', 'b ')
+ ab2 = _NormalizedString('a', ' b')
+ ac1 = _NormalizedString('a', 'c')
+ ac2 = _NormalizedString(' a', 'c ')
+ z = _NormalizedString()
+ assert ab1 == ab2 and ac1 == ac2 # __eq__
+ assert ab1 < ac1 # __lt__
+ assert ac1 > ab2 # __gt__
+ assert ac1 >= ac2 # __ge__
+ assert ab1 <= ab2 # __le__
+ assert ab1 != ac1 # __ne__
+ assert not z # __nonzero__ / __bool__
+ assert sorted([ab1, ab2, ac1]) # the sort order is not stable so we can't really check it, just that we can sort
|
TypeError: '<' not supported between instances of '_NormalizedString' and '_NormalizedString'
Hi there,
I was getting this message when running this command against the Blender's translation files
```
sphinx-intl update -p build/locale -l "vi" &
```
The listing of the error is here:
```
Not Changed: locale/vi/LC_MESSAGES/animation/actions.po
Traceback (most recent call last):
File "/usr/local/bin/sphinx-intl", line 11, in <module>
sys.exit(main())
File "/usr/local/lib64/python3.6/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib64/python3.6/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib64/python3.6/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib64/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/sphinx_intl/commands.py", line 256, in update
basic.update(locale_dir, pot_dir, languages)
File "/usr/local/lib/python3.6/site-packages/sphinx_intl/basic.py", line 53, in update
cat = c.load_po(po_file)
File "/usr/local/lib/python3.6/site-packages/sphinx_intl/catalog.py", line 17, in load_po
cat = pofile.read_po(f)
File "/usr/local/lib64/python3.6/site-packages/babel/messages/pofile.py", line 345, in read_po
parser.parse(fileobj)
File "/usr/local/lib64/python3.6/site-packages/babel/messages/pofile.py", line 276, in parse
self._process_comment(line)
File "/usr/local/lib64/python3.6/site-packages/babel/messages/pofile.py", line 235, in _process_comment
self._finish_current_message()
File "/usr/local/lib64/python3.6/site-packages/babel/messages/pofile.py", line 175, in _finish_current_message
self._add_message()
File "/usr/local/lib64/python3.6/site-packages/babel/messages/pofile.py", line 143, in _add_message
self.translations.sort()
TypeError: '<' not supported between instances of '_NormalizedString' and '_NormalizedString'
```
Traced down to /usr/local/lib64/python3.6/site-packages/babel/messages/pofile.py", line 143
and found that the class '_NormalizedString' missed the implementations of '__repr__', '__gt__', '__eq__', '__lt__'. Hacked implementation of the above operators appeared to have solved the problem. Listing of the '_NormalizedString' class is listed below:
```
class _NormalizedString(object):
def __init__(self, *args):
self._strs = []
for arg in args:
self.append(arg)
def __repr__(self):
return os.linesep.join(self._strs)
def __cmp__(self, other):
if (other == None): return 1
this_text = str(self)
other_text = str(other)
if (this_text == other_text): return 0
if (this_text < other_text): return -1
if (this_text > other_text): return 1
def __gt__(self, other) -> bool:
return self.__cmp__(other) > 0
def __eq__(self, other) -> bool:
return self.__cmp__(other) == 0
def __lt__(self, other) -> bool:
return self.__cmp__(other) < 0
def append(self, s):
self._strs.append(s.strip())
def denormalize(self):
return ''.join(map(unescape, self._strs))
def __nonzero__(self):
return bool(self._strs)
```
I have not yet understood the purpose of 'sort' operation in the pofile.py", line 143, as when listing out the translations list before and after the sort, most I see was one block of msgstr element. Anyhow just to let you know the bug and potential fix.
I think the package version is
babel.noarch 2.5.3-1
Best regards,
Hoang Tran
<[email protected]>
|
0.0
|
4fa0c6e5a2d3ae4c10ca160dabe4e3d169dace81
|
[
"tests/messages/test_normalized_string.py::test_normalized_string"
] |
[] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2019-05-27 08:30:41+00:00
|
bsd-3-clause
| 5,045 |
|
python-babel__babel-932
|
diff --git a/babel/messages/extract.py b/babel/messages/extract.py
index 4f0f649..c19dd5a 100644
--- a/babel/messages/extract.py
+++ b/babel/messages/extract.py
@@ -16,9 +16,10 @@
:license: BSD, see LICENSE for more details.
"""
import ast
+import io
import os
-from os.path import relpath
import sys
+from os.path import relpath
from tokenize import generate_tokens, COMMENT, NAME, OP, STRING
from babel.util import parse_encoding, parse_future_flags, pathmatch
@@ -532,7 +533,7 @@ def _parse_python_string(value, encoding, future_flags):
return None
-def extract_javascript(fileobj, keywords, comment_tags, options):
+def extract_javascript(fileobj, keywords, comment_tags, options, lineno=1):
"""Extract messages from JavaScript source code.
:param fileobj: the seekable, file-like object the messages should be
@@ -544,7 +545,11 @@ def extract_javascript(fileobj, keywords, comment_tags, options):
:param options: a dictionary of additional options (optional)
Supported options are:
* `jsx` -- set to false to disable JSX/E4X support.
- * `template_string` -- set to false to disable ES6 template string support.
+ * `template_string` -- if `True`, supports gettext(`key`)
+ * `parse_template_string` -- if `True` will parse the
+ contents of javascript
+ template strings.
+ :param lineno: line number offset (for parsing embedded fragments)
"""
from babel.messages.jslexer import Token, tokenize, unquote_string
funcname = message_lineno = None
@@ -556,12 +561,12 @@ def extract_javascript(fileobj, keywords, comment_tags, options):
last_token = None
call_stack = -1
dotted = any('.' in kw for kw in keywords)
-
for token in tokenize(
fileobj.read().decode(encoding),
jsx=options.get("jsx", True),
template_string=options.get("template_string", True),
- dotted=dotted
+ dotted=dotted,
+ lineno=lineno
):
if ( # Turn keyword`foo` expressions into keyword("foo") calls:
funcname and # have a keyword...
@@ -573,7 +578,11 @@ def extract_javascript(fileobj, keywords, comment_tags, options):
call_stack = 0
token = Token('operator', ')', token.lineno)
- if token.type == 'operator' and token.value == '(':
+ if options.get('parse_template_string') and not funcname and token.type == 'template_string':
+ for item in parse_template_string(token.value, keywords, comment_tags, options, token.lineno):
+ yield item
+
+ elif token.type == 'operator' and token.value == '(':
if funcname:
message_lineno = token.lineno
call_stack += 1
@@ -665,3 +674,41 @@ def extract_javascript(fileobj, keywords, comment_tags, options):
funcname = token.value
last_token = token
+
+
+def parse_template_string(template_string, keywords, comment_tags, options, lineno=1):
+ """Parse JavaScript template string.
+
+ :param template_string: the template string to be parsed
+ :param keywords: a list of keywords (i.e. function names) that should be
+ recognized as translation functions
+ :param comment_tags: a list of translator tags to search for and include
+ in the results
+ :param options: a dictionary of additional options (optional)
+ :param lineno: starting line number (optional)
+ """
+ from babel.messages.jslexer import line_re
+ prev_character = None
+ level = 0
+ inside_str = False
+ expression_contents = ''
+ for character in template_string[1:-1]:
+ if not inside_str and character in ('"', "'", '`'):
+ inside_str = character
+ elif inside_str == character and prev_character != r'\\':
+ inside_str = False
+ if level:
+ expression_contents += character
+ if not inside_str:
+ if character == '{' and prev_character == '$':
+ level += 1
+ elif level and character == '}':
+ level -= 1
+ if level == 0 and expression_contents:
+ expression_contents = expression_contents[0:-1]
+ fake_file_obj = io.BytesIO(expression_contents.encode())
+ for item in extract_javascript(fake_file_obj, keywords, comment_tags, options, lineno):
+ yield item
+ lineno += len(line_re.findall(expression_contents))
+ expression_contents = ''
+ prev_character = character
diff --git a/babel/messages/jslexer.py b/babel/messages/jslexer.py
index 1264b2d..886f69d 100644
--- a/babel/messages/jslexer.py
+++ b/babel/messages/jslexer.py
@@ -151,17 +151,17 @@ def unquote_string(string):
return u''.join(result)
-def tokenize(source, jsx=True, dotted=True, template_string=True):
+def tokenize(source, jsx=True, dotted=True, template_string=True, lineno=1):
"""
Tokenize JavaScript/JSX source. Returns a generator of tokens.
:param jsx: Enable (limited) JSX parsing.
:param dotted: Read dotted names as single name token.
:param template_string: Support ES6 template strings
+ :param lineno: starting line number (optional)
"""
may_divide = False
pos = 0
- lineno = 1
end = len(source)
rules = get_rules(jsx=jsx, dotted=dotted, template_string=template_string)
diff --git a/babel/numbers.py b/babel/numbers.py
index 2221e95..da5936d 100644
--- a/babel/numbers.py
+++ b/babel/numbers.py
@@ -17,6 +17,7 @@
# TODO:
# Padding and rounding increments in pattern:
# - https://www.unicode.org/reports/tr35/ (Appendix G.6)
+from __future__ import annotations
import decimal
import re
from datetime import date as date_, datetime as datetime_
@@ -431,7 +432,7 @@ def format_compact_decimal(number, *, format_type="short", locale=LC_NUMERIC, fr
u'123万'
>>> format_compact_decimal(2345678, format_type="long", locale="mk")
u'2 милиони'
- >>> format_compact_decimal(21098765, format_type="long", locale="mk")
+ >>> format_compact_decimal(21000000, format_type="long", locale="mk")
u'21 милион'
:param number: the number to format
@@ -469,11 +470,15 @@ def _get_compact_format(number, compact_format, locale, fraction_digits=0):
# equal to the number of 0's in the pattern minus 1
number = number / (magnitude // (10 ** (pattern.count("0") - 1)))
# round to the number of fraction digits requested
- number = round(number, fraction_digits)
+ rounded = round(number, fraction_digits)
# if the remaining number is singular, use the singular format
plural_form = locale.plural_form(abs(number))
- plural_form = plural_form if plural_form in compact_format else "other"
+ if plural_form not in compact_format:
+ plural_form = "other"
+ if number == 1 and "1" in compact_format:
+ plural_form = "1"
format = compact_format[plural_form][str(magnitude)]
+ number = rounded
break
return number, format
@@ -960,17 +965,19 @@ def parse_pattern(pattern):
return NumberPattern(pattern, (pos_prefix, neg_prefix),
(pos_suffix, neg_suffix), grouping,
int_prec, frac_prec,
- exp_prec, exp_plus)
+ exp_prec, exp_plus, number)
class NumberPattern:
def __init__(self, pattern, prefix, suffix, grouping,
- int_prec, frac_prec, exp_prec, exp_plus):
+ int_prec, frac_prec, exp_prec, exp_plus,
+ number_pattern: str | None = None):
# Metadata of the decomposed parsed pattern.
self.pattern = pattern
self.prefix = prefix
self.suffix = suffix
+ self.number_pattern = number_pattern
self.grouping = grouping
self.int_prec = int_prec
self.frac_prec = frac_prec
@@ -1115,7 +1122,7 @@ class NumberPattern:
retval = ''.join([
self.prefix[is_negative],
- number,
+ number if self.number_pattern != '' else '',
self.suffix[is_negative]])
if u'¤' in retval:
|
python-babel/babel
|
a45e25e3125f6ee0a9f32387545df318b0b3b2d0
|
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 4915816..f9a7bee 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -33,7 +33,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip setuptools wheel
- python -m pip install tox tox-gh-actions==2.1.0
+ python -m pip install 'tox<4.0.0' 'tox-gh-actions==2.12.0'
- name: Run test via Tox
run: tox --skip-missing-interpreters
env:
diff --git a/tests/messages/test_js_extract.py b/tests/messages/test_js_extract.py
index 72c5211..95985c0 100644
--- a/tests/messages/test_js_extract.py
+++ b/tests/messages/test_js_extract.py
@@ -150,3 +150,42 @@ def test_template_string_tag_usage():
)
assert messages == [(1, 'Tag template, wow', [], None)]
+
+
+def test_inside_template_string():
+ buf = BytesIO(b"const msg = `${gettext('Hello')} ${user.name}`")
+ messages = list(
+ extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True})
+ )
+
+ assert messages == [(1, 'Hello', [], None)]
+
+
+def test_inside_template_string_with_linebreaks():
+ buf = BytesIO(b"""\
+const userName = gettext('Username')
+const msg = `${
+gettext('Hello')
+} ${userName} ${
+gettext('Are you having a nice day?')
+}`
+const msg2 = `${
+gettext('Howdy')
+} ${userName} ${
+gettext('Are you doing ok?')
+}`
+""")
+ messages = list(
+ extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True})
+ )
+
+ assert messages == [(1, 'Username', [], None), (3, 'Hello', [], None), (5, 'Are you having a nice day?', [], None), (8, 'Howdy', [], None), (10, 'Are you doing ok?', [], None)]
+
+
+def test_inside_nested_template_string():
+ buf = BytesIO(b"const msg = `${gettext('Greetings!')} ${ evening ? `${user.name}: ${gettext('This is a lovely evening.')}` : `${gettext('The day is really nice!')} ${user.name}`}`")
+ messages = list(
+ extract.extract('javascript', buf, {"gettext": None}, [], {'parse_template_string': True})
+ )
+
+ assert messages == [(1, 'Greetings!', [], None), (1, 'This is a lovely evening.', [], None), (1, 'The day is really nice!', [], None)]
diff --git a/tests/test_numbers.py b/tests/test_numbers.py
index bb6c4e8..37d2f9e 100644
--- a/tests/test_numbers.py
+++ b/tests/test_numbers.py
@@ -153,7 +153,12 @@ class FormatDecimalTestCase(unittest.TestCase):
assert numbers.format_compact_decimal(-123456789, format_type='short', locale='en_US') == u'-123M'
assert numbers.format_compact_decimal(-123456789, format_type='long', locale='en_US') == u'-123 million'
assert numbers.format_compact_decimal(2345678, locale='mk', format_type='long') == u'2 милиони'
- assert numbers.format_compact_decimal(21098765, locale='mk', format_type='long') == u'21 милион'
+ assert numbers.format_compact_decimal(21000000, locale='mk', format_type='long') == u'21 милион'
+ assert numbers.format_compact_decimal(21345, locale="gv", format_type="short") == u'21K'
+ assert numbers.format_compact_decimal(1000, locale='it', format_type='long') == u'mille'
+ assert numbers.format_compact_decimal(1234, locale='it', format_type='long') == u'1 mila'
+ assert numbers.format_compact_decimal(1000, locale='fr', format_type='long') == u'mille'
+ assert numbers.format_compact_decimal(1234, locale='fr', format_type='long') == u'1 millier'
class NumberParsingTestCase(unittest.TestCase):
|
format_compact_decimal incorrectly works when the pattern has no 0 characters
## Overview Description
`format_compact_decimal` incorrectly works when the pattern has no 0 characters. Also, it doesn't handle `count="1"` rule.
## Steps to Reproduce
```pycon
>>> from babel import numbers
>>> numbers.format_compact_decimal(1000, format_type='long', locale='it')
'mille1' # should be 'mille'
>>> numbers.format_compact_decimal(1234, format_type='long', locale='it')
'mille1' # should be '1 mila'
>>> numbers.format_compact_decimal(1000, format_type='long', locale='fr')
'1 millier' # should be 'mille'
>>> numbers.format_compact_decimal(1234, format_type='long', locale='fr')
'1 millier' # correct
```
## Additional Information
* https://github.com/unicode-org/cldr/blob/release-41/common/main/it.xml#L5210
* https://github.com/unicode-org/cldr/blob/release-41/common/main/fr.xml#L7743
* [Explicit 0 and 1 rules](https://unicode.org/reports/tr35/tr35-numbers.html#Explicit_0_1_rules)
|
0.0
|
a45e25e3125f6ee0a9f32387545df318b0b3b2d0
|
[
"tests/messages/test_js_extract.py::test_inside_template_string",
"tests/messages/test_js_extract.py::test_inside_template_string_with_linebreaks",
"tests/messages/test_js_extract.py::test_inside_nested_template_string"
] |
[
"tests/messages/test_js_extract.py::test_simple_extract",
"tests/messages/test_js_extract.py::test_various_calls",
"tests/messages/test_js_extract.py::test_message_with_line_comment",
"tests/messages/test_js_extract.py::test_message_with_multiline_comment",
"tests/messages/test_js_extract.py::test_ignore_function_definitions",
"tests/messages/test_js_extract.py::test_misplaced_comments",
"tests/messages/test_js_extract.py::test_jsx_extraction[False]",
"tests/messages/test_js_extract.py::test_jsx_extraction[True]",
"tests/messages/test_js_extract.py::test_dotted_keyword_extract",
"tests/messages/test_js_extract.py::test_template_string_standard_usage",
"tests/messages/test_js_extract.py::test_template_string_tag_usage",
"tests/test_numbers.py::test_decimal_precision",
"tests/test_numbers.py::test_format_decimal_quantization",
"tests/test_numbers.py::test_format_currency_quantization",
"tests/test_numbers.py::test_format_currency_long_display_name_all",
"tests/test_numbers.py::test_format_percent_quantization",
"tests/test_numbers.py::test_format_scientific_quantization",
"tests/test_numbers.py::test_parse_grouping",
"tests/test_numbers.py::test_parse_pattern",
"tests/test_numbers.py::test_parse_pattern_negative",
"tests/test_numbers.py::test_numberpattern_repr",
"tests/test_numbers.py::test_parse_static_pattern"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-17 04:55:00+00:00
|
bsd-3-clause
| 5,046 |
|
python-babel__flask-babel-230
|
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index d0fac7a..c870612 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -2,7 +2,7 @@ on:
workflow_dispatch:
release:
types:
- - created
+ - published
name: Release
diff --git a/flask_babel/__init__.py b/flask_babel/__init__.py
index a76bf7c..9f94d22 100644
--- a/flask_babel/__init__.py
+++ b/flask_babel/__init__.py
@@ -16,10 +16,10 @@ from typing import List, Callable, Optional, Union
from babel.support import Translations, NullTranslations
from flask import current_app, g
-from flask.helpers import locked_cached_property
from babel import dates, numbers, support, Locale
from pytz import timezone, UTC
from werkzeug.datastructures import ImmutableDict
+from werkzeug.utils import cached_property
from flask_babel.speaklater import LazyString
@@ -221,7 +221,7 @@ class Babel:
"""
return get_babel().default_domain
- @locked_cached_property
+ @cached_property
def domain_instance(self):
"""The message domain for the translations.
"""
|
python-babel/flask-babel
|
69d3340cd0ff52f3e23a47518285a7e6d8f8c640
|
diff --git a/tests/test_app_factory.py b/tests/test_app_factory.py
new file mode 100644
index 0000000..0dbef3c
--- /dev/null
+++ b/tests/test_app_factory.py
@@ -0,0 +1,24 @@
+import flask
+import flask_babel as babel
+
+
+def test_app_factory():
+ b = babel.Babel()
+
+ def locale_selector():
+ return 'de_DE'
+
+ def create_app():
+ app_ = flask.Flask(__name__)
+ b.init_app(
+ app_,
+ default_locale='en_US',
+ locale_selector=locale_selector
+ )
+ return app_
+
+ app = create_app()
+ with app.test_request_context():
+ assert str(babel.get_locale()) == 'de_DE'
+ assert babel.gettext(u'Hello %(name)s!', name='Peter') == \
+ 'Hallo Peter!'
|
`locked_cached_property` is deprecated as of Flask>=2.3.0
issue: https://github.com/pallets/flask/issues/4993
pr: https://github.com/pallets/flask/pull/4998
This is the only part where this is used. I'm wondering though, whether locking is even needed in this case or if a `werkzeug.utils.cached_property` is enough?
https://github.com/python-babel/flask-babel/blob/69d3340cd0ff52f3e23a47518285a7e6d8f8c640/flask_babel/__init__.py#L224-L228
happy to send a PR swapping the decorator. But just wanted to be sure whether the lock is actually needed.
(tests pass with `werkzeug.utils.cached_property`)
|
0.0
|
69d3340cd0ff52f3e23a47518285a7e6d8f8c640
|
[
"tests/test_app_factory.py::test_app_factory"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-05-17 10:48:12+00:00
|
bsd-3-clause
| 5,047 |
|
python-beaver__python-conf_d-7
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..21fef2c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+# build files
+*.pyc
+__pycache__
+*.egg-info
+.eggs
+dist
+build
+.tox
diff --git a/README.rst b/README.rst
index 2599913..a2a0ac8 100644
--- a/README.rst
+++ b/README.rst
@@ -7,7 +7,7 @@ read configuration files, conf.d style
Requirements
============
-* Python 2.6+
+* Python 2.6+ or Python 3.4+
Installation
============
@@ -20,7 +20,7 @@ From Github::
From PyPI::
- pip install conf_d==0.0.3
+ pip install conf_d==0.0.5
Usage
=====
diff --git a/conf_d/__init__.py b/conf_d/__init__.py
index a18e3a0..bd55dcc 100644
--- a/conf_d/__init__.py
+++ b/conf_d/__init__.py
@@ -1,13 +1,14 @@
# -*- coding: utf-8 -*-
-import ConfigParser
import os
-__version__ = '0.0.4'
+from conf_d.compat import ConfigParser
+
+__version__ = '0.0.5'
class Configuration():
- def __init__(self, name, path, parse=True, confd_path=None, conf_ext=None, main_defaults={}, section_defaults={}, main_parser=None, section_parser=None, path_from_main=None, config_parser=ConfigParser.ConfigParser):
+ def __init__(self, name, path, parse=True, confd_path=None, conf_ext=None, main_defaults={}, section_defaults={}, main_parser=None, section_parser=None, path_from_main=None, config_parser=ConfigParser):
self._conf_ext = conf_ext
self._config_sections = {}
self._confd_path = confd_path
diff --git a/conf_d/compat.py b/conf_d/compat.py
new file mode 100644
index 0000000..7d0e1fe
--- /dev/null
+++ b/conf_d/compat.py
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+from sys import version_info
+
+if version_info[0] < 3:
+ from ConfigParser import ConfigParser
+else:
+ from configparser import ConfigParser
diff --git a/setup.py b/setup.py
index fd655b7..2b142ee 100644
--- a/setup.py
+++ b/setup.py
@@ -33,6 +33,10 @@ setup(
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
],
description='read configuration files, conf.d style',
long_description=open('README.rst').read() + '\n\n' +
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..607ed8e
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,6 @@
+[tox]
+envlist = py26,py27,py34,py35,py36,py37
+
+[testenv]
+commands=
+ python setup.py test
|
python-beaver/python-conf_d
|
a032f0131c873a7f5199adb4ab819cd7a07bc693
|
diff --git a/conf_d/tests/test_configuration.py b/conf_d/tests/test_configuration.py
index f04143c..d8b64d0 100644
--- a/conf_d/tests/test_configuration.py
+++ b/conf_d/tests/test_configuration.py
@@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
-import ConfigParser
import unittest
from conf_d import Configuration
+from conf_d.compat import ConfigParser
-class TestConfigParser(ConfigParser.ConfigParser):
+
+class TestConfigParser(ConfigParser):
def read(self, path):
raise NotImplementedError('Catch this')
|
ConfigParser not found
ConfigParse has changed to configparser in Python3, when install Beaver from pip, the problem occurs and leads the installation to failure.
|
0.0
|
a032f0131c873a7f5199adb4ab819cd7a07bc693
|
[
"conf_d/tests/test_configuration.py::ConfigurationTests::test_confd",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_custom_config_parser",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_defaults",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_get",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_has_section",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_invalid_path",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_parse",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_parser",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_raw",
"conf_d/tests/test_configuration.py::ConfigurationTests::test_readme"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-12-09 12:41:32+00:00
|
mit
| 5,048 |
|
python-bonobo__bonobo-335
|
diff --git a/bin/update_apidoc.py b/bin/update_apidoc.py
index efb0563..b93cddf 100644
--- a/bin/update_apidoc.py
+++ b/bin/update_apidoc.py
@@ -1,3 +1,4 @@
+import inspect
import os
from jinja2 import DictLoader, Environment
@@ -30,8 +31,6 @@ class Module:
return os.path.join(__path__, apidoc_root, *self.name.split(".")) + ".rst"
-import inspect
-
bonobo = __import__("bonobo")
assert bonobo.__version__
diff --git a/bonobo/structs/graphs.py b/bonobo/structs/graphs.py
index aaf3fd6..ce43ef6 100644
--- a/bonobo/structs/graphs.py
+++ b/bonobo/structs/graphs.py
@@ -59,7 +59,11 @@ class PartialGraph:
class Graph:
"""
- Represents a directed graph of nodes.
+ Core structure representing a directed graph of nodes. It will be used to create data streaming queues between your
+ objects during the job execution.
+
+ This is how the data flows are defined.
+
"""
name = ""
@@ -75,7 +79,9 @@ class Graph:
yield from self.nodes
def __len__(self):
- """Node count.
+ """
+ The graph length is defined as its node count.
+
"""
return len(self.nodes)
@@ -92,8 +98,19 @@ class Graph:
return self.get_cursor().__rshift__(other)
def get_cursor(self, ref=BEGIN):
+ """
+ Create a `GraphCursor` to use the operator-based syntax to build graph, starting at `ref`.
+
+ """
return GraphCursor(self, last=self.index_of(ref))
+ def orphan(self):
+ """
+ Create a `GraphCursor` attached to nothing.
+
+ """
+ return self.get_cursor(None)
+
def index_of(self, mixed):
"""
Find the index based on various strategies for a node, probably an input or output of chain. Supported
@@ -115,10 +132,16 @@ class Graph:
raise ValueError("Cannot find node matching {!r}.".format(mixed))
def indexes_of(self, *things):
+ """
+ Returns the set of indexes of the things passed as arguments.
+
+ """
return set(map(self.index_of, things))
def outputs_of(self, idx_or_node, create=False):
- """Get a set of the outputs for a given node, node index or name.
+ """
+ Get a set of the outputs for a given node, node index or name.
+
"""
idx_or_node = self.index_of(idx_or_node)
@@ -127,8 +150,10 @@ class Graph:
return self.edges[idx_or_node]
def add_node(self, new_node, *, _name=None):
- """Add a node without connections in this graph and returns its index.
+ """
+ Add a node without connections in this graph and returns its index.
If _name is specified, name this node (string reference for further usage).
+
"""
idx = len(self.nodes)
self.edges[idx] = set()
@@ -149,7 +174,8 @@ class Graph:
return self.add_node(new_node, _name=_name)
def add_chain(self, *nodes, _input=BEGIN, _output=None, _name=None, use_existing_nodes=False):
- """Add `nodes` as a chain in this graph.
+ """
+ Add `nodes` as a chain in this graph.
**Input rules**
@@ -222,7 +248,9 @@ class Graph:
@property
def topologically_sorted_indexes(self):
- """Iterate in topological order, based on networkx's topological_sort() function.
+ """
+ Iterate in topological order, based on networkx's topological_sort() function.
+
"""
try:
return self._topologcally_sorted_indexes_cache
diff --git a/docs/guide/graphs.rst b/docs/guide/graphs.rst
index 67f8ce9..e6a83ba 100644
--- a/docs/guide/graphs.rst
+++ b/docs/guide/graphs.rst
@@ -201,8 +201,11 @@ positional parameters as you want.
.. note::
As of |bonobo| 0.7, a new syntax is available that we believe is more powerfull and more readable than the legacy
- `add_chain` method. The former API is here to stay and it's perfectly safe to use it, but if it is an option, you
- should consider the new syntax. During the transition period, we'll document both.
+ `add_chain` method. The former API is here to stay and it's perfectly safe to use it (in fact, the new syntax uses
+ `add_chain` under the hood).
+
+ If it is an option for you, we suggest you consider the new syntax. During the transition period, we'll document
+ both but the new syntax will eventually become default.
.. code-block:: python
@@ -393,6 +396,33 @@ You can also create single nodes, and the api provide the same capability on sin
graph.add_chain(..., _output="foo")
+Orphan nodes / chains
+:::::::::::::::::::::
+
+The default behaviour of `add_chain` (or `get_cursor`) is to connect the first node to the special `BEGIN` token, which
+instruct |bonobo| to call the connected node once without parameter to kickstart the data stream.
+
+This is normally what you want, but there are ways to override it, as you may want to add "orphan" nodes or chains to your graph.
+
+.. code-block:: python
+
+ import bonobo
+
+ graph = bonobo.Graph()
+
+ # using add_node will naturally add a node as "orphan"
+ graph.add_node(a)
+
+ # using add_chain with "None" as the input will create an orphan chain
+ graph.add_chain(a, b, c, _input=None)
+
+ # using the new syntax, you can use either get_cursor(None) or the orphan() shortcut
+ graph.get_cursor(None) >> a >> b >> c
+
+ # ... using the shortcut ...
+ graph.orphan() >> a >> b >> c
+
+
Connecting two nodes
::::::::::::::::::::
|
python-bonobo/bonobo
|
e5b115e5df400ceba9d76a5fb68c2b22cff0da6e
|
diff --git a/bonobo/util/testing.py b/bonobo/util/testing.py
index 13554f8..0c80e92 100644
--- a/bonobo/util/testing.py
+++ b/bonobo/util/testing.py
@@ -5,7 +5,7 @@ import os
import runpy
import sys
from contextlib import contextmanager, redirect_stderr, redirect_stdout
-from unittest.mock import patch
+from unittest.mock import patch, sentinel
import pytest
@@ -14,6 +14,7 @@ from bonobo.commands import entrypoint
from bonobo.execution.contexts.graph import GraphExecutionContext
from bonobo.execution.contexts.node import NodeExecutionContext
from bonobo.structs.tokens import Token
+from bonobo.util import tuplize
@contextmanager
@@ -26,6 +27,11 @@ def optional_contextmanager(cm, *, ignore=False):
class FilesystemTester:
+ """
+ Helper that create temporary filesystem service to be used in unit tests.
+
+ """
+
def __init__(self, extension="txt", mode="w", *, input_data=""):
self.extension = extension
self.input_data = input_data
@@ -43,6 +49,12 @@ class FilesystemTester:
class QueueList(list):
+ """
+ A list that behave like a queue (or is it the oposite?).
+
+ The datastructure is not smart at all, but it's quite useful for testing.
+ """
+
def append(self, item):
if not isinstance(item, Token):
super(QueueList, self).append(item)
@@ -51,6 +63,11 @@ class QueueList(list):
class BufferingContext:
+ """
+ Base class to add a buffer to a context.
+
+ """
+
def __init__(self, buffer=None):
if buffer is None:
buffer = QueueList()
@@ -64,12 +81,22 @@ class BufferingContext:
class BufferingNodeExecutionContext(BufferingContext, NodeExecutionContext):
+ """
+ Node execution context that actually stores the node outputs in a buffer, so one can test it afterward.
+
+ """
+
def __init__(self, *args, buffer=None, **kwargs):
BufferingContext.__init__(self, buffer)
NodeExecutionContext.__init__(self, *args, **kwargs, _outputs=[self.buffer])
class BufferingGraphExecutionContext(BufferingContext, GraphExecutionContext):
+ """
+ Graph execution context that uses buffering node execution contexts, all nodes buffering to the same buffer.
+
+ """
+
NodeExecutionContextType = BufferingNodeExecutionContext
def __init__(self, *args, buffer=None, **kwargs):
@@ -99,13 +126,13 @@ def runner(f):
@runner
def runner_entrypoint(args):
- """ Run bonobo using the python command entrypoint directly (bonobo.commands.entrypoint). """
+ """Run bonobo using the python command entrypoint directly (bonobo.commands.entrypoint). """
return entrypoint(args)
@runner
def runner_module(args):
- """ Run bonobo using the bonobo.__main__ file, which is equivalent as doing "python -m bonobo ..."."""
+ """Run bonobo using the bonobo.__main__ file, which is equivalent as doing "python -m bonobo ..."."""
with patch.object(sys, "argv", ["bonobo", *args]):
return runpy.run_path(__main__.__file__, run_name="__main__")
@@ -192,7 +219,10 @@ class ConfigurableNodeTest:
class ReaderTest(ConfigurableNodeTest):
- """ Helper class to test reader transformations. """
+ """
+ Helper class to test reader transformations.
+
+ """
ReaderNodeType = None
@@ -232,7 +262,10 @@ class ReaderTest(ConfigurableNodeTest):
class WriterTest(ConfigurableNodeTest):
- """ Helper class to test writer transformations. """
+ """
+ Helper class to test writer transformations.
+
+ """
WriterNodeType = None
@@ -255,3 +288,15 @@ class WriterTest(ConfigurableNodeTest):
def readlines(self):
with self.fs.open(self.filename) as fp:
return tuple(map(str.strip, fp.readlines()))
+
+
+@tuplize
+def get_pseudo_nodes(*names):
+ """
+ Generates a serie of named sentinels to test graph APIs.
+
+ >>> a, b, c = get_pseudo_nodes(*"abc")
+
+ """
+ for name in names:
+ yield getattr(sentinel, name)
diff --git a/tests/structs/test_graphs.py b/tests/structs/test_graphs.py
index 725ba61..5dcb10f 100644
--- a/tests/structs/test_graphs.py
+++ b/tests/structs/test_graphs.py
@@ -4,6 +4,7 @@ import pytest
from bonobo.constants import BEGIN
from bonobo.structs.graphs import Graph
+from bonobo.util.testing import get_pseudo_nodes
identity = lambda x: x
@@ -26,19 +27,21 @@ def test_graph_outputs_of():
def test_graph_index_of():
g = Graph()
- g.add_node(sentinel.foo)
- g.add_node(sentinel.bar)
+ foo, bar, not_there = get_pseudo_nodes("foo", "bar", "not_there")
+
+ g.add_node(foo)
+ g.add_node(bar)
# sequential, can resolve objects
- assert g.index_of(sentinel.foo) == 0
- assert g.index_of(sentinel.bar) == 1
+ assert g.index_of(foo) == 0
+ assert g.index_of(bar) == 1
# calling on an index should return the index
- assert g.index_of(sentinel.bar) == g.index_of(g.index_of(sentinel.bar))
+ assert g.index_of(bar) == g.index_of(g.index_of(bar))
# not existing should raise value error
with pytest.raises(ValueError):
- g.index_of(sentinel.not_there)
+ g.index_of(not_there)
# tokens resolve to themselves
assert g.index_of(BEGIN) == BEGIN
@@ -58,15 +61,16 @@ def test_graph_add_component():
def test_invalid_graph_usage():
g = Graph()
+ foo, bar = get_pseudo_nodes("foo", "bar")
with pytest.raises(ValueError):
g.add_chain()
- g.add_node(sentinel.foo)
- g.add_node(sentinel.bar)
+ g.add_node(foo)
+ g.add_node(bar)
with pytest.raises(RuntimeError):
- g.add_chain(_input=sentinel.bar, _output=sentinel.foo, _name="this_is_not_possible")
+ g.add_chain(_input=bar, _output=foo, _name="this_is_not_possible")
def test_graph_add_chain():
@@ -81,48 +85,51 @@ def test_graph_add_chain():
def test_graph_topological_sort():
g = Graph()
+ a1, a2, a3, b1, b2 = get_pseudo_nodes("a1", "a2", "a3", "b1", "b2")
- g.add_chain(sentinel.a1, sentinel.a2, sentinel.a3, _input=None, _output=None)
+ g.add_chain(a1, a2, a3, _input=None, _output=None)
assert g.topologically_sorted_indexes == (0, 1, 2)
- assert g[0] == sentinel.a1
- assert g[1] == sentinel.a2
- assert g[2] == sentinel.a3
+ assert g[0] == a1
+ assert g[1] == a2
+ assert g[2] == a3
- g.add_chain(sentinel.b1, sentinel.b2, _output=sentinel.a2)
+ g.add_chain(b1, b2, _output=a2)
assert g.topologically_sorted_indexes[-2:] == (1, 2)
assert g.topologically_sorted_indexes.index(3) < g.topologically_sorted_indexes.index(4)
- assert g[3] == sentinel.b1
- assert g[4] == sentinel.b2
+ assert g[3] == b1
+ assert g[4] == b2
def test_connect_two_chains():
g = Graph()
+ a1, a2, b1, b2 = get_pseudo_nodes("a1", "a2", "b1", "b2")
- g.add_chain(sentinel.a1, sentinel.a2, _input=None, _output=None)
- g.add_chain(sentinel.b1, sentinel.b2, _input=None, _output=None)
- assert len(g.outputs_of(sentinel.a2)) == 0
+ g.add_chain(a1, a2, _input=None, _output=None)
+ g.add_chain(b1, b2, _input=None, _output=None)
+ assert len(g.outputs_of(a2)) == 0
- g.add_chain(_input=sentinel.a2, _output=sentinel.b1)
- assert g.outputs_of(sentinel.a2) == {g.index_of(sentinel.b1)}
+ g.add_chain(_input=a2, _output=b1)
+ assert g.outputs_of(a2) == g.indexes_of(b1)
def test_connect_two_anonymous_nodes():
g = Graph()
+ a, b = get_pseudo_nodes(*"ab")
# Create two "anonymous" nodes
- g.add_node(sentinel.a)
- g.add_node(sentinel.b)
+ g.add_node(a)
+ g.add_node(b)
# Connect them
- g.add_chain(_input=sentinel.a, _output=sentinel.b)
+ g.add_chain(_input=a, _output=b)
def test_named_nodes():
g = Graph()
- a, b, c, d, e, f = sentinel.a, sentinel.b, sentinel.c, sentinel.d, sentinel.e, sentinel.f
+ a, b, c, d, e, f = get_pseudo_nodes(*"abcdef")
# Here we mark _input to None, so normalize won't get the "begin" impulsion.
g.add_chain(e, f, _input=None, _name="load")
diff --git a/tests/structs/test_graphs_new_syntax.py b/tests/structs/test_graphs_new_syntax.py
index 570fa47..68f0e74 100644
--- a/tests/structs/test_graphs_new_syntax.py
+++ b/tests/structs/test_graphs_new_syntax.py
@@ -1,17 +1,10 @@
from operator import attrgetter
-from unittest.mock import sentinel
import pytest
from bonobo.constants import BEGIN
from bonobo.structs.graphs import Graph, GraphCursor
-from bonobo.util import tuplize
-
-
-@tuplize
-def get_pseudo_nodes(*names):
- for name in names:
- yield getattr(sentinel, name)
+from bonobo.util.testing import get_pseudo_nodes
def test_get_cursor():
@@ -127,3 +120,23 @@ def test_cursor_merge():
assert g.outputs_of(c) == set()
assert c1 == c2
+
+
+def test_cursor_merge_orphan_in_between():
+ a, b, c, v, w, x, y = get_pseudo_nodes(*"abcdefg")
+ g = Graph()
+ g >> a >> b >> c
+ assert len(g) == 3
+ g.orphan() >> v >> w >> b
+ assert len(g) == 5
+ g.orphan() >> x >> y >> b
+ assert len(g) == 7
+
+ assert g.outputs_of(BEGIN) == g.indexes_of(a)
+ assert g.outputs_of(a) == g.indexes_of(b)
+ assert g.outputs_of(b) == g.indexes_of(c)
+ assert g.outputs_of(c) == set()
+ assert g.outputs_of(v) == g.indexes_of(w)
+ assert g.outputs_of(w) == g.indexes_of(b)
+ assert g.outputs_of(x) == g.indexes_of(y)
+ assert g.outputs_of(y) == g.indexes_of(b)
|
New Syntax: Forks
As a dev, I should be able to create a graph using new syntax that contain "forks" (one input, more than one output)
|
0.0
|
e5b115e5df400ceba9d76a5fb68c2b22cff0da6e
|
[
"tests/structs/test_graphs_new_syntax.py::test_cursor_merge_orphan_in_between"
] |
[
"tests/structs/test_graphs.py::test_graph_outputs_of",
"tests/structs/test_graphs.py::test_graph_index_of",
"tests/structs/test_graphs.py::test_graph_add_component",
"tests/structs/test_graphs.py::test_invalid_graph_usage",
"tests/structs/test_graphs.py::test_graph_add_chain",
"tests/structs/test_graphs.py::test_graph_topological_sort",
"tests/structs/test_graphs.py::test_connect_two_chains",
"tests/structs/test_graphs.py::test_connect_two_anonymous_nodes",
"tests/structs/test_graphs.py::test_named_nodes",
"tests/structs/test_graphs.py::test_copy",
"tests/structs/test_graphs_new_syntax.py::test_get_cursor",
"tests/structs/test_graphs_new_syntax.py::test_get_cursor_in_a_vacuum",
"tests/structs/test_graphs_new_syntax.py::test_cursor_usage_to_add_a_chain",
"tests/structs/test_graphs_new_syntax.py::test_cursor_usage_to_add_a_chain_in_a_context_manager",
"tests/structs/test_graphs_new_syntax.py::test_implicit_cursor_usage",
"tests/structs/test_graphs_new_syntax.py::test_cursor_to_fork_a_graph",
"tests/structs/test_graphs_new_syntax.py::test_cursor_to_fork_at_the_end",
"tests/structs/test_graphs_new_syntax.py::test_cursor_merge"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-06-02 06:55:06+00:00
|
apache-2.0
| 5,049 |
|
python-cmd2__cmd2-1069
|
diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py
index 21007289..ef35eabc 100644
--- a/cmd2/argparse_completer.py
+++ b/cmd2/argparse_completer.py
@@ -641,8 +641,11 @@ class ArgparseCompleter:
arg_choices.sort()
self._cmd2_app.matches_sorted = True
- # Since choices can be various types, convert them all to strings
- arg_choices = [str(x) for x in arg_choices]
+ # Since choices can be various types, make sure they are all strings
+ for index, choice in enumerate(arg_choices):
+ # Prevent converting anything that is already a str (i.e. CompletionItem)
+ if not isinstance(choice, str):
+ arg_choices[index] = str(choice)
else:
arg_choices = getattr(arg_state.action, ATTR_CHOICES_CALLABLE, None)
if arg_choices is None:
|
python-cmd2/cmd2
|
cc9d96a7c5309bec64856e4dd9554d2cee235d23
|
diff --git a/tests/test_argparse_completer.py b/tests/test_argparse_completer.py
index 75f24b3e..6002a856 100644
--- a/tests/test_argparse_completer.py
+++ b/tests/test_argparse_completer.py
@@ -107,6 +107,7 @@ class ArgparseCompleterTester(cmd2.Cmd):
int_choices = [-1, 1, -2, 2, 0, -12]
static_choices_list = ['static', 'choices', 'stop', 'here']
choices_from_provider = ['choices', 'provider', 'probably', 'improved']
+ completion_item_choices = [CompletionItem('choice_1', 'A description'), CompletionItem('choice_2', 'Another description')]
def choices_provider(self) -> List[str]:
"""Method that provides choices"""
@@ -150,6 +151,7 @@ class ArgparseCompleterTester(cmd2.Cmd):
nargs=argparse.ONE_OR_MORE,
)
choices_parser.add_argument('-i', '--int', type=int, help='a flag with an int type', choices=int_choices)
+ choices_parser.add_argument('--completion_items', help='choices are CompletionItems', choices=completion_item_choices)
# Positional args for choices command
choices_parser.add_argument("list_pos", help="a positional populated with a choices list", choices=static_choices_list)
@@ -729,6 +731,23 @@ def test_completion_items(ac_app, num_aliases, show_description):
assert 'help' in first_result_line
+def test_completion_item_choices(ac_app):
+ text = ''
+ line = 'choices --completion_items {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, ac_app)
+ assert first_match is not None
+ assert len(ac_app.completion_matches) == len(ac_app.completion_item_choices)
+ assert len(ac_app.display_matches) == len(ac_app.completion_item_choices)
+
+ # Make sure a completion table was created
+ first_result_line = normalize(ac_app.formatted_completions)[1]
+ assert 'choice_1' in first_result_line
+ assert 'A description' in first_result_line
+
+
@pytest.mark.parametrize(
'args, completions',
[
|
Argparse choices can't be CompletionItems
ArgparseCompleter is converting CompletionItems to normal strings when they appear in a choices list.
|
0.0
|
cc9d96a7c5309bec64856e4dd9554d2cee235d23
|
[
"tests/test_argparse_completer.py::test_completion_item_choices"
] |
[
"tests/test_argparse_completer.py::test_help[music]",
"tests/test_argparse_completer.py::test_help[music",
"tests/test_argparse_completer.py::test_bad_subcommand_help",
"tests/test_argparse_completer.py::test_complete_help[-mus-completions0]",
"tests/test_argparse_completer.py::test_complete_help[music-cre-completions1]",
"tests/test_argparse_completer.py::test_complete_help[music-creab-completions2]",
"tests/test_argparse_completer.py::test_complete_help[music",
"tests/test_argparse_completer.py::test_complete_help[fake",
"tests/test_argparse_completer.py::test_subcommand_completions[create--completions0]",
"tests/test_argparse_completer.py::test_subcommand_completions[create-ja-completions1]",
"tests/test_argparse_completer.py::test_subcommand_completions[create-foo-completions2]",
"tests/test_argparse_completer.py::test_subcommand_completions[creab-ja-completions3]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---completion_matches0-display_matches0]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag----completion_matches1-display_matches1]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--n-completion_matches2-display_matches2]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---n-completion_matches3-display_matches3]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--r-completion_matches5-display_matches5]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---rem-completion_matches6-display_matches6]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--s-completion_matches9-display_matches9]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---s-completion_matches10-display_matches10]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag-+-completion_matches13-display_matches13]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag-++-completion_matches14-display_matches14]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-l--completions0]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--list-s-completions1]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-p--completions2]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--provider-pr-completions3]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-i--completions4]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int-1-completions5]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int---completions6]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int--1-completions7]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[1--completions0]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[1-s-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[2--completions2]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[2-pr-completions3]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[3--completions4]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[3-2-completions5]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[4--completions6]",
"tests/test_argparse_completer.py::test_flag_sorting",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[-c--completions0]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[--completer-f-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[1--completions0]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[1-p-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[2--completions2]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[2-m-completions3]",
"tests/test_argparse_completer.py::test_autocomp_blank_token",
"tests/test_argparse_completer.py::test_completion_items[1-False]",
"tests/test_argparse_completer.py::test_completion_items[5-True]",
"tests/test_argparse_completer.py::test_completion_items[100-False]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--set_value-completions0]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--set_value",
"tests/test_argparse_completer.py::test_autcomp_nargs[--one_or_more-completions4]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--one_or_more",
"tests/test_argparse_completer.py::test_autcomp_nargs[--optional-completions6]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--optional",
"tests/test_argparse_completer.py::test_autcomp_nargs[--range-completions8]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--range",
"tests/test_argparse_completer.py::test_autcomp_nargs[--remainder-completions11]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--remainder",
"tests/test_argparse_completer.py::test_autcomp_nargs[--",
"tests/test_argparse_completer.py::test_autcomp_nargs[-completions17]",
"tests/test_argparse_completer.py::test_autcomp_nargs[positional-completions18]",
"tests/test_argparse_completer.py::test_autcomp_nargs[positional",
"tests/test_argparse_completer.py::test_autcomp_nargs[the",
"tests/test_argparse_completer.py::test_unfinished_flag_error[hint",
"tests/test_argparse_completer.py::test_unfinished_flag_error[nargs",
"tests/test_argparse_completer.py::test_completion_items_arg_header",
"tests/test_argparse_completer.py::test_completion_items_descriptive_header",
"tests/test_argparse_completer.py::test_autocomp_hint[hint--True]",
"tests/test_argparse_completer.py::test_autocomp_hint[hint",
"tests/test_argparse_completer.py::test_autocomp_hint[nargs",
"tests/test_argparse_completer.py::test_autocomp_hint[hint---False]",
"tests/test_argparse_completer.py::test_autocomp_hint_no_help_text",
"tests/test_argparse_completer.py::test_completion_error[--choice",
"tests/test_argparse_completer.py::test_completion_error[-completer]",
"tests/test_argparse_completer.py::test_arg_tokens[arg_tokens",
"tests/test_argparse_completer.py::test_complete_mutex_group[mutex--the",
"tests/test_argparse_completer.py::test_complete_mutex_group[mutex---fl----flag",
"tests/test_argparse_completer.py::test_complete_mutex_group[mutex",
"tests/test_argparse_completer.py::test_single_prefix_char",
"tests/test_argparse_completer.py::test_looks_like_flag",
"tests/test_argparse_completer.py::test_complete_command_no_tokens",
"tests/test_argparse_completer.py::test_complete_command_help_no_tokens",
"tests/test_argparse_completer.py::test_complete_standalone[--provider-completions0]",
"tests/test_argparse_completer.py::test_complete_standalone[--completer-completions1]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-02 22:15:02+00:00
|
mit
| 5,050 |
|
python-cmd2__cmd2-365
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c0c1601..d382fc75 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,6 @@
## 0.8.6 (TBD)
* Bug Fixes
- * TBD
+ * Commands using the @with_argparser_and_unknown_args were not correctly recognized when tab completing help
## 0.8.5 (April 15, 2018)
* Bug Fixes
diff --git a/cmd2.py b/cmd2.py
index ec07510e..4c91a6a5 100755
--- a/cmd2.py
+++ b/cmd2.py
@@ -420,8 +420,18 @@ def with_argparser_and_unknown_args(argparser):
# If there are subcommands, store their names in a list to support tab-completion of subcommand names
if argparser._subparsers is not None:
- subcommand_names = argparser._subparsers._group_actions[0]._name_parser_map.keys()
- cmd_wrapper.__dict__['subcommand_names'] = subcommand_names
+ # Key is subcommand name and value is completer function
+ subcommands = collections.OrderedDict()
+
+ # Get all subcommands and check if they have completer functions
+ for name, parser in argparser._subparsers._group_actions[0]._name_parser_map.items():
+ if 'completer' in parser._defaults:
+ completer = parser._defaults['completer']
+ else:
+ completer = None
+ subcommands[name] = completer
+
+ cmd_wrapper.__dict__['subcommands'] = subcommands
return cmd_wrapper
|
python-cmd2/cmd2
|
09b22c56266aad307744372a0dca8b57f43162bd
|
diff --git a/tests/conftest.py b/tests/conftest.py
index 837e7504..1433d425 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -8,9 +8,24 @@ Released under MIT license, see LICENSE file
import sys
from pytest import fixture
+try:
+ from unittest import mock
+except ImportError:
+ import mock
import cmd2
+# Prefer statically linked gnureadline if available (for macOS compatibility due to issues with libedit)
+try:
+ import gnureadline as readline
+except ImportError:
+ # Try to import readline, but allow failure for convenience in Windows unit testing
+ # Note: If this actually fails, you should install readline on Linux or Mac or pyreadline on Windows
+ try:
+ # noinspection PyUnresolvedReferences
+ import readline
+ except ImportError:
+ pass
# Help text for base cmd2.Cmd application
BASE_HELP = """Documented commands (type help <topic>):
@@ -141,3 +156,38 @@ def base_app():
c = cmd2.Cmd()
c.stdout = StdOut()
return c
+
+
+def complete_tester(text, line, begidx, endidx, app):
+ """
+ This is a convenience function to test cmd2.complete() since
+ in a unit test environment there is no actual console readline
+ is monitoring. Therefore we use mock to provide readline data
+ to complete().
+
+ :param text: str - the string prefix we are attempting to match
+ :param line: str - the current input line with leading whitespace removed
+ :param begidx: int - the beginning index of the prefix text
+ :param endidx: int - the ending index of the prefix text
+ :param app: the cmd2 app that will run completions
+ :return: The first matched string or None if there are no matches
+ Matches are stored in app.completion_matches
+ These matches also have been sorted by complete()
+ """
+ def get_line():
+ return line
+
+ def get_begidx():
+ return begidx
+
+ def get_endidx():
+ return endidx
+
+ first_match = None
+ with mock.patch.object(readline, 'get_line_buffer', get_line):
+ with mock.patch.object(readline, 'get_begidx', get_begidx):
+ with mock.patch.object(readline, 'get_endidx', get_endidx):
+ # Run the readline tab-completion function with readline mocks in place
+ first_match = app.complete(text, 0)
+
+ return first_match
diff --git a/tests/test_completion.py b/tests/test_completion.py
index b102bc0a..839e1de2 100644
--- a/tests/test_completion.py
+++ b/tests/test_completion.py
@@ -13,21 +13,8 @@ import os
import sys
import cmd2
-import mock
import pytest
-
-# Prefer statically linked gnureadline if available (for macOS compatibility due to issues with libedit)
-try:
- import gnureadline as readline
-except ImportError:
- # Try to import readline, but allow failure for convenience in Windows unit testing
- # Note: If this actually fails, you should install readline on Linux or Mac or pyreadline on Windows
- try:
- # noinspection PyUnresolvedReferences
- import readline
- except ImportError:
- pass
-
+from conftest import complete_tester
# List of strings used with completion functions
food_item_strs = ['Pizza', 'Ham', 'Ham Sandwich', 'Potato']
@@ -87,41 +74,6 @@ def cmd2_app():
return c
-def complete_tester(text, line, begidx, endidx, app):
- """
- This is a convenience function to test cmd2.complete() since
- in a unit test environment there is no actual console readline
- is monitoring. Therefore we use mock to provide readline data
- to complete().
-
- :param text: str - the string prefix we are attempting to match
- :param line: str - the current input line with leading whitespace removed
- :param begidx: int - the beginning index of the prefix text
- :param endidx: int - the ending index of the prefix text
- :param app: the cmd2 app that will run completions
- :return: The first matched string or None if there are no matches
- Matches are stored in app.completion_matches
- These matches also have been sorted by complete()
- """
- def get_line():
- return line
-
- def get_begidx():
- return begidx
-
- def get_endidx():
- return endidx
-
- first_match = None
- with mock.patch.object(readline, 'get_line_buffer', get_line):
- with mock.patch.object(readline, 'get_begidx', get_begidx):
- with mock.patch.object(readline, 'get_endidx', get_endidx):
- # Run the readline tab-completion function with readline mocks in place
- first_match = app.complete(text, 0)
-
- return first_match
-
-
def test_cmd2_command_completion_single(cmd2_app):
text = 'he'
line = text
@@ -911,6 +863,7 @@ def test_subcommand_tab_completion(sc_app):
# It is at end of line, so extra space is present
assert first_match is not None and sc_app.completion_matches == ['Football ']
+
def test_subcommand_tab_completion_with_no_completer(sc_app):
# This tests what happens when a subcommand has no completer
# In this case, the foo subcommand has no completer defined
@@ -922,6 +875,7 @@ def test_subcommand_tab_completion_with_no_completer(sc_app):
first_match = complete_tester(text, line, begidx, endidx, sc_app)
assert first_match is None
+
def test_subcommand_tab_completion_space_in_text(sc_app):
text = 'B'
line = 'base sport "Space {}'.format(text)
@@ -934,6 +888,179 @@ def test_subcommand_tab_completion_space_in_text(sc_app):
sc_app.completion_matches == ['Ball" '] and \
sc_app.display_matches == ['Space Ball']
+####################################################
+
+
+class SubcommandsWithUnknownExample(cmd2.Cmd):
+ """
+ Example cmd2 application where we a base command which has a couple subcommands
+ and the "sport" subcommand has tab completion enabled.
+ """
+
+ def __init__(self):
+ cmd2.Cmd.__init__(self)
+
+ # subcommand functions for the base command
+ def base_foo(self, args):
+ """foo subcommand of base command"""
+ self.poutput(args.x * args.y)
+
+ def base_bar(self, args):
+ """bar subcommand of base command"""
+ self.poutput('((%s))' % args.z)
+
+ def base_sport(self, args):
+ """sport subcommand of base command"""
+ self.poutput('Sport is {}'.format(args.sport))
+
+ # noinspection PyUnusedLocal
+ def complete_base_sport(self, text, line, begidx, endidx):
+ """ Adds tab completion to base sport subcommand """
+ index_dict = {1: sport_item_strs}
+ return self.index_based_complete(text, line, begidx, endidx, index_dict)
+
+ # create the top-level parser for the base command
+ base_parser = argparse.ArgumentParser(prog='base')
+ base_subparsers = base_parser.add_subparsers(title='subcommands', help='subcommand help')
+
+ # create the parser for the "foo" subcommand
+ parser_foo = base_subparsers.add_parser('foo', help='foo help')
+ parser_foo.add_argument('-x', type=int, default=1, help='integer')
+ parser_foo.add_argument('y', type=float, help='float')
+ parser_foo.set_defaults(func=base_foo)
+
+ # create the parser for the "bar" subcommand
+ parser_bar = base_subparsers.add_parser('bar', help='bar help')
+ parser_bar.add_argument('z', help='string')
+ parser_bar.set_defaults(func=base_bar)
+
+ # create the parser for the "sport" subcommand
+ parser_sport = base_subparsers.add_parser('sport', help='sport help')
+ parser_sport.add_argument('sport', help='Enter name of a sport')
+
+ # Set both a function and tab completer for the "sport" subcommand
+ parser_sport.set_defaults(func=base_sport, completer=complete_base_sport)
+
+ @cmd2.with_argparser_and_unknown_args(base_parser)
+ def do_base(self, args):
+ """Base command help"""
+ func = getattr(args, 'func', None)
+ if func is not None:
+ # Call whatever subcommand function was selected
+ func(self, args)
+ else:
+ # No subcommand was provided, so call help
+ self.do_help('base')
+
+ # Enable tab completion of base to make sure the subcommands' completers get called.
+ complete_base = cmd2.Cmd.cmd_with_subs_completer
+
+
[email protected]
+def scu_app():
+ """Declare test fixture for with_argparser_and_unknown_args"""
+ app = SubcommandsWithUnknownExample()
+ return app
+
+
+def test_cmd2_subcmd_with_unknown_completion_single_end(scu_app):
+ text = 'f'
+ line = 'base {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, scu_app)
+
+ # It is at end of line, so extra space is present
+ assert first_match is not None and scu_app.completion_matches == ['foo ']
+
+
+def test_cmd2_subcmd_with_unknown_completion_multiple(scu_app):
+ text = ''
+ line = 'base {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, scu_app)
+ assert first_match is not None and scu_app.completion_matches == ['bar', 'foo', 'sport']
+
+
+def test_cmd2_subcmd_with_unknown_completion_nomatch(scu_app):
+ text = 'z'
+ line = 'base {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, scu_app)
+ assert first_match is None
+
+
+def test_cmd2_help_subcommand_completion_single(scu_app):
+ text = 'base'
+ line = 'help {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+ assert scu_app.complete_help(text, line, begidx, endidx) == ['base']
+
+
+def test_cmd2_help_subcommand_completion_multiple(scu_app):
+ text = ''
+ line = 'help base {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ matches = sorted(scu_app.complete_help(text, line, begidx, endidx))
+ assert matches == ['bar', 'foo', 'sport']
+
+
+def test_cmd2_help_subcommand_completion_nomatch(scu_app):
+ text = 'z'
+ line = 'help base {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+ assert scu_app.complete_help(text, line, begidx, endidx) == []
+
+
+def test_subcommand_tab_completion(scu_app):
+ # This makes sure the correct completer for the sport subcommand is called
+ text = 'Foot'
+ line = 'base sport {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, scu_app)
+
+ # It is at end of line, so extra space is present
+ assert first_match is not None and scu_app.completion_matches == ['Football ']
+
+
+def test_subcommand_tab_completion_with_no_completer(scu_app):
+ # This tests what happens when a subcommand has no completer
+ # In this case, the foo subcommand has no completer defined
+ text = 'Foot'
+ line = 'base foo {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, scu_app)
+ assert first_match is None
+
+
+def test_subcommand_tab_completion_space_in_text(scu_app):
+ text = 'B'
+ line = 'base sport "Space {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, scu_app)
+
+ assert first_match is not None and \
+ scu_app.completion_matches == ['Ball" '] and \
+ scu_app.display_matches == ['Space Ball']
+
+####################################################
+
+
class SecondLevel(cmd2.Cmd):
"""To be used as a second level command class. """
|
Backport bug in help completion handling of commands using argparser_with_unknown_args
During the autocompleter development I found a bug in handling of help completion that affects the 0.8.x line so I'm going to port those changes back to the python2 branch.
|
0.0
|
09b22c56266aad307744372a0dca8b57f43162bd
|
[
"tests/test_completion.py::test_cmd2_help_subcommand_completion_multiple",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_nomatch",
"tests/test_completion.py::test_subcommand_tab_completion",
"tests/test_completion.py::test_subcommand_tab_completion_space_in_text",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_single_end",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_multiple"
] |
[
"tests/test_completion.py::test_cmd2_command_completion_single",
"tests/test_completion.py::test_complete_command_single",
"tests/test_completion.py::test_complete_empty_arg",
"tests/test_completion.py::test_complete_bogus_command",
"tests/test_completion.py::test_cmd2_command_completion_multiple",
"tests/test_completion.py::test_cmd2_command_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_completion_single",
"tests/test_completion.py::test_cmd2_help_completion_multiple",
"tests/test_completion.py::test_cmd2_help_completion_nomatch",
"tests/test_completion.py::test_shell_command_completion_shortcut",
"tests/test_completion.py::test_shell_command_completion_doesnt_match_wildcards",
"tests/test_completion.py::test_shell_command_completion_multiple",
"tests/test_completion.py::test_shell_command_completion_nomatch",
"tests/test_completion.py::test_shell_command_completion_doesnt_complete_when_just_shell",
"tests/test_completion.py::test_shell_command_completion_does_path_completion_when_after_command",
"tests/test_completion.py::test_path_completion_single_end",
"tests/test_completion.py::test_path_completion_multiple",
"tests/test_completion.py::test_path_completion_nomatch",
"tests/test_completion.py::test_default_to_shell_completion",
"tests/test_completion.py::test_path_completion_cwd",
"tests/test_completion.py::test_path_completion_doesnt_match_wildcards",
"tests/test_completion.py::test_path_completion_expand_user_dir",
"tests/test_completion.py::test_path_completion_user_expansion",
"tests/test_completion.py::test_path_completion_directories_only",
"tests/test_completion.py::test_basic_completion_single",
"tests/test_completion.py::test_basic_completion_multiple",
"tests/test_completion.py::test_basic_completion_nomatch",
"tests/test_completion.py::test_delimiter_completion",
"tests/test_completion.py::test_flag_based_completion_single",
"tests/test_completion.py::test_flag_based_completion_multiple",
"tests/test_completion.py::test_flag_based_completion_nomatch",
"tests/test_completion.py::test_flag_based_default_completer",
"tests/test_completion.py::test_flag_based_callable_completer",
"tests/test_completion.py::test_index_based_completion_single",
"tests/test_completion.py::test_index_based_completion_multiple",
"tests/test_completion.py::test_index_based_completion_nomatch",
"tests/test_completion.py::test_index_based_default_completer",
"tests/test_completion.py::test_index_based_callable_completer",
"tests/test_completion.py::test_tokens_for_completion_quoted",
"tests/test_completion.py::test_tokens_for_completion_unclosed_quote",
"tests/test_completion.py::test_tokens_for_completion_redirect",
"tests/test_completion.py::test_tokens_for_completion_quoted_redirect",
"tests/test_completion.py::test_tokens_for_completion_redirect_off",
"tests/test_completion.py::test_parseline_command_and_args",
"tests/test_completion.py::test_parseline_emptyline",
"tests/test_completion.py::test_parseline_strips_line",
"tests/test_completion.py::test_parseline_expands_alias",
"tests/test_completion.py::test_parseline_expands_shortcuts",
"tests/test_completion.py::test_add_opening_quote_basic_no_text",
"tests/test_completion.py::test_add_opening_quote_basic_nothing_added",
"tests/test_completion.py::test_add_opening_quote_basic_quote_added",
"tests/test_completion.py::test_add_opening_quote_basic_text_is_common_prefix",
"tests/test_completion.py::test_add_opening_quote_delimited_no_text",
"tests/test_completion.py::test_add_opening_quote_delimited_nothing_added",
"tests/test_completion.py::test_add_opening_quote_delimited_quote_added",
"tests/test_completion.py::test_add_opening_quote_delimited_text_is_common_prefix",
"tests/test_completion.py::test_add_opening_quote_delimited_space_in_prefix",
"tests/test_completion.py::test_cmd2_subcommand_completion_single_end",
"tests/test_completion.py::test_cmd2_subcommand_completion_multiple",
"tests/test_completion.py::test_cmd2_subcommand_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_single",
"tests/test_completion.py::test_subcommand_tab_completion_with_no_completer",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_nomatch",
"tests/test_completion.py::test_cmd2_submenu_completion_single_end",
"tests/test_completion.py::test_cmd2_submenu_completion_multiple",
"tests/test_completion.py::test_cmd2_submenu_completion_nomatch",
"tests/test_completion.py::test_cmd2_submenu_completion_after_submenu_match",
"tests/test_completion.py::test_cmd2_submenu_completion_after_submenu_nomatch",
"tests/test_completion.py::test_cmd2_help_submenu_completion_multiple",
"tests/test_completion.py::test_cmd2_help_submenu_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_submenu_completion_subcommands"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-04-20 16:21:27+00:00
|
mit
| 5,051 |
|
python-cmd2__cmd2-398
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 503f15e0..f9627194 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,7 @@
* Deleted ``cmd_with_subs_completer``, ``get_subcommands``, and ``get_subcommand_completer``
* Replaced by default AutoCompleter implementation for all commands using argparse
* Deleted support for old method of calling application commands with ``cmd()`` and ``self``
+ * ``cmd2.redirector`` is no longer supported. Output redirection can only be done with '>' or '>>'
* Python 2 no longer supported
* ``cmd2`` now supports Python 3.4+
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 02ae96fe..43fd99ec 100755
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -338,7 +338,6 @@ class Cmd(cmd.Cmd):
# Attributes used to configure the StatementParser, best not to change these at runtime
blankLinesAllowed = False
multiline_commands = []
- redirector = '>' # for sending output to file
shortcuts = {'?': 'help', '!': 'shell', '@': 'load', '@@': '_relative_load'}
aliases = dict()
terminators = [';']
@@ -1149,29 +1148,26 @@ class Cmd(cmd.Cmd):
if len(raw_tokens) > 1:
- # Build a list of all redirection tokens
- all_redirects = constants.REDIRECTION_CHARS + ['>>']
-
# Check if there are redirection strings prior to the token being completed
seen_pipe = False
has_redirection = False
for cur_token in raw_tokens[:-1]:
- if cur_token in all_redirects:
+ if cur_token in constants.REDIRECTION_TOKENS:
has_redirection = True
- if cur_token == '|':
+ if cur_token == constants.REDIRECTION_PIPE:
seen_pipe = True
# Get token prior to the one being completed
prior_token = raw_tokens[-2]
# If a pipe is right before the token being completed, complete a shell command as the piped process
- if prior_token == '|':
+ if prior_token == constants.REDIRECTION_PIPE:
return self.shell_cmd_complete(text, line, begidx, endidx)
# Otherwise do path completion either as files to redirectors or arguments to the piped process
- elif prior_token in all_redirects or seen_pipe:
+ elif prior_token in constants.REDIRECTION_TOKENS or seen_pipe:
return self.path_complete(text, line, begidx, endidx)
# If there were redirection strings anywhere on the command line, then we
@@ -1820,7 +1816,7 @@ class Cmd(cmd.Cmd):
# We want Popen to raise an exception if it fails to open the process. Thus we don't set shell to True.
try:
- self.pipe_proc = subprocess.Popen(shlex.split(statement.pipe_to), stdin=subproc_stdin)
+ self.pipe_proc = subprocess.Popen(statement.pipe_to, stdin=subproc_stdin)
except Exception as ex:
# Restore stdout to what it was and close the pipe
self.stdout.close()
@@ -1834,24 +1830,30 @@ class Cmd(cmd.Cmd):
raise ex
elif statement.output:
if (not statement.output_to) and (not can_clip):
- raise EnvironmentError('Cannot redirect to paste buffer; install ``xclip`` and re-run to enable')
+ raise EnvironmentError("Cannot redirect to paste buffer; install 'pyperclip' and re-run to enable")
self.kept_state = Statekeeper(self, ('stdout',))
self.kept_sys = Statekeeper(sys, ('stdout',))
self.redirecting = True
if statement.output_to:
+ # going to a file
mode = 'w'
- if statement.output == 2 * self.redirector:
+ # statement.output can only contain
+ # REDIRECTION_APPEND or REDIRECTION_OUTPUT
+ if statement.output == constants.REDIRECTION_APPEND:
mode = 'a'
sys.stdout = self.stdout = open(os.path.expanduser(statement.output_to), mode)
else:
+ # going to a paste buffer
sys.stdout = self.stdout = tempfile.TemporaryFile(mode="w+")
- if statement.output == '>>':
+ if statement.output == constants.REDIRECTION_APPEND:
self.poutput(get_paste_buffer())
def _restore_output(self, statement):
- """Handles restoring state after output redirection as well as the actual pipe operation if present.
+ """Handles restoring state after output redirection as well as
+ the actual pipe operation if present.
- :param statement: Statement object which contains the parsed input from the user
+ :param statement: Statement object which contains the parsed
+ input from the user
"""
# If we have redirected output to a file or the clipboard or piped it to a shell command, then restore state
if self.kept_state is not None:
diff --git a/cmd2/constants.py b/cmd2/constants.py
index 838650e5..b829000f 100644
--- a/cmd2/constants.py
+++ b/cmd2/constants.py
@@ -4,9 +4,14 @@
import re
-# Used for command parsing, tab completion and word breaks. Do not change.
+# Used for command parsing, output redirection, tab completion and word
+# breaks. Do not change.
QUOTES = ['"', "'"]
-REDIRECTION_CHARS = ['|', '>']
+REDIRECTION_PIPE = '|'
+REDIRECTION_OUTPUT = '>'
+REDIRECTION_APPEND = '>>'
+REDIRECTION_CHARS = [REDIRECTION_PIPE, REDIRECTION_OUTPUT]
+REDIRECTION_TOKENS = [REDIRECTION_PIPE, REDIRECTION_OUTPUT, REDIRECTION_APPEND]
# Regular expression to match ANSI escape codes
ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
diff --git a/cmd2/parsing.py b/cmd2/parsing.py
index 3a9b390b..ce15bd38 100644
--- a/cmd2/parsing.py
+++ b/cmd2/parsing.py
@@ -45,7 +45,8 @@ class Statement(str):
redirection, if any
:type suffix: str or None
:var pipe_to: if output was piped to a shell command, the shell command
- :type pipe_to: str or None
+ as a list of tokens
+ :type pipe_to: list
:var output: if output was redirected, the redirection token, i.e. '>>'
:type output: str or None
:var output_to: if output was redirected, the destination, usually a filename
@@ -283,12 +284,27 @@ class StatementParser:
argv = tokens
tokens = []
+ # check for a pipe to a shell process
+ # if there is a pipe, everything after the pipe needs to be passed
+ # to the shell, even redirected output
+ # this allows '(Cmd) say hello | wc > countit.txt'
+ try:
+ # find the first pipe if it exists
+ pipe_pos = tokens.index(constants.REDIRECTION_PIPE)
+ # save everything after the first pipe as tokens
+ pipe_to = tokens[pipe_pos+1:]
+ # remove all the tokens after the pipe
+ tokens = tokens[:pipe_pos]
+ except ValueError:
+ # no pipe in the tokens
+ pipe_to = None
+
# check for output redirect
output = None
output_to = None
try:
- output_pos = tokens.index('>')
- output = '>'
+ output_pos = tokens.index(constants.REDIRECTION_OUTPUT)
+ output = constants.REDIRECTION_OUTPUT
output_to = ' '.join(tokens[output_pos+1:])
# remove all the tokens after the output redirect
tokens = tokens[:output_pos]
@@ -296,26 +312,14 @@ class StatementParser:
pass
try:
- output_pos = tokens.index('>>')
- output = '>>'
+ output_pos = tokens.index(constants.REDIRECTION_APPEND)
+ output = constants.REDIRECTION_APPEND
output_to = ' '.join(tokens[output_pos+1:])
# remove all tokens after the output redirect
tokens = tokens[:output_pos]
except ValueError:
pass
- # check for pipes
- try:
- # find the first pipe if it exists
- pipe_pos = tokens.index('|')
- # save everything after the first pipe
- pipe_to = ' '.join(tokens[pipe_pos+1:])
- # remove all the tokens after the pipe
- tokens = tokens[:pipe_pos]
- except ValueError:
- # no pipe in the tokens
- pipe_to = None
-
if terminator:
# whatever is left is the suffix
suffix = ' '.join(tokens)
diff --git a/docs/freefeatures.rst b/docs/freefeatures.rst
index 95ae127c..a03a1d08 100644
--- a/docs/freefeatures.rst
+++ b/docs/freefeatures.rst
@@ -100,26 +100,8 @@ As in a Unix shell, output of a command can be redirected:
- appended to a file with ``>>``, as in ``mycommand args >> filename.txt``
- piped (``|``) as input to operating-system commands, as in
``mycommand args | wc``
- - sent to the paste buffer, ready for the next Copy operation, by
- ending with a bare ``>``, as in ``mycommand args >``.. Redirecting
- to paste buffer requires software to be installed on the operating
- system, pywin32_ on Windows or xclip_ on \*nix.
+ - sent to the operating system paste buffer, by ending with a bare ``>``, as in ``mycommand args >``. You can even append output to the current contents of the paste buffer by ending your command with ``>>``.
-If your application depends on mathematical syntax, ``>`` may be a bad
-choice for redirecting output - it will prevent you from using the
-greater-than sign in your actual user commands. You can override your
-app's value of ``self.redirector`` to use a different string for output redirection::
-
- class MyApp(cmd2.Cmd):
- redirector = '->'
-
-::
-
- (Cmd) say line1 -> out.txt
- (Cmd) say line2 ->-> out.txt
- (Cmd) !cat out.txt
- line1
- line2
.. note::
@@ -136,8 +118,8 @@ app's value of ``self.redirector`` to use a different string for output redirect
arguments after them from the command line arguments accordingly. But output from a command will not be redirected
to a file or piped to a shell command.
-.. _pywin32: http://sourceforge.net/projects/pywin32/
-.. _xclip: http://www.cyberciti.biz/faq/xclip-linux-insert-files-command-output-intoclipboard/
+If you need to include any of these redirection characters in your command,
+you can enclose them in quotation marks, ``mycommand 'with > in the argument'``.
Python
======
diff --git a/docs/unfreefeatures.rst b/docs/unfreefeatures.rst
index a4776a53..41144c8f 100644
--- a/docs/unfreefeatures.rst
+++ b/docs/unfreefeatures.rst
@@ -10,13 +10,17 @@ commands whose names are listed in the
parameter ``app.multiline_commands``. These
commands will be executed only
after the user has entered a *terminator*.
-By default, the command terminators is
+By default, the command terminator is
``;``; replacing or appending to the list
``app.terminators`` allows different
terminators. A blank line
is *always* considered a command terminator
(cannot be overridden).
+In multiline commands, output redirection characters
+like ``>`` and ``|`` are part of the command
+arguments unless they appear after the terminator.
+
Parsed statements
=================
|
python-cmd2/cmd2
|
9d4d929709ffbcfcbd0974d8193c44d514f5a9b4
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index bc76505f..6e4a5a3e 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -1430,7 +1430,7 @@ def test_clipboard_failure(capsys):
# Make sure we got the error output
out, err = capsys.readouterr()
assert out == ''
- assert 'Cannot redirect to paste buffer; install ``xclip`` and re-run to enable' in err
+ assert "Cannot redirect to paste buffer; install 'pyperclip' and re-run to enable" in err
class CmdResultApp(cmd2.Cmd):
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index bfb55b23..41966c71 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -159,7 +159,7 @@ def test_parse_simple_pipe(parser, line):
assert statement.command == 'simple'
assert not statement.args
assert statement.argv == ['simple']
- assert statement.pipe_to == 'piped'
+ assert statement.pipe_to == ['piped']
def test_parse_double_pipe_is_not_a_pipe(parser):
line = 'double-pipe || is not a pipe'
@@ -177,7 +177,7 @@ def test_parse_complex_pipe(parser):
assert statement.argv == ['command', 'with', 'args,', 'terminator']
assert statement.terminator == '&'
assert statement.suffix == 'sufx'
- assert statement.pipe_to == 'piped'
+ assert statement.pipe_to == ['piped']
@pytest.mark.parametrize('line,output', [
('help > out.txt', '>'),
@@ -227,9 +227,9 @@ def test_parse_pipe_and_redirect(parser):
assert statement.argv == ['output', 'into']
assert statement.terminator == ';'
assert statement.suffix == 'sufx'
- assert statement.pipe_to == 'pipethrume plz'
- assert statement.output == '>'
- assert statement.output_to == 'afile.txt'
+ assert statement.pipe_to == ['pipethrume', 'plz', '>', 'afile.txt']
+ assert not statement.output
+ assert not statement.output_to
def test_parse_output_to_paste_buffer(parser):
line = 'output to paste buffer >> '
@@ -240,8 +240,9 @@ def test_parse_output_to_paste_buffer(parser):
assert statement.output == '>>'
def test_parse_redirect_inside_terminator(parser):
- """The terminator designates the end of the commmand/arguments portion. If a redirector
- occurs before a terminator, then it will be treated as part of the arguments and not as a redirector."""
+ """The terminator designates the end of the commmand/arguments portion.
+ If a redirector occurs before a terminator, then it will be treated as
+ part of the arguments and not as a redirector."""
line = 'has > inside;'
statement = parser.parse(line)
assert statement.command == 'has'
@@ -385,7 +386,7 @@ def test_parse_alias_pipe(parser, line):
statement = parser.parse(line)
assert statement.command == 'help'
assert not statement.args
- assert statement.pipe_to == 'less'
+ assert statement.pipe_to == ['less']
def test_parse_alias_terminator_no_whitespace(parser):
line = 'helpalias;'
|
Cmd2.redirector isn't honored any more, either make it work or deprecate it
With the merge of PR #370, `Cmd2.redirector` is no longer honored: the redirector symbol is currently hard-coded as '>'. The documentation still states that you can set `Cmd2.redirector` to something like '->' and have the parsing logic honor that change. We need to either fix the code to match the documentation, or deprecate the attribute and fix the documentation to say that you can't change the redirector.
Related to #392.
|
0.0
|
9d4d929709ffbcfcbd0974d8193c44d514f5a9b4
|
[
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_parsing.py::test_parse_simple_pipe[simple",
"tests/test_parsing.py::test_parse_simple_pipe[simple|piped]",
"tests/test_parsing.py::test_parse_complex_pipe",
"tests/test_parsing.py::test_parse_pipe_and_redirect",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias|less]"
] |
[
"tests/test_cmd2.py::test_ver",
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_help_history",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_base_show_readonly",
"tests/test_cmd2.py::test_cast",
"tests/test_cmd2.py::test_cast_problems",
"tests/test_cmd2.py::test_base_set",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_quiet",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_base_py",
"tests/test_cmd2.py::test_base_run_python_script",
"tests/test_cmd2.py::test_base_run_pyscript",
"tests/test_cmd2.py::test_recursive_pyscript_not_allowed",
"tests/test_cmd2.py::test_pyscript_with_nonexist_file",
"tests/test_cmd2.py::test_pyscript_with_exception",
"tests/test_cmd2.py::test_pyscript_requires_an_argument",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_history_span",
"tests/test_cmd2.py::test_history_get",
"tests/test_cmd2.py::test_base_history",
"tests/test_cmd2.py::test_history_script_format",
"tests/test_cmd2.py::test_history_with_string_argument",
"tests/test_cmd2.py::test_history_with_integer_argument",
"tests/test_cmd2.py::test_history_with_integer_span",
"tests/test_cmd2.py::test_history_with_span_start",
"tests/test_cmd2.py::test_history_with_span_end",
"tests/test_cmd2.py::test_history_with_span_index_error",
"tests/test_cmd2.py::test_history_output_file",
"tests/test_cmd2.py::test_history_edit",
"tests/test_cmd2.py::test_history_run_all_commands",
"tests/test_cmd2.py::test_history_run_one_command",
"tests/test_cmd2.py::test_base_load",
"tests/test_cmd2.py::test_load_with_empty_args",
"tests/test_cmd2.py::test_load_with_nonexistent_file",
"tests/test_cmd2.py::test_load_with_empty_file",
"tests/test_cmd2.py::test_load_with_binary_file",
"tests/test_cmd2.py::test_load_with_utf8_file",
"tests/test_cmd2.py::test_load_nested_loads",
"tests/test_cmd2.py::test_base_runcmds_plus_hooks",
"tests/test_cmd2.py::test_base_relative_load",
"tests/test_cmd2.py::test_relative_load_requires_an_argument",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_allow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_base_colorize",
"tests/test_cmd2.py::test_edit_no_editor",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_exclude_from_history",
"tests/test_cmd2.py::test_base_cmdloop_with_queue",
"tests/test_cmd2.py::test_base_cmdloop_without_queue",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell_unknown",
"tests/test_cmd2.py::test_default_to_shell_good",
"tests/test_cmd2.py::test_default_to_shell_failure",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_cmdresult",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_eos",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false",
"tests/test_cmd2.py::test_raw_input",
"tests/test_cmd2.py::test_stdin_input",
"tests/test_cmd2.py::test_empty_stdin_input",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_alias",
"tests/test_cmd2.py::test_alias_lookup_invalid_alias",
"tests/test_cmd2.py::test_unalias",
"tests/test_cmd2.py::test_unalias_all",
"tests/test_cmd2.py::test_unalias_non_existing",
"tests/test_cmd2.py::test_create_invalid_alias[\">\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"no>pe\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"no",
"tests/test_cmd2.py::test_create_invalid_alias[\"nopipe|\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"noterm;\"]",
"tests/test_cmd2.py::test_create_invalid_alias[noembedded\"quotes]",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline",
"tests/test_parsing.py::test_parse_empty_string",
"tests/test_parsing.py::test_tokenize[command-tokens0]",
"tests/test_parsing.py::test_tokenize[command",
"tests/test_parsing.py::test_tokenize[42",
"tests/test_parsing.py::test_tokenize[l-tokens4]",
"tests/test_parsing.py::test_tokenize[termbare",
"tests/test_parsing.py::test_tokenize[termbare;",
"tests/test_parsing.py::test_tokenize[termbare&",
"tests/test_parsing.py::test_tokenize[help|less-tokens9]",
"tests/test_parsing.py::test_tokenize[l|less-tokens10]",
"tests/test_parsing.py::test_tokenize_unclosed_quotes",
"tests/test_parsing.py::test_command_and_args[tokens0-None-None]",
"tests/test_parsing.py::test_command_and_args[tokens1-command-None]",
"tests/test_parsing.py::test_command_and_args[tokens2-command-arg1",
"tests/test_parsing.py::test_parse_single_word[plainword]",
"tests/test_parsing.py::test_parse_single_word[\"one",
"tests/test_parsing.py::test_parse_single_word['one",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare;-;]",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare&-&]",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare;",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare&",
"tests/test_parsing.py::test_parse_command_with_args",
"tests/test_parsing.py::test_parse_command_with_quoted_args",
"tests/test_parsing.py::test_parse_command_with_args_terminator_and_suffix",
"tests/test_parsing.py::test_parse_hashcomment",
"tests/test_parsing.py::test_parse_c_comment",
"tests/test_parsing.py::test_parse_c_comment_empty",
"tests/test_parsing.py::test_parse_what_if_quoted_strings_seem_to_start_comments",
"tests/test_parsing.py::test_parse_double_pipe_is_not_a_pipe",
"tests/test_parsing.py::test_parse_redirect[help",
"tests/test_parsing.py::test_parse_redirect[help>out.txt->]",
"tests/test_parsing.py::test_parse_redirect[help>>out.txt->>]",
"tests/test_parsing.py::test_parse_redirect_with_args",
"tests/test_parsing.py::test_parse_redirect_with_dash_in_path",
"tests/test_parsing.py::test_parse_redirect_append",
"tests/test_parsing.py::test_parse_output_to_paste_buffer",
"tests/test_parsing.py::test_parse_redirect_inside_terminator",
"tests/test_parsing.py::test_parse_unfinished_multiliine_command",
"tests/test_parsing.py::test_parse_multiline_command_ignores_redirectors_within_it[multiline",
"tests/test_parsing.py::test_parse_multiline_with_incomplete_comment",
"tests/test_parsing.py::test_parse_multiline_with_complete_comment",
"tests/test_parsing.py::test_parse_multiline_termninated_by_empty_line",
"tests/test_parsing.py::test_parse_multiline_ignores_terminators_in_comments",
"tests/test_parsing.py::test_parse_command_with_unicode_args",
"tests/test_parsing.py::test_parse_unicode_command",
"tests/test_parsing.py::test_parse_redirect_to_unicode_filename",
"tests/test_parsing.py::test_parse_unclosed_quotes",
"tests/test_parsing.py::test_empty_statement_raises_exception",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias-help-None]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42-theanswer-None]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls-shell-ls]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[l-shell-ls",
"tests/test_parsing.py::test_parse_alias_on_multiline_command",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>out.txt->]",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>>out.txt->>]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace",
"tests/test_parsing.py::test_parse_command_only_command_and_args",
"tests/test_parsing.py::test_parse_command_only_emptyline",
"tests/test_parsing.py::test_parse_command_only_strips_line",
"tests/test_parsing.py::test_parse_command_only_expands_alias",
"tests/test_parsing.py::test_parse_command_only_expands_shortcuts",
"tests/test_parsing.py::test_parse_command_only_quoted_args",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>>out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help|less]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias;]",
"tests/test_parsing.py::test_parse_command_only_none[;]",
"tests/test_parsing.py::test_parse_command_only_none[>]",
"tests/test_parsing.py::test_parse_command_only_none[']",
"tests/test_parsing.py::test_parse_command_only_none[\"]",
"tests/test_parsing.py::test_parse_command_only_none[|]"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-10 17:18:31+00:00
|
mit
| 5,052 |
|
python-cmd2__cmd2-403
|
diff --git a/cmd2/parsing.py b/cmd2/parsing.py
index ce15bd38..655e0c58 100644
--- a/cmd2/parsing.py
+++ b/cmd2/parsing.py
@@ -250,23 +250,27 @@ class StatementParser:
tokens = self.tokenize(rawinput)
# of the valid terminators, find the first one to occur in the input
- terminator_pos = len(tokens)+1
- for test_terminator in self.terminators:
- try:
- pos = tokens.index(test_terminator)
- if pos < terminator_pos:
+ terminator_pos = len(tokens) + 1
+ for pos, cur_token in enumerate(tokens):
+ for test_terminator in self.terminators:
+ if cur_token.startswith(test_terminator):
terminator_pos = pos
terminator = test_terminator
+ # break the inner loop, and we want to break the
+ # outer loop too
break
- except ValueError:
- # the terminator is not in the tokens
- pass
+ else:
+ # this else clause is only run if the inner loop
+ # didn't execute a break. If it didn't, then
+ # continue to the next iteration of the outer loop
+ continue
+ # inner loop was broken, break the outer
+ break
if terminator:
if terminator == LINE_FEED:
terminator_pos = len(tokens)+1
- else:
- terminator_pos = tokens.index(terminator)
+
# everything before the first terminator is the command and the args
argv = tokens[:terminator_pos]
(command, args) = self._command_and_args(argv)
|
python-cmd2/cmd2
|
a9b712108e5af49937b0af3aa51db2ebe5c159e4
|
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index 41966c71..7b361b7e 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -250,6 +250,23 @@ def test_parse_redirect_inside_terminator(parser):
assert statement.argv == ['has', '>', 'inside']
assert statement.terminator == ';'
[email protected]('line,terminator',[
+ ('multiline with | inside;', ';'),
+ ('multiline with | inside ;', ';'),
+ ('multiline with | inside;;;', ';'),
+ ('multiline with | inside;; ;;', ';'),
+ ('multiline with | inside&', '&'),
+ ('multiline with | inside &;', '&'),
+ ('multiline with | inside&&;', '&'),
+ ('multiline with | inside &; &;', '&'),
+])
+def test_parse_multiple_terminators(parser, line, terminator):
+ statement = parser.parse(line)
+ assert statement.multiline_command == 'multiline'
+ assert statement.args == 'with | inside'
+ assert statement.argv == ['multiline', 'with', '|', 'inside']
+ assert statement.terminator == terminator
+
def test_parse_unfinished_multiliine_command(parser):
line = 'multiline has > inside an unfinished command'
statement = parser.parse(line)
@@ -261,7 +278,10 @@ def test_parse_unfinished_multiliine_command(parser):
@pytest.mark.parametrize('line,terminator',[
('multiline has > inside;', ';'),
+ ('multiline has > inside;;;', ';'),
+ ('multiline has > inside;; ;;', ';'),
('multiline has > inside &', '&'),
+ ('multiline has > inside & &', '&'),
])
def test_parse_multiline_command_ignores_redirectors_within_it(parser, line, terminator):
statement = parser.parse(line)
@@ -388,8 +408,15 @@ def test_parse_alias_pipe(parser, line):
assert not statement.args
assert statement.pipe_to == ['less']
-def test_parse_alias_terminator_no_whitespace(parser):
- line = 'helpalias;'
[email protected]('line', [
+ 'helpalias;',
+ 'helpalias;;',
+ 'helpalias;; ;',
+ 'helpalias ;',
+ 'helpalias ; ;',
+ 'helpalias ;; ;',
+])
+def test_parse_alias_terminator_no_whitespace(parser, line):
statement = parser.parse(line)
assert statement.command == 'help'
assert not statement.args
@@ -448,6 +475,8 @@ def test_parse_command_only_quoted_args(parser):
'helpalias>>out.txt',
'help|less',
'helpalias;',
+ 'help ;;',
+ 'help; ;;',
])
def test_parse_command_only_specialchars(parser, line):
statement = parser.parse_command_only(line)
@@ -455,6 +484,11 @@ def test_parse_command_only_specialchars(parser, line):
@pytest.mark.parametrize('line', [
';',
+ ';;',
+ ';; ;',
+ '&',
+ '& &',
+ ' && &',
'>',
"'",
'"',
|
Allow continuous run of terminators to end a multiline command
`test_cmd ;;;;;` (Results in a new line)
`test_cmd ;;;;; ;` (Completes the command)
Both of these input lines should complete the command.
|
0.0
|
a9b712108e5af49937b0af3aa51db2ebe5c159e4
|
[
"tests/test_parsing.py::test_parse_multiple_terminators[multiline",
"tests/test_parsing.py::test_parse_multiline_command_ignores_redirectors_within_it[multiline",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias"
] |
[
"tests/test_parsing.py::test_parse_empty_string",
"tests/test_parsing.py::test_tokenize[command-tokens0]",
"tests/test_parsing.py::test_tokenize[command",
"tests/test_parsing.py::test_tokenize[42",
"tests/test_parsing.py::test_tokenize[l-tokens4]",
"tests/test_parsing.py::test_tokenize[termbare",
"tests/test_parsing.py::test_tokenize[termbare;",
"tests/test_parsing.py::test_tokenize[termbare&",
"tests/test_parsing.py::test_tokenize[help|less-tokens9]",
"tests/test_parsing.py::test_tokenize[l|less-tokens10]",
"tests/test_parsing.py::test_tokenize_unclosed_quotes",
"tests/test_parsing.py::test_command_and_args[tokens0-None-None]",
"tests/test_parsing.py::test_command_and_args[tokens1-command-None]",
"tests/test_parsing.py::test_command_and_args[tokens2-command-arg1",
"tests/test_parsing.py::test_parse_single_word[plainword]",
"tests/test_parsing.py::test_parse_single_word[\"one",
"tests/test_parsing.py::test_parse_single_word['one",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare;-;]",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare&-&]",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare;",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare&",
"tests/test_parsing.py::test_parse_command_with_args",
"tests/test_parsing.py::test_parse_command_with_quoted_args",
"tests/test_parsing.py::test_parse_command_with_args_terminator_and_suffix",
"tests/test_parsing.py::test_parse_hashcomment",
"tests/test_parsing.py::test_parse_c_comment",
"tests/test_parsing.py::test_parse_c_comment_empty",
"tests/test_parsing.py::test_parse_what_if_quoted_strings_seem_to_start_comments",
"tests/test_parsing.py::test_parse_simple_pipe[simple",
"tests/test_parsing.py::test_parse_simple_pipe[simple|piped]",
"tests/test_parsing.py::test_parse_double_pipe_is_not_a_pipe",
"tests/test_parsing.py::test_parse_complex_pipe",
"tests/test_parsing.py::test_parse_redirect[help",
"tests/test_parsing.py::test_parse_redirect[help>out.txt->]",
"tests/test_parsing.py::test_parse_redirect[help>>out.txt->>]",
"tests/test_parsing.py::test_parse_redirect_with_args",
"tests/test_parsing.py::test_parse_redirect_with_dash_in_path",
"tests/test_parsing.py::test_parse_redirect_append",
"tests/test_parsing.py::test_parse_pipe_and_redirect",
"tests/test_parsing.py::test_parse_output_to_paste_buffer",
"tests/test_parsing.py::test_parse_redirect_inside_terminator",
"tests/test_parsing.py::test_parse_unfinished_multiliine_command",
"tests/test_parsing.py::test_parse_multiline_with_incomplete_comment",
"tests/test_parsing.py::test_parse_multiline_with_complete_comment",
"tests/test_parsing.py::test_parse_multiline_termninated_by_empty_line",
"tests/test_parsing.py::test_parse_multiline_ignores_terminators_in_comments",
"tests/test_parsing.py::test_parse_command_with_unicode_args",
"tests/test_parsing.py::test_parse_unicode_command",
"tests/test_parsing.py::test_parse_redirect_to_unicode_filename",
"tests/test_parsing.py::test_parse_unclosed_quotes",
"tests/test_parsing.py::test_empty_statement_raises_exception",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias-help-None]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42-theanswer-None]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls-shell-ls]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[l-shell-ls",
"tests/test_parsing.py::test_parse_alias_on_multiline_command",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>out.txt->]",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>>out.txt->>]",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias|less]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;]",
"tests/test_parsing.py::test_parse_command_only_command_and_args",
"tests/test_parsing.py::test_parse_command_only_emptyline",
"tests/test_parsing.py::test_parse_command_only_strips_line",
"tests/test_parsing.py::test_parse_command_only_expands_alias",
"tests/test_parsing.py::test_parse_command_only_expands_shortcuts",
"tests/test_parsing.py::test_parse_command_only_quoted_args",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>>out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help|less]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias;]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help",
"tests/test_parsing.py::test_parse_command_only_specialchars[help;",
"tests/test_parsing.py::test_parse_command_only_none[;]",
"tests/test_parsing.py::test_parse_command_only_none[;;]",
"tests/test_parsing.py::test_parse_command_only_none[;;",
"tests/test_parsing.py::test_parse_command_only_none[&]",
"tests/test_parsing.py::test_parse_command_only_none[&",
"tests/test_parsing.py::test_parse_command_only_none[",
"tests/test_parsing.py::test_parse_command_only_none[>]",
"tests/test_parsing.py::test_parse_command_only_none[']",
"tests/test_parsing.py::test_parse_command_only_none[\"]",
"tests/test_parsing.py::test_parse_command_only_none[|]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-16 04:23:38+00:00
|
mit
| 5,053 |
|
python-cmd2__cmd2-409
|
diff --git a/cmd2/argcomplete_bridge.py b/cmd2/argcomplete_bridge.py
index a036af1e..0ac68f1c 100644
--- a/cmd2/argcomplete_bridge.py
+++ b/cmd2/argcomplete_bridge.py
@@ -6,11 +6,16 @@ try:
import argcomplete
except ImportError: # pragma: no cover
# not installed, skip the rest of the file
- pass
-
+ DEFAULT_COMPLETER = None
else:
# argcomplete is installed
+ # Newer versions of argcomplete have FilesCompleter at top level, older versions only have it under completers
+ try:
+ DEFAULT_COMPLETER = argcomplete.FilesCompleter()
+ except AttributeError:
+ DEFAULT_COMPLETER = argcomplete.completers.FilesCompleter()
+
from contextlib import redirect_stdout
import copy
from io import StringIO
@@ -102,7 +107,7 @@ else:
def __call__(self, argument_parser, completer=None, always_complete_options=True, exit_method=os._exit, output_stream=None,
exclude=None, validator=None, print_suppressed=False, append_space=None,
- default_completer=argcomplete.FilesCompleter()):
+ default_completer=DEFAULT_COMPLETER):
"""
:param argument_parser: The argument parser to autocomplete on
:type argument_parser: :class:`argparse.ArgumentParser`
@@ -140,9 +145,14 @@ else:
added to argcomplete.safe_actions, if their values are wanted in the ``parsed_args`` completer argument, or
their execution is otherwise desirable.
"""
- self.__init__(argument_parser, always_complete_options=always_complete_options, exclude=exclude,
- validator=validator, print_suppressed=print_suppressed, append_space=append_space,
- default_completer=default_completer)
+ # Older versions of argcomplete have fewer keyword arguments
+ if sys.version_info >= (3, 5):
+ self.__init__(argument_parser, always_complete_options=always_complete_options, exclude=exclude,
+ validator=validator, print_suppressed=print_suppressed, append_space=append_space,
+ default_completer=default_completer)
+ else:
+ self.__init__(argument_parser, always_complete_options=always_complete_options, exclude=exclude,
+ validator=validator, print_suppressed=print_suppressed)
if "_ARGCOMPLETE" not in os.environ:
# not an argument completion invocation
diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py
index a8a0f24a..1995b8d5 100755
--- a/cmd2/argparse_completer.py
+++ b/cmd2/argparse_completer.py
@@ -472,8 +472,23 @@ class AutoCompleter(object):
if action.dest in self._arg_choices:
arg_choices = self._arg_choices[action.dest]
- if isinstance(arg_choices, tuple) and len(arg_choices) > 0 and callable(arg_choices[0]):
- completer = arg_choices[0]
+ # if arg_choices is a tuple
+ # Let's see if it's a custom completion function. If it is, return what it provides
+ # To do this, we make sure the first element is either a callable
+ # or it's the name of a callable in the application
+ if isinstance(arg_choices, tuple) and len(arg_choices) > 0 and \
+ (callable(arg_choices[0]) or
+ (isinstance(arg_choices[0], str) and hasattr(self._cmd2_app, arg_choices[0]) and
+ callable(getattr(self._cmd2_app, arg_choices[0]))
+ )
+ ):
+
+ if callable(arg_choices[0]):
+ completer = arg_choices[0]
+ elif isinstance(arg_choices[0], str) and callable(getattr(self._cmd2_app, arg_choices[0])):
+ completer = getattr(self._cmd2_app, arg_choices[0])
+
+ # extract the positional and keyword arguments from the tuple
list_args = None
kw_args = None
for index in range(1, len(arg_choices)):
@@ -481,14 +496,19 @@ class AutoCompleter(object):
list_args = arg_choices[index]
elif isinstance(arg_choices[index], dict):
kw_args = arg_choices[index]
- if list_args is not None and kw_args is not None:
- return completer(text, line, begidx, endidx, *list_args, **kw_args)
- elif list_args is not None:
- return completer(text, line, begidx, endidx, *list_args)
- elif kw_args is not None:
- return completer(text, line, begidx, endidx, **kw_args)
- else:
- return completer(text, line, begidx, endidx)
+ try:
+ # call the provided function differently depending on the provided positional and keyword arguments
+ if list_args is not None and kw_args is not None:
+ return completer(text, line, begidx, endidx, *list_args, **kw_args)
+ elif list_args is not None:
+ return completer(text, line, begidx, endidx, *list_args)
+ elif kw_args is not None:
+ return completer(text, line, begidx, endidx, **kw_args)
+ else:
+ return completer(text, line, begidx, endidx)
+ except TypeError:
+ # assume this is due to an incorrect function signature, return nothing.
+ return []
else:
return AutoCompleter.basic_complete(text, line, begidx, endidx,
self._resolve_choices_for_arg(action, used_values))
@@ -499,6 +519,16 @@ class AutoCompleter(object):
if action.dest in self._arg_choices:
args = self._arg_choices[action.dest]
+ # is the argument a string? If so, see if we can find an attribute in the
+ # application matching the string.
+ if isinstance(args, str):
+ try:
+ args = getattr(self._cmd2_app, args)
+ except AttributeError:
+ # Couldn't find anything matching the name
+ return []
+
+ # is the provided argument a callable. If so, call it
if callable(args):
try:
if self._cmd2_app is not None:
@@ -535,7 +565,10 @@ class AutoCompleter(object):
prefix = '{}{}'.format(flags, param)
else:
- prefix = '{}'.format(str(action.dest).upper())
+ if action.dest != SUPPRESS:
+ prefix = '{}'.format(str(action.dest).upper())
+ else:
+ prefix = ''
prefix = ' {0: <{width}} '.format(prefix, width=20)
pref_len = len(prefix)
diff --git a/cmd2/pyscript_bridge.py b/cmd2/pyscript_bridge.py
index 277d8531..196be82b 100644
--- a/cmd2/pyscript_bridge.py
+++ b/cmd2/pyscript_bridge.py
@@ -230,7 +230,7 @@ class ArgparseFunctor:
if action.option_strings:
cmd_str[0] += '{} '.format(action.option_strings[0])
- if isinstance(value, List) or isinstance(value, Tuple):
+ if isinstance(value, List) or isinstance(value, tuple):
for item in value:
item = str(item).strip()
if ' ' in item:
@@ -250,7 +250,7 @@ class ArgparseFunctor:
cmd_str[0] += '{} '.format(self._args[action.dest])
traverse_parser(action.choices[self._args[action.dest]])
elif isinstance(action, argparse._AppendAction):
- if isinstance(self._args[action.dest], List) or isinstance(self._args[action.dest], Tuple):
+ if isinstance(self._args[action.dest], list) or isinstance(self._args[action.dest], tuple):
for values in self._args[action.dest]:
process_flag(action, values)
else:
diff --git a/examples/tab_autocompletion.py b/examples/tab_autocompletion.py
index f3302533..adfe9702 100755
--- a/examples/tab_autocompletion.py
+++ b/examples/tab_autocompletion.py
@@ -96,6 +96,15 @@ class TabCompleteExample(cmd2.Cmd):
},
}
+ file_list = \
+ [
+ '/home/user/file.db',
+ '/home/user/file space.db',
+ '/home/user/another.db',
+ '/home/other user/maps.db',
+ '/home/other user/tests.db'
+ ]
+
def instance_query_actors(self) -> List[str]:
"""Simulating a function that queries and returns a completion values"""
return actors
@@ -225,9 +234,23 @@ class TabCompleteExample(cmd2.Cmd):
required=True)
actor_action = vid_movies_add_parser.add_argument('actor', help='Actors', nargs='*')
+ vid_movies_load_parser = vid_movies_commands_subparsers.add_parser('load')
+ vid_movie_file_action = vid_movies_load_parser.add_argument('movie_file', help='Movie database')
+
+ vid_movies_read_parser = vid_movies_commands_subparsers.add_parser('read')
+ vid_movie_fread_action = vid_movies_read_parser.add_argument('movie_file', help='Movie database')
+
# tag the action objects with completion providers. This can be a collection or a callable
setattr(director_action, argparse_completer.ACTION_ARG_CHOICES, static_list_directors)
- setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, instance_query_actors)
+ setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, 'instance_query_actors')
+
+ # tag the file property with a custom completion function 'delimeter_complete' provided by cmd2.
+ setattr(vid_movie_file_action, argparse_completer.ACTION_ARG_CHOICES,
+ ('delimiter_complete',
+ {'delimiter': '/',
+ 'match_against': file_list}))
+ setattr(vid_movie_fread_action, argparse_completer.ACTION_ARG_CHOICES,
+ ('path_complete', [False, False]))
vid_movies_delete_parser = vid_movies_commands_subparsers.add_parser('delete')
@@ -306,6 +329,9 @@ class TabCompleteExample(cmd2.Cmd):
movies_delete_parser = movies_commands_subparsers.add_parser('delete')
+ movies_load_parser = movies_commands_subparsers.add_parser('load')
+ movie_file_action = movies_load_parser.add_argument('movie_file', help='Movie database')
+
shows_parser = media_types_subparsers.add_parser('shows')
shows_parser.set_defaults(func=_do_media_shows)
@@ -333,7 +359,8 @@ class TabCompleteExample(cmd2.Cmd):
def complete_media(self, text, line, begidx, endidx):
""" Adds tab completion to media"""
choices = {'actor': query_actors, # function
- 'director': TabCompleteExample.static_list_directors # static list
+ 'director': TabCompleteExample.static_list_directors, # static list
+ 'movie_file': (self.path_complete, [False, False])
}
completer = argparse_completer.AutoCompleter(TabCompleteExample.media_parser, arg_choices=choices)
|
python-cmd2/cmd2
|
a38e3f26887f60a358a5e36421a52526a04637f5
|
diff --git a/tests/test_autocompletion.py b/tests/test_autocompletion.py
index 1d0c9678..e0a71831 100644
--- a/tests/test_autocompletion.py
+++ b/tests/test_autocompletion.py
@@ -168,7 +168,7 @@ def test_autocomp_subcmd_nested(cmd2_app):
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
assert first_match is not None and \
- cmd2_app.completion_matches == ['add', 'delete', 'list']
+ cmd2_app.completion_matches == ['add', 'delete', 'list', 'load']
def test_autocomp_subcmd_flag_choices_append(cmd2_app):
@@ -246,7 +246,7 @@ def test_autcomp_pos_consumed(cmd2_app):
def test_autcomp_pos_after_flag(cmd2_app):
text = 'Joh'
- line = 'media movies add -d "George Lucas" -- "Han Solo" PG "Emilia Clarke" "{}'.format(text)
+ line = 'video movies add -d "George Lucas" -- "Han Solo" PG "Emilia Clarke" "{}'.format(text)
endidx = len(line)
begidx = endidx - len(text)
diff --git a/tests/test_bashcompletion.py b/tests/test_bashcompletion.py
index ceae2aa9..298bdf1e 100644
--- a/tests/test_bashcompletion.py
+++ b/tests/test_bashcompletion.py
@@ -139,15 +139,13 @@ def test_invalid_ifs(parser1, mock):
@pytest.mark.parametrize('comp_line, exp_out, exp_err', [
('media ', 'movies\013shows', ''),
('media mo', 'movies', ''),
+ ('media movies list -a "J', '"John Boyega"\013"Jake Lloyd"', ''),
+ ('media movies list ', '', ''),
('media movies add ', '\013\013 ', '''
Hint:
TITLE Movie Title'''),
- ('media movies list -a "J', '"John Boyega"\013"Jake Lloyd"', ''),
- ('media movies list ', '', '')
])
def test_commands(parser1, capfd, mock, comp_line, exp_out, exp_err):
- completer = CompletionFinder()
-
mock.patch.dict(os.environ, {'_ARGCOMPLETE': '1',
'_ARGCOMPLETE_IFS': '\013',
'COMP_TYPE': '63',
@@ -157,6 +155,8 @@ def test_commands(parser1, capfd, mock, comp_line, exp_out, exp_err):
mock.patch.object(os, 'fdopen', my_fdopen)
with pytest.raises(SystemExit):
+ completer = CompletionFinder()
+
choices = {'actor': query_actors, # function
}
autocompleter = AutoCompleter(parser1, arg_choices=choices)
|
Autocompleter - type invalid text for a subcommand and press tab and ==SUPPRESS== is displayed.
Type invalid text for a subcommand and press tab and ==SUPPRESS== is displayed.
If the text typed doesn't match anything in the subcommand list for a command, autocompleter attempts to print the Hint for the parameter. For a subcommand that comes out as == SUPPRESS ==.
|
0.0
|
a38e3f26887f60a358a5e36421a52526a04637f5
|
[
"tests/test_autocompletion.py::test_autocomp_subcmd_nested"
] |
[
"tests/test_autocompletion.py::test_help_required_group",
"tests/test_autocompletion.py::test_help_required_group_long",
"tests/test_autocompletion.py::test_autocomp_flags",
"tests/test_autocompletion.py::test_autcomp_hint",
"tests/test_autocompletion.py::test_autcomp_flag_comp",
"tests/test_autocompletion.py::test_autocomp_flags_choices",
"tests/test_autocompletion.py::test_autcomp_hint_in_narg_range",
"tests/test_autocompletion.py::test_autocomp_flags_narg_max",
"tests/test_autocompletion.py::test_autcomp_narg_beyond_max",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_choices_append",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_choices_append_exclude",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_func",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_list",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_func_attr",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_list_attr",
"tests/test_autocompletion.py::test_autcomp_pos_consumed",
"tests/test_autocompletion.py::test_autcomp_pos_after_flag",
"tests/test_autocompletion.py::test_autcomp_custom_func_list_arg",
"tests/test_autocompletion.py::test_autcomp_custom_func_list_and_dict_arg"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-19 20:12:22+00:00
|
mit
| 5,054 |
|
python-cmd2__cmd2-424
|
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index b6e7cf19..2d8766f4 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -124,7 +124,7 @@ try:
except ImportError:
ipython_available = False
-__version__ = '0.9.1'
+__version__ = '0.9.2a'
# optional attribute, when tagged on a function, allows cmd2 to categorize commands
diff --git a/docs/conf.py b/docs/conf.py
index 997405dd..25ba2a78 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -62,7 +62,7 @@ author = 'Catherine Devlin and Todd Leonhardt'
# The short X.Y version.
version = '0.9'
# The full version, including alpha/beta/rc tags.
-release = '0.9.1'
+release = '0.9.2a'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff --git a/setup.py b/setup.py
index 0127ae5b..59c53b68 100755
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ Setuptools setup file, used to install or test 'cmd2'
"""
from setuptools import setup
-VERSION = '0.9.1'
+VERSION = '0.9.2a'
DESCRIPTION = "cmd2 - a tool for building interactive command line applications in Python"
LONG_DESCRIPTION = """cmd2 is a tool for building interactive command line applications in Python. Its goal is to make
it quick and easy for developers to build feature-rich and user-friendly interactive command line applications. It
@@ -73,7 +73,7 @@ EXTRAS_REQUIRE = {
# install with 'pip install -e .[dev]'
'dev': [
'pytest', 'pytest-cov', 'tox', 'pylint', 'sphinx', 'sphinx-rtd-theme',
- 'sphinx-autobuild','invoke', 'twine',
+ 'sphinx-autobuild', 'invoke', 'twine>=1.11',
]
}
diff --git a/tasks.py b/tasks.py
index 000af0a5..5c0bd772 100644
--- a/tasks.py
+++ b/tasks.py
@@ -1,7 +1,12 @@
#
# coding=utf-8
-"""Development related tasks to be run with 'invoke'"""
+"""Development related tasks to be run with 'invoke'.
+Make sure you satisfy the following Python module requirements if you are trying to publish a release to PyPI:
+ - twine >= 1.11.0
+ - wheel >= 0.31.0
+ - setuptools >= 39.1.0
+"""
import os
import shutil
|
python-cmd2/cmd2
|
7000604ac826a637539c388ad8f5ff8a3ebfc419
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index 33d9ca41..68aa0b98 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -28,7 +28,7 @@ from .conftest import run_cmd, normalize, BASE_HELP, BASE_HELP_VERBOSE, \
def test_ver():
- assert cmd2.__version__ == '0.9.1'
+ assert cmd2.__version__ == '0.9.2a'
def test_empty_statement(base_app):
|
Fix twine upload
Running the new **invoke pypi** command to build and upload a release to PyPI fails in the very last step with the following error message:
```sh
Uploading distributions to https://pypi.python.org/pypi
Note: you are uploading to the old upload URL. It's recommended to use the new URL "https://upload.pypi.org/legacy/" or to leave the URL unspecified and allow twine to choose.
Uploading cmd2-0.9.0.post1-py3-none-any.whl
100%|██████████| 76.8k/76.8k [00:00<00:00, 721kB/s]
RedirectDetected: "https://pypi.python.org/pypi" attempted to redirect to "https://pypi.org/pypi" during upload. Aborting...
```
The command being executed when this occurs is:
```sh
twine upload dist/*
```
|
0.0
|
7000604ac826a637539c388ad8f5ff8a3ebfc419
|
[
"tests/test_cmd2.py::test_ver"
] |
[
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_help_history",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_base_show_readonly",
"tests/test_cmd2.py::test_cast",
"tests/test_cmd2.py::test_cast_problems",
"tests/test_cmd2.py::test_base_set",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_quiet",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_base_py",
"tests/test_cmd2.py::test_base_run_python_script",
"tests/test_cmd2.py::test_base_run_pyscript",
"tests/test_cmd2.py::test_recursive_pyscript_not_allowed",
"tests/test_cmd2.py::test_pyscript_with_nonexist_file",
"tests/test_cmd2.py::test_pyscript_with_exception",
"tests/test_cmd2.py::test_pyscript_requires_an_argument",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_history_span",
"tests/test_cmd2.py::test_history_get",
"tests/test_cmd2.py::test_base_history",
"tests/test_cmd2.py::test_history_script_format",
"tests/test_cmd2.py::test_history_with_string_argument",
"tests/test_cmd2.py::test_history_with_integer_argument",
"tests/test_cmd2.py::test_history_with_integer_span",
"tests/test_cmd2.py::test_history_with_span_start",
"tests/test_cmd2.py::test_history_with_span_end",
"tests/test_cmd2.py::test_history_with_span_index_error",
"tests/test_cmd2.py::test_history_output_file",
"tests/test_cmd2.py::test_history_edit",
"tests/test_cmd2.py::test_history_run_all_commands",
"tests/test_cmd2.py::test_history_run_one_command",
"tests/test_cmd2.py::test_base_load",
"tests/test_cmd2.py::test_load_with_empty_args",
"tests/test_cmd2.py::test_load_with_nonexistent_file",
"tests/test_cmd2.py::test_load_with_empty_file",
"tests/test_cmd2.py::test_load_with_binary_file",
"tests/test_cmd2.py::test_load_with_utf8_file",
"tests/test_cmd2.py::test_load_nested_loads",
"tests/test_cmd2.py::test_base_runcmds_plus_hooks",
"tests/test_cmd2.py::test_base_relative_load",
"tests/test_cmd2.py::test_relative_load_requires_an_argument",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_allow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_base_colorize",
"tests/test_cmd2.py::test_edit_no_editor",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_exclude_from_history",
"tests/test_cmd2.py::test_base_cmdloop_with_queue",
"tests/test_cmd2.py::test_base_cmdloop_without_queue",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell_unknown",
"tests/test_cmd2.py::test_default_to_shell_good",
"tests/test_cmd2.py::test_default_to_shell_failure",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_cmd2.py::test_cmdresult",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_eos",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false",
"tests/test_cmd2.py::test_raw_input",
"tests/test_cmd2.py::test_stdin_input",
"tests/test_cmd2.py::test_empty_stdin_input",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_alias",
"tests/test_cmd2.py::test_alias_lookup_invalid_alias",
"tests/test_cmd2.py::test_unalias",
"tests/test_cmd2.py::test_unalias_all",
"tests/test_cmd2.py::test_unalias_non_existing",
"tests/test_cmd2.py::test_create_invalid_alias[\">\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"no>pe\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"no",
"tests/test_cmd2.py::test_create_invalid_alias[\"nopipe|\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"noterm;\"]",
"tests/test_cmd2.py::test_create_invalid_alias[noembedded\"quotes]",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-31 04:03:54+00:00
|
mit
| 5,055 |
|
python-cmd2__cmd2-496
|
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 7273286b..94b75e5f 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -1858,8 +1858,30 @@ class Cmd(cmd.Cmd):
pipe runs out. We can't refactor it because we need to retain
backwards compatibility with the standard library version of cmd.
"""
- statement = self.statement_parser.parse(self.preparse(line))
- while statement.multiline_command and not statement.terminator:
+ # preparse() is deprecated, use self.register_postparsing_hook() instead
+ line = self.preparse(line)
+
+ while True:
+ try:
+ statement = self.statement_parser.parse(line)
+ if statement.multiline_command and statement.terminator:
+ # we have a completed multiline command, we are done
+ break
+ if not statement.multiline_command:
+ # it's not a multiline command, but we parsed it ok
+ # so we are done
+ break
+ except ValueError:
+ # we have unclosed quotation marks, lets parse only the command
+ # and see if it's a multiline
+ statement = self.statement_parser.parse_command_only(line)
+ if not statement.multiline_command:
+ # not a multiline command, so raise the exception
+ raise
+
+ # if we get here we must have:
+ # - a multiline command with no terminator
+ # - a multiline command with unclosed quotation marks
if not self.quit_on_sigint:
try:
newline = self.pseudo_raw_input(self.continuation_prompt)
@@ -1885,7 +1907,6 @@ class Cmd(cmd.Cmd):
newline = '\n'
self.poutput(newline)
line = '{}\n{}'.format(statement.raw, newline)
- statement = self.statement_parser.parse(line)
if not statement.command:
raise EmptyStatement()
diff --git a/cmd2/parsing.py b/cmd2/parsing.py
index 475554b0..b67cef10 100644
--- a/cmd2/parsing.py
+++ b/cmd2/parsing.py
@@ -407,8 +407,8 @@ class StatementParser:
"""Partially parse input into a Statement object.
The command is identified, and shortcuts and aliases are expanded.
- Terminators, multiline commands, and output redirection are not
- parsed.
+ Multiline commands are identified, but terminators and output
+ redirection are not parsed.
This method is used by tab completion code and therefore must not
generate an exception if there are unclosed quotes.
@@ -420,8 +420,8 @@ class StatementParser:
- args
Different from parse(), this method does not remove redundant whitespace
- within statement.args. It does however, ensure args does not have leading
- or trailing whitespace.
+ within statement.args. It does however, ensure args does not have
+ leading or trailing whitespace.
"""
# expand shortcuts and aliases
line = self._expand(rawinput)
@@ -447,6 +447,12 @@ class StatementParser:
if not command or not args:
args = None
+ # set multiline
+ if command in self.multiline_commands:
+ multiline_command = command
+ else:
+ multiline_command = None
+
# build the statement
# string representation of args must be an empty string instead of
# None for compatibility with standard library cmd
@@ -454,6 +460,7 @@ class StatementParser:
raw=rawinput,
command=command,
args=args,
+ multiline_command=multiline_command,
)
return statement
|
python-cmd2/cmd2
|
46955ec2f403a94ca3582fe3225bdcc369f334e1
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index 3324a105..0ec993e9 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -1471,7 +1471,8 @@ def test_multiline_complete_empty_statement_raises_exception(multiline_app):
multiline_app._complete_statement('')
def test_multiline_complete_statement_without_terminator(multiline_app):
- # Mock out the input call so we don't actually wait for a user's response on stdin when it looks for more input
+ # Mock out the input call so we don't actually wait for a user's response
+ # on stdin when it looks for more input
m = mock.MagicMock(name='input', return_value='\n')
builtins.input = m
@@ -1481,6 +1482,20 @@ def test_multiline_complete_statement_without_terminator(multiline_app):
statement = multiline_app._complete_statement(line)
assert statement == args
assert statement.command == command
+ assert statement.multiline_command == command
+
+def test_multiline_complete_statement_with_unclosed_quotes(multiline_app):
+ # Mock out the input call so we don't actually wait for a user's response
+ # on stdin when it looks for more input
+ m = mock.MagicMock(name='input', side_effect=['quotes', '" now closed;'])
+ builtins.input = m
+
+ line = 'orate hi "partially open'
+ statement = multiline_app._complete_statement(line)
+ assert statement == 'hi "partially open\nquotes\n" now closed'
+ assert statement.command == 'orate'
+ assert statement.multiline_command == 'orate'
+ assert statement.terminator == ';'
def test_clipboard_failure(base_app, capsys):
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index 6e795660..de4c637e 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -376,7 +376,7 @@ def test_parse_multiline_with_complete_comment(parser):
assert statement.argv == ['multiline', 'command', 'is', 'done']
assert statement.terminator == ';'
-def test_parse_multiline_termninated_by_empty_line(parser):
+def test_parse_multiline_terminated_by_empty_line(parser):
line = 'multiline command ends\n\n'
statement = parser.parse(line)
assert statement.multiline_command == 'multiline'
@@ -386,6 +386,23 @@ def test_parse_multiline_termninated_by_empty_line(parser):
assert statement.argv == ['multiline', 'command', 'ends']
assert statement.terminator == '\n'
[email protected]('line,terminator',[
+ ('multiline command "with\nembedded newline";', ';'),
+ ('multiline command "with\nembedded newline";;;', ';'),
+ ('multiline command "with\nembedded newline";; ;;', ';'),
+ ('multiline command "with\nembedded newline" &', '&'),
+ ('multiline command "with\nembedded newline" & &', '&'),
+ ('multiline command "with\nembedded newline"\n\n', '\n'),
+])
+def test_parse_multiline_with_embedded_newline(parser, line, terminator):
+ statement = parser.parse(line)
+ assert statement.multiline_command == 'multiline'
+ assert statement.command == 'multiline'
+ assert statement.args == 'command "with\nembedded newline"'
+ assert statement == statement.args
+ assert statement.argv == ['multiline', 'command', 'with\nembedded newline']
+ assert statement.terminator == terminator
+
def test_parse_multiline_ignores_terminators_in_comments(parser):
line = 'multiline command "with term; ends" now\n\n'
statement = parser.parse(line)
@@ -584,6 +601,16 @@ def test_parse_command_only_none(parser, line):
assert statement.args is None
assert statement == ''
+def test_parse_command_only_multiline(parser):
+ line = 'multiline with partially "open quotes and no terminator'
+ statement = parser.parse_command_only(line)
+ assert statement.command == 'multiline'
+ assert statement.multiline_command == 'multiline'
+ assert statement.args == 'with partially "open quotes and no terminator'
+ assert statement == statement.args
+ assert statement.command_and_args == line
+
+
def test_statement_initialization(parser):
string = 'alias'
statement = cmd2.Statement(string)
|
Question: multiline command args with matching quote on another line?
Is it possible to configure cmd2 to have the closing quote on another line ('embedded newline in args'):
my_command is a multiline command
Expected behaviour
my_command 'This is a long arg broken over two
lines';
self.argv[1] = 'This is a long arg broken over two\nlines'
Currently the parser shows "ERROR: Invalid syntax: No closing quotation"
|
0.0
|
46955ec2f403a94ca3582fe3225bdcc369f334e1
|
[
"tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes",
"tests/test_parsing.py::test_parse_command_only_multiline"
] |
[
"tests/test_cmd2.py::test_version",
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_help_history",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_base_show_readonly",
"tests/test_cmd2.py::test_cast",
"tests/test_cmd2.py::test_cast_problems",
"tests/test_cmd2.py::test_base_set",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_quiet",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_base_py",
"tests/test_cmd2.py::test_base_run_python_script",
"tests/test_cmd2.py::test_base_run_pyscript",
"tests/test_cmd2.py::test_recursive_pyscript_not_allowed",
"tests/test_cmd2.py::test_pyscript_with_nonexist_file",
"tests/test_cmd2.py::test_pyscript_with_exception",
"tests/test_cmd2.py::test_pyscript_requires_an_argument",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_history_span",
"tests/test_cmd2.py::test_history_get",
"tests/test_cmd2.py::test_base_history",
"tests/test_cmd2.py::test_history_script_format",
"tests/test_cmd2.py::test_history_with_string_argument",
"tests/test_cmd2.py::test_history_with_integer_argument",
"tests/test_cmd2.py::test_history_with_integer_span",
"tests/test_cmd2.py::test_history_with_span_start",
"tests/test_cmd2.py::test_history_with_span_end",
"tests/test_cmd2.py::test_history_with_span_index_error",
"tests/test_cmd2.py::test_history_output_file",
"tests/test_cmd2.py::test_history_edit",
"tests/test_cmd2.py::test_history_run_all_commands",
"tests/test_cmd2.py::test_history_run_one_command",
"tests/test_cmd2.py::test_history_clear",
"tests/test_cmd2.py::test_base_load",
"tests/test_cmd2.py::test_load_with_empty_args",
"tests/test_cmd2.py::test_load_with_nonexistent_file",
"tests/test_cmd2.py::test_load_with_directory",
"tests/test_cmd2.py::test_load_with_empty_file",
"tests/test_cmd2.py::test_load_with_binary_file",
"tests/test_cmd2.py::test_load_with_utf8_file",
"tests/test_cmd2.py::test_load_nested_loads",
"tests/test_cmd2.py::test_base_runcmds_plus_hooks",
"tests/test_cmd2.py::test_base_relative_load",
"tests/test_cmd2.py::test_relative_load_requires_an_argument",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory",
"tests/test_cmd2.py::test_output_redirection_to_too_long_filename",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_allow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_base_colorize",
"tests/test_cmd2.py::test_edit_no_editor",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_exclude_from_history",
"tests/test_cmd2.py::test_base_cmdloop_with_queue",
"tests/test_cmd2.py::test_base_cmdloop_without_queue",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell_unknown",
"tests/test_cmd2.py::test_default_to_shell_good",
"tests/test_cmd2.py::test_default_to_shell_failure",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_cmd2.py::test_commandresult_truthy",
"tests/test_cmd2.py::test_commandresult_falsy",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_eos",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false",
"tests/test_cmd2.py::test_raw_input",
"tests/test_cmd2.py::test_stdin_input",
"tests/test_cmd2.py::test_empty_stdin_input",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_alias",
"tests/test_cmd2.py::test_alias_lookup_invalid_alias",
"tests/test_cmd2.py::test_unalias",
"tests/test_cmd2.py::test_unalias_all",
"tests/test_cmd2.py::test_unalias_non_existing",
"tests/test_cmd2.py::test_create_invalid_alias[\">\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"no>pe\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"no",
"tests/test_cmd2.py::test_create_invalid_alias[\"nopipe|\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"noterm;\"]",
"tests/test_cmd2.py::test_create_invalid_alias[noembedded\"quotes]",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline",
"tests/test_cmd2.py::test_readline_remove_history_item",
"tests/test_cmd2.py::test_onecmd_raw_str_continue",
"tests/test_cmd2.py::test_onecmd_raw_str_quit",
"tests/test_cmd2.py::test_existing_history_file",
"tests/test_cmd2.py::test_new_history_file",
"tests/test_cmd2.py::test_bad_history_file_path",
"tests/test_parsing.py::test_parse_empty_string_default",
"tests/test_parsing.py::test_tokenize_default[command-tokens0]",
"tests/test_parsing.py::test_tokenize_default[command",
"tests/test_parsing.py::test_tokenize_default[termbare",
"tests/test_parsing.py::test_tokenize_default[termbare;",
"tests/test_parsing.py::test_tokenize_default[termbare&",
"tests/test_parsing.py::test_tokenize_default[help|less-tokens7]",
"tests/test_parsing.py::test_parse_empty_string",
"tests/test_parsing.py::test_tokenize[command-tokens0]",
"tests/test_parsing.py::test_tokenize[command",
"tests/test_parsing.py::test_tokenize[42",
"tests/test_parsing.py::test_tokenize[l-tokens4]",
"tests/test_parsing.py::test_tokenize[termbare",
"tests/test_parsing.py::test_tokenize[termbare;",
"tests/test_parsing.py::test_tokenize[termbare&",
"tests/test_parsing.py::test_tokenize[help|less-tokens9]",
"tests/test_parsing.py::test_tokenize[l|less-tokens10]",
"tests/test_parsing.py::test_tokenize_unclosed_quotes",
"tests/test_parsing.py::test_command_and_args[tokens0-None-None]",
"tests/test_parsing.py::test_command_and_args[tokens1-command-None]",
"tests/test_parsing.py::test_command_and_args[tokens2-command-arg1",
"tests/test_parsing.py::test_parse_single_word[plainword]",
"tests/test_parsing.py::test_parse_single_word[\"one",
"tests/test_parsing.py::test_parse_single_word['one",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare;-;]",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare&-&]",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare;",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare&",
"tests/test_parsing.py::test_parse_command_with_args",
"tests/test_parsing.py::test_parse_command_with_quoted_args",
"tests/test_parsing.py::test_parse_command_with_args_terminator_and_suffix",
"tests/test_parsing.py::test_parse_hashcomment",
"tests/test_parsing.py::test_parse_c_comment",
"tests/test_parsing.py::test_parse_c_comment_empty",
"tests/test_parsing.py::test_parse_c_comment_no_closing",
"tests/test_parsing.py::test_parse_c_comment_multiple_opening",
"tests/test_parsing.py::test_parse_what_if_quoted_strings_seem_to_start_comments",
"tests/test_parsing.py::test_parse_simple_pipe[simple",
"tests/test_parsing.py::test_parse_simple_pipe[simple|piped]",
"tests/test_parsing.py::test_parse_double_pipe_is_not_a_pipe",
"tests/test_parsing.py::test_parse_complex_pipe",
"tests/test_parsing.py::test_parse_redirect[help",
"tests/test_parsing.py::test_parse_redirect[help>out.txt->]",
"tests/test_parsing.py::test_parse_redirect[help>>out.txt->>]",
"tests/test_parsing.py::test_parse_redirect_with_args",
"tests/test_parsing.py::test_parse_redirect_with_dash_in_path",
"tests/test_parsing.py::test_parse_redirect_append",
"tests/test_parsing.py::test_parse_pipe_and_redirect",
"tests/test_parsing.py::test_parse_output_to_paste_buffer",
"tests/test_parsing.py::test_parse_redirect_inside_terminator",
"tests/test_parsing.py::test_parse_multiple_terminators[multiline",
"tests/test_parsing.py::test_parse_unfinished_multiliine_command",
"tests/test_parsing.py::test_parse_multiline_command_ignores_redirectors_within_it[multiline",
"tests/test_parsing.py::test_parse_multiline_with_incomplete_comment",
"tests/test_parsing.py::test_parse_multiline_with_complete_comment",
"tests/test_parsing.py::test_parse_multiline_terminated_by_empty_line",
"tests/test_parsing.py::test_parse_multiline_with_embedded_newline[multiline",
"tests/test_parsing.py::test_parse_multiline_ignores_terminators_in_comments",
"tests/test_parsing.py::test_parse_command_with_unicode_args",
"tests/test_parsing.py::test_parse_unicode_command",
"tests/test_parsing.py::test_parse_redirect_to_unicode_filename",
"tests/test_parsing.py::test_parse_unclosed_quotes",
"tests/test_parsing.py::test_empty_statement_raises_exception",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias-help-None]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42-theanswer-None]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls-shell-ls]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[l-shell-ls",
"tests/test_parsing.py::test_parse_alias_on_multiline_command",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>out.txt->]",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>>out.txt->>]",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias|less]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias",
"tests/test_parsing.py::test_parse_command_only_command_and_args",
"tests/test_parsing.py::test_parse_command_only_emptyline",
"tests/test_parsing.py::test_parse_command_only_strips_line",
"tests/test_parsing.py::test_parse_command_only_expands_alias",
"tests/test_parsing.py::test_parse_command_only_expands_shortcuts",
"tests/test_parsing.py::test_parse_command_only_quoted_args",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>>out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help|less]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias;]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help",
"tests/test_parsing.py::test_parse_command_only_specialchars[help;",
"tests/test_parsing.py::test_parse_command_only_none[;]",
"tests/test_parsing.py::test_parse_command_only_none[;;]",
"tests/test_parsing.py::test_parse_command_only_none[;;",
"tests/test_parsing.py::test_parse_command_only_none[&]",
"tests/test_parsing.py::test_parse_command_only_none[&",
"tests/test_parsing.py::test_parse_command_only_none[",
"tests/test_parsing.py::test_parse_command_only_none[>]",
"tests/test_parsing.py::test_parse_command_only_none[']",
"tests/test_parsing.py::test_parse_command_only_none[\"]",
"tests/test_parsing.py::test_parse_command_only_none[|]",
"tests/test_parsing.py::test_statement_initialization"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-09 03:34:58+00:00
|
mit
| 5,056 |
|
python-cmd2__cmd2-542
|
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 91b84f0d..c64966a1 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -2160,7 +2160,7 @@ class Cmd(cmd.Cmd):
def do_alias(self, statement: Statement) -> None:
"""Define or display aliases
-Usage: Usage: alias [name] | [<name> <value>]
+ Usage: alias [name] | [<name> <value>]
Where:
name - name of the alias being looked up, added, or replaced
value - what the alias will be resolved to (if adding or replacing)
@@ -2188,7 +2188,8 @@ Usage: Usage: alias [name] | [<name> <value>]
# If no args were given, then print a list of current aliases
if not alias_arg_list:
- for cur_alias in self.aliases:
+ sorted_aliases = utils.alphabetical_sort(list(self.aliases))
+ for cur_alias in sorted_aliases:
self.poutput("alias {} {}".format(cur_alias, self.aliases[cur_alias]))
return
@@ -2222,9 +2223,6 @@ Usage: Usage: alias [name] | [<name> <value>]
# Set the alias
self.aliases[name] = value
self.poutput("Alias {!r} created".format(name))
-
- # Keep aliases in alphabetically sorted order
- self.aliases = collections.OrderedDict(sorted(self.aliases.items()))
else:
errmsg = "Aliases can not contain: {}".format(invalidchars)
self.perror(errmsg, traceback_war=False)
@@ -2245,7 +2243,7 @@ Usage: Usage: alias [name] | [<name> <value>]
def do_unalias(self, arglist: List[str]) -> None:
"""Unsets aliases
-Usage: Usage: unalias [-a] name [name ...]
+ Usage: unalias [-a] name [name ...]
Where:
name - name of the alias being unset
|
python-cmd2/cmd2
|
38f070a5876e91945bfadd3fe60ddcb8b21b96c3
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index 17c19f2a..e3992c7b 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -1828,7 +1828,22 @@ def test_complete_unalias(base_app):
# Validate that there are now completions
expected = ['fake', 'fall']
- assert base_app.complete_unalias(text, line, begidx, endidx) == expected
+ result = base_app.complete_unalias(text, line, begidx, endidx)
+ assert sorted(expected) == sorted(result)
+
+def test_multiple_aliases(base_app):
+ alias1 = 'h1'
+ alias2 = 'h2'
+ run_cmd(base_app, 'alias {} help'.format(alias1))
+ run_cmd(base_app, 'alias {} help -v'.format(alias2))
+ out = run_cmd(base_app, alias1)
+ expected = normalize(BASE_HELP)
+ assert out == expected
+
+ out = run_cmd(base_app, alias2)
+ expected = normalize(BASE_HELP_VERBOSE)
+ assert out == expected
+
def test_ppaged(base_app):
msg = 'testing...'
|
alias command broken in some circumstances
The ``alias`` command is currently broken on the *master* branch.
A good way to reproduce one case in which it is broken is to use the [alias_startup.py](https://github.com/python-cmd2/cmd2/blob/master/examples/alias_startup.py) example and attempt to run the **pwd** alias as defined in the [.cmd2rc](https://github.com/python-cmd2/cmd2/blob/master/examples/.cmd2rc) startup script.
I believe that the changes in the works on the *macro* branch will fix the current problem.
|
0.0
|
38f070a5876e91945bfadd3fe60ddcb8b21b96c3
|
[
"tests/test_cmd2.py::test_multiple_aliases"
] |
[
"tests/test_cmd2.py::test_version",
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_help_history",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_invalid_option",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_base_show_readonly",
"tests/test_cmd2.py::test_cast",
"tests/test_cmd2.py::test_cast_problems",
"tests/test_cmd2.py::test_base_set",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_quiet",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_base_py",
"tests/test_cmd2.py::test_base_run_python_script",
"tests/test_cmd2.py::test_base_run_pyscript",
"tests/test_cmd2.py::test_recursive_pyscript_not_allowed",
"tests/test_cmd2.py::test_pyscript_with_nonexist_file",
"tests/test_cmd2.py::test_pyscript_with_exception",
"tests/test_cmd2.py::test_pyscript_requires_an_argument",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_history_span",
"tests/test_cmd2.py::test_history_get",
"tests/test_cmd2.py::test_base_history",
"tests/test_cmd2.py::test_history_script_format",
"tests/test_cmd2.py::test_history_with_string_argument",
"tests/test_cmd2.py::test_history_with_integer_argument",
"tests/test_cmd2.py::test_history_with_integer_span",
"tests/test_cmd2.py::test_history_with_span_start",
"tests/test_cmd2.py::test_history_with_span_end",
"tests/test_cmd2.py::test_history_with_span_index_error",
"tests/test_cmd2.py::test_history_output_file",
"tests/test_cmd2.py::test_history_edit",
"tests/test_cmd2.py::test_history_run_all_commands",
"tests/test_cmd2.py::test_history_run_one_command",
"tests/test_cmd2.py::test_history_clear",
"tests/test_cmd2.py::test_base_load",
"tests/test_cmd2.py::test_load_with_empty_args",
"tests/test_cmd2.py::test_load_with_nonexistent_file",
"tests/test_cmd2.py::test_load_with_directory",
"tests/test_cmd2.py::test_load_with_empty_file",
"tests/test_cmd2.py::test_load_with_binary_file",
"tests/test_cmd2.py::test_load_with_utf8_file",
"tests/test_cmd2.py::test_load_nested_loads",
"tests/test_cmd2.py::test_base_runcmds_plus_hooks",
"tests/test_cmd2.py::test_base_relative_load",
"tests/test_cmd2.py::test_relative_load_requires_an_argument",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory",
"tests/test_cmd2.py::test_output_redirection_to_too_long_filename",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_allow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_base_colorize",
"tests/test_cmd2.py::test_edit_no_editor",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_exclude_from_history",
"tests/test_cmd2.py::test_base_cmdloop_with_queue",
"tests/test_cmd2.py::test_base_cmdloop_without_queue",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell_unknown",
"tests/test_cmd2.py::test_default_to_shell_good",
"tests/test_cmd2.py::test_default_to_shell_failure",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes",
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_cmd2.py::test_commandresult_truthy",
"tests/test_cmd2.py::test_commandresult_falsy",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_eos",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false",
"tests/test_cmd2.py::test_raw_input",
"tests/test_cmd2.py::test_stdin_input",
"tests/test_cmd2.py::test_empty_stdin_input",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_alias",
"tests/test_cmd2.py::test_alias_with_quotes",
"tests/test_cmd2.py::test_alias_lookup_invalid_alias",
"tests/test_cmd2.py::test_unalias",
"tests/test_cmd2.py::test_unalias_all",
"tests/test_cmd2.py::test_unalias_non_existing",
"tests/test_cmd2.py::test_create_invalid_alias[\">\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"no>pe\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"no",
"tests/test_cmd2.py::test_create_invalid_alias[\"nopipe|\"]",
"tests/test_cmd2.py::test_create_invalid_alias[\"noterm;\"]",
"tests/test_cmd2.py::test_create_invalid_alias[noembedded\"quotes]",
"tests/test_cmd2.py::test_complete_unalias",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline",
"tests/test_cmd2.py::test_readline_remove_history_item",
"tests/test_cmd2.py::test_onecmd_raw_str_continue",
"tests/test_cmd2.py::test_onecmd_raw_str_quit",
"tests/test_cmd2.py::test_existing_history_file",
"tests/test_cmd2.py::test_new_history_file",
"tests/test_cmd2.py::test_bad_history_file_path",
"tests/test_cmd2.py::test_get_all_commands",
"tests/test_cmd2.py::test_get_help_topics",
"tests/test_cmd2.py::test_exit_code_default",
"tests/test_cmd2.py::test_exit_code_nonzero"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-09-25 18:17:42+00:00
|
mit
| 5,057 |
|
python-cmd2__cmd2-559
|
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 03c71a91..e04138fa 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -2982,6 +2982,8 @@ class Cmd(cmd.Cmd):
if self.locals_in_py:
self.pystate['self'] = self
+ elif 'self' in self.pystate:
+ del self.pystate['self']
localvars = self.pystate
from code import InteractiveConsole
|
python-cmd2/cmd2
|
9ca3476df3857cd5c89a5179e0e2578f95cb4425
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index a382a940..3d57a105 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -216,18 +216,35 @@ def test_base_shell(base_app, monkeypatch):
assert m.called
def test_base_py(base_app, capsys):
+ # Create a variable and make sure we can see it
run_cmd(base_app, 'py qqq=3')
out, err = capsys.readouterr()
assert out == ''
-
run_cmd(base_app, 'py print(qqq)')
out, err = capsys.readouterr()
assert out.rstrip() == '3'
+ # Add a more complex statement
run_cmd(base_app, 'py print("spaces" + " in this " + "command")')
out, err = capsys.readouterr()
assert out.rstrip() == 'spaces in this command'
+ # Set locals_in_py to True and make sure we see self
+ out = run_cmd(base_app, 'set locals_in_py True')
+ assert 'now: True' in out
+
+ run_cmd(base_app, 'py print(self)')
+ out, err = capsys.readouterr()
+ assert 'cmd2.cmd2.Cmd object' in out
+
+ # Set locals_in_py to False and make sure we can't see self
+ out = run_cmd(base_app, 'set locals_in_py False')
+ assert 'now: False' in out
+
+ run_cmd(base_app, 'py print(self)')
+ out, err = capsys.readouterr()
+ assert "name 'self' is not defined" in err
+
@pytest.mark.skipif(sys.platform == 'win32',
reason="Unit test doesn't work on win32, but feature does")
|
py command doesn't properly respect locals_in_py=False if it was ever True
Currently the **py** command will have ``self`` accessible forevermore if the ``locals_in_py`` attribute ever gets set to True - changing it back to False will have no effect.
Either setting it to False should make ``self`` no longer accessible within **py** OR ``locals_in_py`` should not be a runtime settable parameter.
|
0.0
|
9ca3476df3857cd5c89a5179e0e2578f95cb4425
|
[
"tests/test_cmd2.py::test_base_py"
] |
[
"tests/test_cmd2.py::test_version",
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_help_history",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_invalid_option",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_base_show_readonly",
"tests/test_cmd2.py::test_cast",
"tests/test_cmd2.py::test_cast_problems",
"tests/test_cmd2.py::test_base_set",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_quiet",
"tests/test_cmd2.py::test_set_onchange_hook",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_base_run_python_script",
"tests/test_cmd2.py::test_base_run_pyscript",
"tests/test_cmd2.py::test_recursive_pyscript_not_allowed",
"tests/test_cmd2.py::test_pyscript_with_nonexist_file",
"tests/test_cmd2.py::test_pyscript_with_exception",
"tests/test_cmd2.py::test_pyscript_requires_an_argument",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_history_span",
"tests/test_cmd2.py::test_history_get",
"tests/test_cmd2.py::test_base_history",
"tests/test_cmd2.py::test_history_script_format",
"tests/test_cmd2.py::test_history_with_string_argument",
"tests/test_cmd2.py::test_history_with_integer_argument",
"tests/test_cmd2.py::test_history_with_integer_span",
"tests/test_cmd2.py::test_history_with_span_start",
"tests/test_cmd2.py::test_history_with_span_end",
"tests/test_cmd2.py::test_history_with_span_index_error",
"tests/test_cmd2.py::test_history_output_file",
"tests/test_cmd2.py::test_history_edit",
"tests/test_cmd2.py::test_history_run_all_commands",
"tests/test_cmd2.py::test_history_run_one_command",
"tests/test_cmd2.py::test_history_clear",
"tests/test_cmd2.py::test_base_load",
"tests/test_cmd2.py::test_load_with_empty_args",
"tests/test_cmd2.py::test_load_with_nonexistent_file",
"tests/test_cmd2.py::test_load_with_directory",
"tests/test_cmd2.py::test_load_with_empty_file",
"tests/test_cmd2.py::test_load_with_binary_file",
"tests/test_cmd2.py::test_load_with_utf8_file",
"tests/test_cmd2.py::test_load_nested_loads",
"tests/test_cmd2.py::test_base_runcmds_plus_hooks",
"tests/test_cmd2.py::test_base_relative_load",
"tests/test_cmd2.py::test_relative_load_requires_an_argument",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory",
"tests/test_cmd2.py::test_output_redirection_to_too_long_filename",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_allow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_base_colorize",
"tests/test_cmd2.py::test_edit_no_editor",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_exclude_from_history",
"tests/test_cmd2.py::test_base_cmdloop_with_queue",
"tests/test_cmd2.py::test_base_cmdloop_without_queue",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell_unknown",
"tests/test_cmd2.py::test_default_to_shell_good",
"tests/test_cmd2.py::test_default_to_shell_failure",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes",
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_cmd2.py::test_commandresult_truthy",
"tests/test_cmd2.py::test_commandresult_falsy",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_eos",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false",
"tests/test_cmd2.py::test_raw_input",
"tests/test_cmd2.py::test_stdin_input",
"tests/test_cmd2.py::test_empty_stdin_input",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_poutput_color_always",
"tests/test_cmd2.py::test_poutput_color_never",
"tests/test_cmd2.py::test_get_alias_names",
"tests/test_cmd2.py::test_get_macro_names",
"tests/test_cmd2.py::test_alias_no_subcommand",
"tests/test_cmd2.py::test_alias_create",
"tests/test_cmd2.py::test_alias_quoted_name",
"tests/test_cmd2.py::test_alias_create_with_quoted_value",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_alias_create_with_macro_name",
"tests/test_cmd2.py::test_alias_list_invalid_alias",
"tests/test_cmd2.py::test_alias_delete",
"tests/test_cmd2.py::test_alias_delete_all",
"tests/test_cmd2.py::test_alias_delete_non_existing",
"tests/test_cmd2.py::test_alias_delete_no_name",
"tests/test_cmd2.py::test_multiple_aliases",
"tests/test_cmd2.py::test_macro_no_subcommand",
"tests/test_cmd2.py::test_macro_create",
"tests/test_cmd2.py::test_macro_create_quoted_name",
"tests/test_cmd2.py::test_macro_create_with_quoted_value",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_macro_create_with_alias_name",
"tests/test_cmd2.py::test_macro_create_with_command_name",
"tests/test_cmd2.py::test_macro_create_with_args",
"tests/test_cmd2.py::test_macro_create_with_escaped_args",
"tests/test_cmd2.py::test_macro_create_with_missing_arg_nums",
"tests/test_cmd2.py::test_macro_create_with_invalid_arg_num",
"tests/test_cmd2.py::test_macro_create_with_wrong_arg_count",
"tests/test_cmd2.py::test_macro_create_with_unicode_numbered_arg",
"tests/test_cmd2.py::test_macro_create_with_missing_unicode_arg_nums",
"tests/test_cmd2.py::test_macro_list_invalid_macro",
"tests/test_cmd2.py::test_macro_delete",
"tests/test_cmd2.py::test_macro_delete_all",
"tests/test_cmd2.py::test_macro_delete_non_existing",
"tests/test_cmd2.py::test_macro_delete_no_name",
"tests/test_cmd2.py::test_multiple_macros",
"tests/test_cmd2.py::test_nonexistent_macro",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline",
"tests/test_cmd2.py::test_readline_remove_history_item",
"tests/test_cmd2.py::test_onecmd_raw_str_continue",
"tests/test_cmd2.py::test_onecmd_raw_str_quit",
"tests/test_cmd2.py::test_existing_history_file",
"tests/test_cmd2.py::test_new_history_file",
"tests/test_cmd2.py::test_bad_history_file_path",
"tests/test_cmd2.py::test_get_all_commands",
"tests/test_cmd2.py::test_get_help_topics",
"tests/test_cmd2.py::test_exit_code_default",
"tests/test_cmd2.py::test_exit_code_nonzero",
"tests/test_cmd2.py::test_colors_default",
"tests/test_cmd2.py::test_colors_pouterr_always_tty",
"tests/test_cmd2.py::test_colors_pouterr_always_notty",
"tests/test_cmd2.py::test_colors_terminal_tty",
"tests/test_cmd2.py::test_colors_terminal_notty",
"tests/test_cmd2.py::test_colors_never_tty",
"tests/test_cmd2.py::test_colors_never_notty"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2018-10-01 21:33:03+00:00
|
mit
| 5,058 |
|
python-cmd2__cmd2-569
|
diff --git a/cmd2/pyscript_bridge.py b/cmd2/pyscript_bridge.py
index 2002ca6d..7c09aab0 100644
--- a/cmd2/pyscript_bridge.py
+++ b/cmd2/pyscript_bridge.py
@@ -33,9 +33,16 @@ class CommandResult(namedtuple_with_defaults('CommandResult', ['stdout', 'stderr
NOTE: Named tuples are immutable. So the contents are there for access, not for modification.
"""
- def __bool__(self):
- """If stderr is None and data is not None the command is considered a success"""
- return not self.stderr and self.data is not None
+ def __bool__(self) -> bool:
+ """Returns True if the command succeeded, otherwise False"""
+
+ # If data has a __bool__ method, then call it to determine success of command
+ if self.data is not None and callable(getattr(self.data, '__bool__', None)):
+ return bool(self.data)
+
+ # Otherwise check if stderr was filled out
+ else:
+ return not self.stderr
def _exec_cmd(cmd2_app, func: Callable, echo: bool) -> CommandResult:
|
python-cmd2/cmd2
|
9fee6105210b36201b5d2edc610f20bd67eac9f2
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index a64f21e4..a2bd6197 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -1576,8 +1576,14 @@ class CommandResultApp(cmd2.Cmd):
self._last_result = cmd2.CommandResult(arg, data=True)
def do_negative(self, arg):
+ self._last_result = cmd2.CommandResult(arg, data=False)
+
+ def do_affirmative_no_data(self, arg):
self._last_result = cmd2.CommandResult(arg)
+ def do_negative_no_data(self, arg):
+ self._last_result = cmd2.CommandResult('', arg)
+
@pytest.fixture
def commandresult_app():
app = CommandResultApp()
@@ -1590,11 +1596,19 @@ def test_commandresult_truthy(commandresult_app):
assert commandresult_app._last_result
assert commandresult_app._last_result == cmd2.CommandResult(arg, data=True)
+ run_cmd(commandresult_app, 'affirmative_no_data {}'.format(arg))
+ assert commandresult_app._last_result
+ assert commandresult_app._last_result == cmd2.CommandResult(arg)
+
def test_commandresult_falsy(commandresult_app):
arg = 'bar'
run_cmd(commandresult_app, 'negative {}'.format(arg))
assert not commandresult_app._last_result
- assert commandresult_app._last_result == cmd2.CommandResult(arg)
+ assert commandresult_app._last_result == cmd2.CommandResult(arg, data=False)
+
+ run_cmd(commandresult_app, 'negative_no_data {}'.format(arg))
+ assert not commandresult_app._last_result
+ assert commandresult_app._last_result == cmd2.CommandResult('', arg)
def test_is_text_file_bad_input(base_app):
|
CommandResult is False for cmd2 built-ins
Since no built-in **cmd2** command fills out `self._last_result`, `CommandResult` is always **False** when running these commands in `pyscript`.
|
0.0
|
9fee6105210b36201b5d2edc610f20bd67eac9f2
|
[
"tests/test_cmd2.py::test_commandresult_truthy",
"tests/test_cmd2.py::test_commandresult_falsy"
] |
[
"tests/test_cmd2.py::test_version",
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_help_history",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_invalid_option",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_base_show_readonly",
"tests/test_cmd2.py::test_cast",
"tests/test_cmd2.py::test_cast_problems",
"tests/test_cmd2.py::test_base_set",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_quiet",
"tests/test_cmd2.py::test_set_onchange_hook",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_base_py",
"tests/test_cmd2.py::test_base_run_python_script",
"tests/test_cmd2.py::test_base_run_pyscript",
"tests/test_cmd2.py::test_recursive_pyscript_not_allowed",
"tests/test_cmd2.py::test_pyscript_with_nonexist_file",
"tests/test_cmd2.py::test_pyscript_with_exception",
"tests/test_cmd2.py::test_pyscript_requires_an_argument",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_history_span",
"tests/test_cmd2.py::test_history_get",
"tests/test_cmd2.py::test_base_history",
"tests/test_cmd2.py::test_history_script_format",
"tests/test_cmd2.py::test_history_with_string_argument",
"tests/test_cmd2.py::test_history_with_integer_argument",
"tests/test_cmd2.py::test_history_with_integer_span",
"tests/test_cmd2.py::test_history_with_span_start",
"tests/test_cmd2.py::test_history_with_span_end",
"tests/test_cmd2.py::test_history_with_span_index_error",
"tests/test_cmd2.py::test_history_output_file",
"tests/test_cmd2.py::test_history_edit",
"tests/test_cmd2.py::test_history_run_all_commands",
"tests/test_cmd2.py::test_history_run_one_command",
"tests/test_cmd2.py::test_history_clear",
"tests/test_cmd2.py::test_base_load",
"tests/test_cmd2.py::test_load_with_empty_args",
"tests/test_cmd2.py::test_load_with_nonexistent_file",
"tests/test_cmd2.py::test_load_with_directory",
"tests/test_cmd2.py::test_load_with_empty_file",
"tests/test_cmd2.py::test_load_with_binary_file",
"tests/test_cmd2.py::test_load_with_utf8_file",
"tests/test_cmd2.py::test_load_nested_loads",
"tests/test_cmd2.py::test_base_runcmds_plus_hooks",
"tests/test_cmd2.py::test_base_relative_load",
"tests/test_cmd2.py::test_relative_load_requires_an_argument",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory",
"tests/test_cmd2.py::test_output_redirection_to_too_long_filename",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_allow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_base_colorize",
"tests/test_cmd2.py::test_edit_no_editor",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_exclude_from_history",
"tests/test_cmd2.py::test_base_cmdloop_with_queue",
"tests/test_cmd2.py::test_base_cmdloop_without_queue",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell_unknown",
"tests/test_cmd2.py::test_default_to_shell_good",
"tests/test_cmd2.py::test_default_to_shell_failure",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes",
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_eos",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false",
"tests/test_cmd2.py::test_raw_input",
"tests/test_cmd2.py::test_stdin_input",
"tests/test_cmd2.py::test_empty_stdin_input",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_poutput_color_always",
"tests/test_cmd2.py::test_poutput_color_never",
"tests/test_cmd2.py::test_get_alias_names",
"tests/test_cmd2.py::test_get_macro_names",
"tests/test_cmd2.py::test_alias_no_subcommand",
"tests/test_cmd2.py::test_alias_create",
"tests/test_cmd2.py::test_alias_create_with_quoted_value",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_alias_create_with_macro_name",
"tests/test_cmd2.py::test_alias_list_invalid_alias",
"tests/test_cmd2.py::test_alias_delete",
"tests/test_cmd2.py::test_alias_delete_all",
"tests/test_cmd2.py::test_alias_delete_non_existing",
"tests/test_cmd2.py::test_alias_delete_no_name",
"tests/test_cmd2.py::test_multiple_aliases",
"tests/test_cmd2.py::test_macro_no_subcommand",
"tests/test_cmd2.py::test_macro_create",
"tests/test_cmd2.py::test_macro_create_with_quoted_value",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_macro_create_with_alias_name",
"tests/test_cmd2.py::test_macro_create_with_command_name",
"tests/test_cmd2.py::test_macro_create_with_args",
"tests/test_cmd2.py::test_macro_create_with_escaped_args",
"tests/test_cmd2.py::test_macro_create_with_missing_arg_nums",
"tests/test_cmd2.py::test_macro_create_with_invalid_arg_num",
"tests/test_cmd2.py::test_macro_create_with_wrong_arg_count",
"tests/test_cmd2.py::test_macro_create_with_unicode_numbered_arg",
"tests/test_cmd2.py::test_macro_create_with_missing_unicode_arg_nums",
"tests/test_cmd2.py::test_macro_list_invalid_macro",
"tests/test_cmd2.py::test_macro_delete",
"tests/test_cmd2.py::test_macro_delete_all",
"tests/test_cmd2.py::test_macro_delete_non_existing",
"tests/test_cmd2.py::test_macro_delete_no_name",
"tests/test_cmd2.py::test_multiple_macros",
"tests/test_cmd2.py::test_nonexistent_macro",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline",
"tests/test_cmd2.py::test_readline_remove_history_item",
"tests/test_cmd2.py::test_onecmd_raw_str_continue",
"tests/test_cmd2.py::test_onecmd_raw_str_quit",
"tests/test_cmd2.py::test_existing_history_file",
"tests/test_cmd2.py::test_new_history_file",
"tests/test_cmd2.py::test_bad_history_file_path",
"tests/test_cmd2.py::test_get_all_commands",
"tests/test_cmd2.py::test_get_help_topics",
"tests/test_cmd2.py::test_exit_code_default",
"tests/test_cmd2.py::test_exit_code_nonzero",
"tests/test_cmd2.py::test_colors_default",
"tests/test_cmd2.py::test_colors_pouterr_always_tty",
"tests/test_cmd2.py::test_colors_pouterr_always_notty",
"tests/test_cmd2.py::test_colors_terminal_tty",
"tests/test_cmd2.py::test_colors_terminal_notty",
"tests/test_cmd2.py::test_colors_never_tty",
"tests/test_cmd2.py::test_colors_never_notty"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-10-05 19:51:27+00:00
|
mit
| 5,059 |
|
python-cmd2__cmd2-612
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7383541..22fd5046 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,4 +1,6 @@
## 0.9.7 (TBD, 2018)
+* Bug Fixes
+ * Fixed bug when user chooses a zero or negative index when calling ``Cmd.select()``
* Enhancements
* **cmdloop** now only attempts to register a custom signal handler for SIGINT if running in the main thread
* commands run as a result of ``default_to_shell`` being **True** now run via ``do_shell()`` and are saved
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index a513d0e7..56d74ec8 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -2780,6 +2780,8 @@ class Cmd(cmd.Cmd):
try:
choice = int(response)
+ if choice < 1:
+ raise IndexError
result = fulloptions[choice - 1][0]
break
except (ValueError, IndexError):
|
python-cmd2/cmd2
|
3efb3f14630d007572a5cf1246bdb78ee63be089
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index 57e1e90f..630a8fa0 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -1344,11 +1344,11 @@ def test_select_options(select_app):
# And verify the expected output to stdout
assert out == expected
-def test_select_invalid_option(select_app):
+def test_select_invalid_option_too_big(select_app):
# Mock out the input call so we don't actually wait for a user's response on stdin
m = mock.MagicMock(name='input')
# If side_effect is an iterable then each call to the mock will return the next value from the iterable.
- m.side_effect = ['3', '1'] # First pass and invalid selection, then pass a valid one
+ m.side_effect = ['3', '1'] # First pass an invalid selection, then pass a valid one
builtins.input = m
food = 'fish'
@@ -1368,6 +1368,30 @@ def test_select_invalid_option(select_app):
# And verify the expected output to stdout
assert out == expected
+def test_select_invalid_option_too_small(select_app):
+ # Mock out the input call so we don't actually wait for a user's response on stdin
+ m = mock.MagicMock(name='input')
+ # If side_effect is an iterable then each call to the mock will return the next value from the iterable.
+ m.side_effect = ['0', '1'] # First pass an invalid selection, then pass a valid one
+ builtins.input = m
+
+ food = 'fish'
+ out = run_cmd(select_app, "eat {}".format(food))
+ expected = normalize("""
+ 1. sweet
+ 2. salty
+'0' isn't a valid choice. Pick a number between 1 and 2:
+{} with sweet sauce, yum!
+""".format(food))
+
+ # Make sure our mock was called exactly twice with the expected arguments
+ arg = 'Sauce? '
+ calls = [mock.call(arg), mock.call(arg)]
+ m.assert_has_calls(calls)
+
+ # And verify the expected output to stdout
+ assert out == expected
+
def test_select_list_of_strings(select_app):
# Mock out the input call so we don't actually wait for a user's response on stdin
m = mock.MagicMock(name='input', return_value='2')
|
The select() method needs to check for a user response of 0.
The select() method presents a numbered list, starting with "1", for the user to choose from. When a 0 is entered, the last item in the list is automatically selected. Depending on the list size, some negative numbers are also accepted. I would suggest changing the code as follows to flag anything less then 1 as invalid:
```Python3
choice = int(response)
if choice < 1:
self.poutput("{!r} isn't a valid choice. Pick a number between 1 and {}:\n".format(response, len(fulloptions)))
continue
result = fulloptions[choice - 1][0]
```
|
0.0
|
3efb3f14630d007572a5cf1246bdb78ee63be089
|
[
"tests/test_cmd2.py::test_select_invalid_option_too_small"
] |
[
"tests/test_cmd2.py::test_version",
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_help_history",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_invalid_option",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_base_show_readonly",
"tests/test_cmd2.py::test_cast",
"tests/test_cmd2.py::test_cast_problems",
"tests/test_cmd2.py::test_base_set",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_quiet",
"tests/test_cmd2.py::test_set_onchange_hook",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_base_py",
"tests/test_cmd2.py::test_base_run_python_script",
"tests/test_cmd2.py::test_base_run_pyscript",
"tests/test_cmd2.py::test_recursive_pyscript_not_allowed",
"tests/test_cmd2.py::test_pyscript_with_nonexist_file",
"tests/test_cmd2.py::test_pyscript_with_exception",
"tests/test_cmd2.py::test_pyscript_requires_an_argument",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_history_span",
"tests/test_cmd2.py::test_history_get",
"tests/test_cmd2.py::test_base_history",
"tests/test_cmd2.py::test_history_script_format",
"tests/test_cmd2.py::test_history_with_string_argument",
"tests/test_cmd2.py::test_history_with_integer_argument",
"tests/test_cmd2.py::test_history_with_integer_span",
"tests/test_cmd2.py::test_history_with_span_start",
"tests/test_cmd2.py::test_history_with_span_end",
"tests/test_cmd2.py::test_history_with_span_index_error",
"tests/test_cmd2.py::test_history_output_file",
"tests/test_cmd2.py::test_history_edit",
"tests/test_cmd2.py::test_history_run_all_commands",
"tests/test_cmd2.py::test_history_run_one_command",
"tests/test_cmd2.py::test_history_clear",
"tests/test_cmd2.py::test_base_load",
"tests/test_cmd2.py::test_load_with_empty_args",
"tests/test_cmd2.py::test_load_with_nonexistent_file",
"tests/test_cmd2.py::test_load_with_directory",
"tests/test_cmd2.py::test_load_with_empty_file",
"tests/test_cmd2.py::test_load_with_binary_file",
"tests/test_cmd2.py::test_load_with_utf8_file",
"tests/test_cmd2.py::test_load_nested_loads",
"tests/test_cmd2.py::test_base_runcmds_plus_hooks",
"tests/test_cmd2.py::test_base_relative_load",
"tests/test_cmd2.py::test_relative_load_requires_an_argument",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory",
"tests/test_cmd2.py::test_output_redirection_to_too_long_filename",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_allow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_edit_no_editor",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_exclude_from_history",
"tests/test_cmd2.py::test_base_cmdloop_with_queue",
"tests/test_cmd2.py::test_base_cmdloop_without_queue",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option_too_big",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes",
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_cmd2.py::test_commandresult_truthy",
"tests/test_cmd2.py::test_commandresult_falsy",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_eos",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true",
"tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true",
"tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false",
"tests/test_cmd2.py::test_raw_input",
"tests/test_cmd2.py::test_stdin_input",
"tests/test_cmd2.py::test_empty_stdin_input",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_poutput_color_always",
"tests/test_cmd2.py::test_poutput_color_never",
"tests/test_cmd2.py::test_get_alias_names",
"tests/test_cmd2.py::test_get_macro_names",
"tests/test_cmd2.py::test_alias_no_subcommand",
"tests/test_cmd2.py::test_alias_create",
"tests/test_cmd2.py::test_alias_create_with_quoted_value",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_alias_create_with_macro_name",
"tests/test_cmd2.py::test_alias_list_invalid_alias",
"tests/test_cmd2.py::test_alias_delete",
"tests/test_cmd2.py::test_alias_delete_all",
"tests/test_cmd2.py::test_alias_delete_non_existing",
"tests/test_cmd2.py::test_alias_delete_no_name",
"tests/test_cmd2.py::test_multiple_aliases",
"tests/test_cmd2.py::test_macro_no_subcommand",
"tests/test_cmd2.py::test_macro_create",
"tests/test_cmd2.py::test_macro_create_with_quoted_value",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_macro_create_with_alias_name",
"tests/test_cmd2.py::test_macro_create_with_command_name",
"tests/test_cmd2.py::test_macro_create_with_args",
"tests/test_cmd2.py::test_macro_create_with_escaped_args",
"tests/test_cmd2.py::test_macro_usage_with_missing_args",
"tests/test_cmd2.py::test_macro_usage_with_exta_args",
"tests/test_cmd2.py::test_macro_create_with_missing_arg_nums",
"tests/test_cmd2.py::test_macro_create_with_invalid_arg_num",
"tests/test_cmd2.py::test_macro_create_with_unicode_numbered_arg",
"tests/test_cmd2.py::test_macro_create_with_missing_unicode_arg_nums",
"tests/test_cmd2.py::test_macro_list_invalid_macro",
"tests/test_cmd2.py::test_macro_delete",
"tests/test_cmd2.py::test_macro_delete_all",
"tests/test_cmd2.py::test_macro_delete_non_existing",
"tests/test_cmd2.py::test_macro_delete_no_name",
"tests/test_cmd2.py::test_multiple_macros",
"tests/test_cmd2.py::test_nonexistent_macro",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_ppaged_strips_color_when_redirecting",
"tests/test_cmd2.py::test_ppaged_strips_color_when_redirecting_if_always",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline",
"tests/test_cmd2.py::test_readline_remove_history_item",
"tests/test_cmd2.py::test_onecmd_raw_str_continue",
"tests/test_cmd2.py::test_onecmd_raw_str_quit",
"tests/test_cmd2.py::test_existing_history_file",
"tests/test_cmd2.py::test_new_history_file",
"tests/test_cmd2.py::test_bad_history_file_path",
"tests/test_cmd2.py::test_get_all_commands",
"tests/test_cmd2.py::test_get_help_topics",
"tests/test_cmd2.py::test_exit_code_default",
"tests/test_cmd2.py::test_exit_code_nonzero",
"tests/test_cmd2.py::test_colors_default",
"tests/test_cmd2.py::test_colors_pouterr_always_tty",
"tests/test_cmd2.py::test_colors_pouterr_always_notty",
"tests/test_cmd2.py::test_colors_terminal_tty",
"tests/test_cmd2.py::test_colors_terminal_notty",
"tests/test_cmd2.py::test_colors_never_tty",
"tests/test_cmd2.py::test_colors_never_notty"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-12-14 03:16:53+00:00
|
mit
| 5,060 |
|
python-cmd2__cmd2-671
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4967891a..ce72a858 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,8 @@
since the output will print at the same frequency as when the command is run in a terminal.
* **ACArgumentParser** no longer prints complete help text when a parsing error occurs since long help messages
scroll the actual error message off the screen.
+ * Exceptions occurring in tab completion functions are now printed to stderr before returning control back to
+ readline. This makes debugging a lot easier since readline suppresses these exceptions.
* **Python 3.4 EOL notice**
* Python 3.4 reached its [end of life](https://www.python.org/dev/peps/pep-0429/) on March 18, 2019
* This is the last release of `cmd2` which will support Python 3.4
diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py
index ac65185b..edfaeec4 100644
--- a/cmd2/argparse_completer.py
+++ b/cmd2/argparse_completer.py
@@ -667,7 +667,7 @@ class AutoCompleter(object):
if callable(arg_choices[0]):
completer = arg_choices[0]
- elif isinstance(arg_choices[0], str) and callable(getattr(self._cmd2_app, arg_choices[0])):
+ else:
completer = getattr(self._cmd2_app, arg_choices[0])
# extract the positional and keyword arguments from the tuple
@@ -678,19 +678,16 @@ class AutoCompleter(object):
list_args = arg_choices[index]
elif isinstance(arg_choices[index], dict):
kw_args = arg_choices[index]
- try:
- # call the provided function differently depending on the provided positional and keyword arguments
- if list_args is not None and kw_args is not None:
- return completer(text, line, begidx, endidx, *list_args, **kw_args)
- elif list_args is not None:
- return completer(text, line, begidx, endidx, *list_args)
- elif kw_args is not None:
- return completer(text, line, begidx, endidx, **kw_args)
- else:
- return completer(text, line, begidx, endidx)
- except TypeError:
- # assume this is due to an incorrect function signature, return nothing.
- return []
+
+ # call the provided function differently depending on the provided positional and keyword arguments
+ if list_args is not None and kw_args is not None:
+ return completer(text, line, begidx, endidx, *list_args, **kw_args)
+ elif list_args is not None:
+ return completer(text, line, begidx, endidx, *list_args)
+ elif kw_args is not None:
+ return completer(text, line, begidx, endidx, **kw_args)
+ else:
+ return completer(text, line, begidx, endidx)
else:
return self._cmd2_app.basic_complete(text, line, begidx, endidx,
self._resolve_choices_for_arg(action, used_values))
@@ -704,32 +701,17 @@ class AutoCompleter(object):
# is the argument a string? If so, see if we can find an attribute in the
# application matching the string.
if isinstance(args, str):
- try:
- args = getattr(self._cmd2_app, args)
- except AttributeError:
- # Couldn't find anything matching the name
- return []
+ args = getattr(self._cmd2_app, args)
# is the provided argument a callable. If so, call it
if callable(args):
try:
- try:
- args = args(self._cmd2_app)
- except TypeError:
- args = args()
+ args = args(self._cmd2_app)
except TypeError:
- return []
-
- try:
- iter(args)
- except TypeError:
- pass
- else:
- # filter out arguments we already used
- args = [arg for arg in args if arg not in used_values]
+ args = args()
- if len(args) > 0:
- return args
+ # filter out arguments we already used
+ return [arg for arg in args if arg not in used_values]
return []
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index a7b60b1a..3c1c8d2c 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -1362,16 +1362,13 @@ class Cmd(cmd.Cmd):
# Display matches using actual display function. This also redraws the prompt and line.
orig_pyreadline_display(matches_to_display)
- # ----- Methods which override stuff in cmd -----
-
- def complete(self, text: str, state: int) -> Optional[str]:
- """Override of command method which returns the next possible completion for 'text'.
+ def _complete_worker(self, text: str, state: int) -> Optional[str]:
+ """The actual worker function for tab completion which is called by complete() and returns
+ the next possible completion for 'text'.
If a command has not been entered, then complete against command list.
Otherwise try to call complete_<command> to get list of completions.
- This method gets called directly by readline because it is set as the tab-completion function.
-
This completer function is called as complete(text, state), for state in 0, 1, 2, …, until it returns a
non-string value. It should return the next possible completion starting with text.
@@ -1581,6 +1578,24 @@ class Cmd(cmd.Cmd):
except IndexError:
return None
+ def complete(self, text: str, state: int) -> Optional[str]:
+ """Override of cmd2's complete method which returns the next possible completion for 'text'
+
+ This method gets called directly by readline. Since readline suppresses any exception raised
+ in completer functions, they can be difficult to debug. Therefore this function wraps the
+ actual tab completion logic and prints to stderr any exception that occurs before returning
+ control to readline.
+
+ :param text: the current word that user is typing
+ :param state: non-negative integer
+ """
+ # noinspection PyBroadException
+ try:
+ return self._complete_worker(text, state)
+ except Exception as e:
+ self.perror(e)
+ return None
+
def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int,
argparser: argparse.ArgumentParser) -> List[str]:
"""Default completion function for argparse commands."""
diff --git a/examples/tab_autocomp_dynamic.py b/examples/tab_autocomp_dynamic.py
index bedc9d4b..93b72442 100755
--- a/examples/tab_autocomp_dynamic.py
+++ b/examples/tab_autocomp_dynamic.py
@@ -69,7 +69,7 @@ class TabCompleteExample(cmd2.Cmd):
setattr(director_action, argparse_completer.ACTION_ARG_CHOICES, TabCompleteExample.static_list_directors)
setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, 'instance_query_actors')
- # tag the file property with a custom completion function 'delimeter_complete' provided by cmd2.
+ # tag the file property with a custom completion function 'delimiter_complete' provided by cmd2.
setattr(vid_movie_file_action, argparse_completer.ACTION_ARG_CHOICES,
('delimiter_complete',
{'delimiter': '/',
diff --git a/examples/tab_autocompletion.py b/examples/tab_autocompletion.py
index aa28fc10..3f06a274 100755
--- a/examples/tab_autocompletion.py
+++ b/examples/tab_autocompletion.py
@@ -255,7 +255,7 @@ class TabCompleteExample(cmd2.Cmd):
setattr(director_action, argparse_completer.ACTION_ARG_CHOICES, static_list_directors)
setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, 'instance_query_actors')
- # tag the file property with a custom completion function 'delimeter_complete' provided by cmd2.
+ # tag the file property with a custom completion function 'delimiter_complete' provided by cmd2.
setattr(vid_movie_file_action, argparse_completer.ACTION_ARG_CHOICES,
('delimiter_complete',
{'delimiter': '/',
|
python-cmd2/cmd2
|
673d8a1bebcada7f0182758acfe7f65637113286
|
diff --git a/tests/test_autocompletion.py b/tests/test_autocompletion.py
index a5dafd2d..005eee81 100644
--- a/tests/test_autocompletion.py
+++ b/tests/test_autocompletion.py
@@ -229,7 +229,7 @@ def test_autocomp_subcmd_flag_comp_list_attr(cmd2_app):
assert first_match is not None and first_match == '"Gareth Edwards'
-def test_autcomp_pos_consumed(cmd2_app):
+def test_autocomp_pos_consumed(cmd2_app):
text = ''
line = 'library movie add SW_EP01 {}'.format(text)
endidx = len(line)
@@ -239,7 +239,7 @@ def test_autcomp_pos_consumed(cmd2_app):
assert first_match is None
-def test_autcomp_pos_after_flag(cmd2_app):
+def test_autocomp_pos_after_flag(cmd2_app):
text = 'Joh'
line = 'video movies add -d "George Lucas" -- "Han Solo" PG "Emilia Clarke" "{}'.format(text)
endidx = len(line)
@@ -250,7 +250,7 @@ def test_autcomp_pos_after_flag(cmd2_app):
cmd2_app.completion_matches == ['John Boyega" ']
-def test_autcomp_custom_func_list_arg(cmd2_app):
+def test_autocomp_custom_func_list_arg(cmd2_app):
text = 'SW_'
line = 'library show add {}'.format(text)
endidx = len(line)
@@ -261,7 +261,7 @@ def test_autcomp_custom_func_list_arg(cmd2_app):
cmd2_app.completion_matches == ['SW_CW', 'SW_REB', 'SW_TCW']
-def test_autcomp_custom_func_list_and_dict_arg(cmd2_app):
+def test_autocomp_custom_func_list_and_dict_arg(cmd2_app):
text = ''
line = 'library show add SW_REB {}'.format(text)
endidx = len(line)
@@ -272,6 +272,17 @@ def test_autcomp_custom_func_list_and_dict_arg(cmd2_app):
cmd2_app.completion_matches == ['S01E02', 'S01E03', 'S02E01', 'S02E03']
+def test_autocomp_custom_func_dict_arg(cmd2_app):
+ text = '/home/user/'
+ line = 'video movies load {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
+ assert first_match is not None and \
+ cmd2_app.completion_matches == ['/home/user/another.db', '/home/user/file space.db', '/home/user/file.db']
+
+
def test_argparse_remainder_flag_completion(cmd2_app):
import cmd2
import argparse
diff --git a/tests/test_completion.py b/tests/test_completion.py
index 23843012..158856ec 100644
--- a/tests/test_completion.py
+++ b/tests/test_completion.py
@@ -77,6 +77,12 @@ class CompletionsExample(cmd2.Cmd):
num_strs = ['2', '11', '1']
return self.basic_complete(text, line, begidx, endidx, num_strs)
+ def do_test_raise_exception(self, args):
+ pass
+
+ def complete_test_raise_exception(self, text, line, begidx, endidx):
+ raise IndexError("You are out of bounds!!")
+
@pytest.fixture
def cmd2_app():
@@ -120,6 +126,18 @@ def test_complete_bogus_command(cmd2_app):
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
assert first_match is None
+def test_complete_exception(cmd2_app, capsys):
+ text = ''
+ line = 'test_raise_exception {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
+ out, err = capsys.readouterr()
+
+ assert first_match is None
+ assert "IndexError" in err
+
def test_complete_macro(base_app, request):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake pyscript {1}')
|
Give informative error message for invalid completer instead of empty completion results.
The following code suppresses an error when a completion function with an invalid signature is provided https://github.com/python-cmd2/cmd2/blob/de701086ff832bad0f0d97ffb10c2159d56ede7d/cmd2/argparse_completer.py#L691-L693
Instead of returning an empty list, I think that an informative error message explaining that the function signature is incorrect would be much more helpful. When I was implementing completion I was confused about why my completer wasn't returning any results until I traced it to this `return []`.
|
0.0
|
673d8a1bebcada7f0182758acfe7f65637113286
|
[
"tests/test_completion.py::test_complete_exception"
] |
[
"tests/test_autocompletion.py::test_help_required_group",
"tests/test_autocompletion.py::test_help_required_group_long",
"tests/test_autocompletion.py::test_autocomp_flags",
"tests/test_autocompletion.py::test_autcomp_hint",
"tests/test_autocompletion.py::test_autcomp_flag_comp",
"tests/test_autocompletion.py::test_autocomp_flags_choices",
"tests/test_autocompletion.py::test_autcomp_hint_in_narg_range",
"tests/test_autocompletion.py::test_autocomp_flags_narg_max",
"tests/test_autocompletion.py::test_autcomp_narg_beyond_max",
"tests/test_autocompletion.py::test_autocomp_subcmd_nested",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_choices_append",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_choices_append_exclude",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_func",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_list",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_func_attr",
"tests/test_autocompletion.py::test_autocomp_subcmd_flag_comp_list_attr",
"tests/test_autocompletion.py::test_autocomp_pos_consumed",
"tests/test_autocompletion.py::test_autocomp_pos_after_flag",
"tests/test_autocompletion.py::test_autocomp_custom_func_list_arg",
"tests/test_autocompletion.py::test_autocomp_custom_func_list_and_dict_arg",
"tests/test_autocompletion.py::test_autocomp_custom_func_dict_arg",
"tests/test_autocompletion.py::test_argparse_remainder_flag_completion",
"tests/test_autocompletion.py::test_completion_after_double_dash",
"tests/test_completion.py::test_cmd2_command_completion_single",
"tests/test_completion.py::test_complete_command_single",
"tests/test_completion.py::test_complete_empty_arg",
"tests/test_completion.py::test_complete_bogus_command",
"tests/test_completion.py::test_complete_macro",
"tests/test_completion.py::test_matches_sort_key",
"tests/test_completion.py::test_cmd2_command_completion_multiple",
"tests/test_completion.py::test_cmd2_command_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_completion_single",
"tests/test_completion.py::test_cmd2_help_completion_multiple",
"tests/test_completion.py::test_cmd2_help_completion_nomatch",
"tests/test_completion.py::test_shell_command_completion_shortcut",
"tests/test_completion.py::test_shell_command_completion_doesnt_match_wildcards",
"tests/test_completion.py::test_shell_command_completion_multiple",
"tests/test_completion.py::test_shell_command_completion_nomatch",
"tests/test_completion.py::test_shell_command_completion_doesnt_complete_when_just_shell",
"tests/test_completion.py::test_shell_command_completion_does_path_completion_when_after_command",
"tests/test_completion.py::test_shell_commmand_complete_in_path",
"tests/test_completion.py::test_path_completion_single_end",
"tests/test_completion.py::test_path_completion_multiple",
"tests/test_completion.py::test_path_completion_nomatch",
"tests/test_completion.py::test_default_to_shell_completion",
"tests/test_completion.py::test_path_completion_no_text",
"tests/test_completion.py::test_path_completion_no_path",
"tests/test_completion.py::test_path_completion_cwd_is_root_dir",
"tests/test_completion.py::test_path_completion_doesnt_match_wildcards",
"tests/test_completion.py::test_path_completion_complete_user",
"tests/test_completion.py::test_path_completion_user_path_expansion",
"tests/test_completion.py::test_path_completion_directories_only",
"tests/test_completion.py::test_basic_completion_single",
"tests/test_completion.py::test_basic_completion_multiple",
"tests/test_completion.py::test_basic_completion_nomatch",
"tests/test_completion.py::test_delimiter_completion",
"tests/test_completion.py::test_flag_based_completion_single",
"tests/test_completion.py::test_flag_based_completion_multiple",
"tests/test_completion.py::test_flag_based_completion_nomatch",
"tests/test_completion.py::test_flag_based_default_completer",
"tests/test_completion.py::test_flag_based_callable_completer",
"tests/test_completion.py::test_index_based_completion_single",
"tests/test_completion.py::test_index_based_completion_multiple",
"tests/test_completion.py::test_index_based_completion_nomatch",
"tests/test_completion.py::test_index_based_default_completer",
"tests/test_completion.py::test_index_based_callable_completer",
"tests/test_completion.py::test_tokens_for_completion_quoted",
"tests/test_completion.py::test_tokens_for_completion_unclosed_quote",
"tests/test_completion.py::test_tokens_for_completion_redirect",
"tests/test_completion.py::test_tokens_for_completion_quoted_redirect",
"tests/test_completion.py::test_tokens_for_completion_redirect_off",
"tests/test_completion.py::test_add_opening_quote_basic_no_text",
"tests/test_completion.py::test_add_opening_quote_basic_nothing_added",
"tests/test_completion.py::test_add_opening_quote_basic_quote_added",
"tests/test_completion.py::test_add_opening_quote_basic_text_is_common_prefix",
"tests/test_completion.py::test_add_opening_quote_delimited_no_text",
"tests/test_completion.py::test_add_opening_quote_delimited_nothing_added",
"tests/test_completion.py::test_add_opening_quote_delimited_quote_added",
"tests/test_completion.py::test_add_opening_quote_delimited_text_is_common_prefix",
"tests/test_completion.py::test_add_opening_quote_delimited_space_in_prefix",
"tests/test_completion.py::test_cmd2_subcommand_completion_single_end",
"tests/test_completion.py::test_cmd2_subcommand_completion_multiple",
"tests/test_completion.py::test_cmd2_subcommand_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_single",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_multiple",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_nomatch",
"tests/test_completion.py::test_subcommand_tab_completion",
"tests/test_completion.py::test_subcommand_tab_completion_with_no_completer",
"tests/test_completion.py::test_subcommand_tab_completion_space_in_text",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_single_end",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_multiple",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_single_scu",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_multiple_scu",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_with_flags_before_command",
"tests/test_completion.py::test_complete_help_subcommand_with_no_command",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_nomatch_scu",
"tests/test_completion.py::test_subcommand_tab_completion_scu",
"tests/test_completion.py::test_subcommand_tab_completion_with_no_completer_scu",
"tests/test_completion.py::test_subcommand_tab_completion_space_in_text_scu"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-06 04:40:31+00:00
|
mit
| 5,061 |
|
python-cmd2__cmd2-681
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a6f56821..2fe4e734 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,10 +19,13 @@
scroll the actual error message off the screen.
* Exceptions occurring in tab completion functions are now printed to stderr before returning control back to
readline. This makes debugging a lot easier since readline suppresses these exceptions.
+ * Added support for custom Namespaces in the argparse decorators. See description of `ns_provider` argument
+ for more information.
* Potentially breaking changes
* Replaced `unquote_redirection_tokens()` with `unquote_specific_tokens()`. This was to support the fix
that allows terminators in alias and macro values.
- * Changed `Statement.pipe_to` to a string instead of a list
+ * Changed `Statement.pipe_to` to a string instead of a list
+ * `preserve_quotes` is now a keyword-only argument in the argparse decorators
* **Python 3.4 EOL notice**
* Python 3.4 reached its [end of life](https://www.python.org/dev/peps/pep-0429/) on March 18, 2019
* This is the last release of `cmd2` which will support Python 3.4
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index c29a1812..f5a2a844 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -191,12 +191,17 @@ def with_argument_list(*args: List[Callable], preserve_quotes: bool = False) ->
return arg_decorator
-def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve_quotes: bool = False) -> \
+def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, *,
+ ns_provider: Optional[Callable[..., argparse.Namespace]] = None,
+ preserve_quotes: bool = False) -> \
Callable[[argparse.Namespace, List], Optional[bool]]:
"""A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given
instance of argparse.ArgumentParser, but also returning unknown args as a list.
:param argparser: unique instance of ArgumentParser
+ :param ns_provider: An optional function that accepts a cmd2.Cmd object as an argument and returns an
+ argparse.Namespace. This is useful if the Namespace needs to be prepopulated with
+ state data that affects parsing.
:param preserve_quotes: if True, then arguments passed to argparse maintain their quotes
:return: function that gets passed argparse-parsed args in a Namespace and a list of unknown argument strings
A member called __statement__ is added to the Namespace to provide command functions access to the
@@ -213,8 +218,13 @@ def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve
statement,
preserve_quotes)
+ if ns_provider is None:
+ namespace = None
+ else:
+ namespace = ns_provider(cmd2_instance)
+
try:
- args, unknown = argparser.parse_known_args(parsed_arglist)
+ args, unknown = argparser.parse_known_args(parsed_arglist, namespace)
except SystemExit:
return
else:
@@ -241,12 +251,16 @@ def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve
return arg_decorator
-def with_argparser(argparser: argparse.ArgumentParser,
+def with_argparser(argparser: argparse.ArgumentParser, *,
+ ns_provider: Optional[Callable[..., argparse.Namespace]] = None,
preserve_quotes: bool = False) -> Callable[[argparse.Namespace], Optional[bool]]:
"""A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments
with the given instance of argparse.ArgumentParser.
:param argparser: unique instance of ArgumentParser
+ :param ns_provider: An optional function that accepts a cmd2.Cmd object as an argument and returns an
+ argparse.Namespace. This is useful if the Namespace needs to be prepopulated with
+ state data that affects parsing.
:param preserve_quotes: if True, then arguments passed to argparse maintain their quotes
:return: function that gets passed the argparse-parsed args in a Namespace
A member called __statement__ is added to the Namespace to provide command functions access to the
@@ -261,8 +275,14 @@ def with_argparser(argparser: argparse.ArgumentParser,
statement, parsed_arglist = cmd2_instance.statement_parser.get_command_arg_list(command_name,
statement,
preserve_quotes)
+
+ if ns_provider is None:
+ namespace = None
+ else:
+ namespace = ns_provider(cmd2_instance)
+
try:
- args = argparser.parse_args(parsed_arglist)
+ args = argparser.parse_args(parsed_arglist, namespace)
except SystemExit:
return
else:
diff --git a/docs/argument_processing.rst b/docs/argument_processing.rst
index fc1f2433..4bd917cf 100644
--- a/docs/argument_processing.rst
+++ b/docs/argument_processing.rst
@@ -247,7 +247,7 @@ argument list instead of a string::
pass
-Using the argument parser decorator and also receiving a a list of unknown positional arguments
+Using the argument parser decorator and also receiving a list of unknown positional arguments
===============================================================================================
If you want all unknown arguments to be passed to your command as a list of strings, then
decorate the command method with the ``@with_argparser_and_unknown_args`` decorator.
@@ -275,6 +275,31 @@ Here's what it looks like::
...
+Using custom argparse.Namespace with argument parser decorators
+===============================================================================================
+In some cases, it may be necessary to write custom ``argparse`` code that is dependent on state data of your
+application. To support this ability while still allowing use of the decorators, both ``@with_argparser`` and
+``@with_argparser_and_unknown_args`` have an optional argument called ``ns_provider``.
+
+``ns_provider`` is a Callable that accepts a ``cmd2.Cmd`` object as an argument and returns an ``argparse.Namespace``::
+
+ Callable[[cmd2.Cmd], argparse.Namespace]
+
+For example::
+
+ def settings_ns_provider(self) -> argparse.Namespace:
+ """Populate an argparse Namespace with current settings"""
+ ns = argparse.Namespace()
+ ns.app_settings = self.settings
+ return ns
+
+To use this function with the argparse decorators, do the following::
+
+ @with_argparser(my_parser, ns_provider=settings_ns_provider)
+
+The Namespace is passed by the decorators to the ``argparse`` parsing functions which gives your custom code access
+to the state data it needs for its parsing logic.
+
Sub-commands
============
Sub-commands are supported for commands using either the ``@with_argparser`` or
|
python-cmd2/cmd2
|
3ee97d121887d3055fc6326b1d9bc290f5235866
|
diff --git a/tests/test_argparse.py b/tests/test_argparse.py
index d716c68d..74a5d16f 100644
--- a/tests/test_argparse.py
+++ b/tests/test_argparse.py
@@ -29,6 +29,11 @@ class ArgparseApp(cmd2.Cmd):
self.maxrepeats = 3
cmd2.Cmd.__init__(self)
+ def namespace_provider(self) -> argparse.Namespace:
+ ns = argparse.Namespace()
+ ns.custom_stuff = "custom"
+ return ns
+
say_parser = argparse.ArgumentParser()
say_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
say_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
@@ -56,11 +61,15 @@ class ArgparseApp(cmd2.Cmd):
tag_parser.add_argument('tag', help='tag')
tag_parser.add_argument('content', nargs='+', help='content to surround with tag')
- @cmd2.with_argparser(tag_parser)
+ @cmd2.with_argparser(tag_parser, preserve_quotes=True)
def do_tag(self, args):
self.stdout.write('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content)))
self.stdout.write('\n')
+ @cmd2.with_argparser(argparse.ArgumentParser(), ns_provider=namespace_provider)
+ def do_test_argparse_ns(self, args):
+ self.stdout.write('{}'.format(args.custom_stuff))
+
@cmd2.with_argument_list
def do_arglist(self, arglist):
if isinstance(arglist, list):
@@ -93,21 +102,14 @@ class ArgparseApp(cmd2.Cmd):
self.stdout.write(' '.join(words))
self.stdout.write('\n')
- @cmd2.with_argparser_and_unknown_args(known_parser)
- def do_talk(self, args, extra):
- words = []
- for word in extra:
- if word is None:
- word = ''
- if args.piglatin:
- word = '%s%say' % (word[1:], word[0])
- if args.shout:
- word = word.upper()
- words.append(word)
- repetitions = args.repeat or 1
- for i in range(min(repetitions, self.maxrepeats)):
- self.stdout.write(' '.join(words))
- self.stdout.write('\n')
+ @cmd2.with_argparser_and_unknown_args(argparse.ArgumentParser(), preserve_quotes=True)
+ def do_test_argparse_with_list_quotes(self, args, extra):
+ self.stdout.write('{}'.format(' '.join(extra)))
+
+ @cmd2.with_argparser_and_unknown_args(argparse.ArgumentParser(), ns_provider=namespace_provider)
+ def do_test_argparse_with_list_ns(self, args, extra):
+ self.stdout.write('{}'.format(args.custom_stuff))
+
@pytest.fixture
def argparse_app():
@@ -123,14 +125,34 @@ def test_argparse_basic_command(argparse_app):
out, err = run_cmd(argparse_app, 'say hello')
assert out == ['hello']
-def test_argparse_quoted_arguments(argparse_app):
+def test_argparse_remove_quotes(argparse_app):
out, err = run_cmd(argparse_app, 'say "hello there"')
assert out == ['hello there']
+def test_argparse_preserve_quotes(argparse_app):
+ out, err = run_cmd(argparse_app, 'tag mytag "hello"')
+ assert out[0] == '<mytag>"hello"</mytag>'
+
+def test_argparse_custom_namespace(argparse_app):
+ out, err = run_cmd(argparse_app, 'test_argparse_ns')
+ assert out[0] == 'custom'
+
def test_argparse_with_list(argparse_app):
out, err = run_cmd(argparse_app, 'speak -s hello world!')
assert out == ['HELLO WORLD!']
+def test_argparse_with_list_remove_quotes(argparse_app):
+ out, err = run_cmd(argparse_app, 'speak -s hello "world!"')
+ assert out == ['HELLO WORLD!']
+
+def test_argparse_with_list_preserve_quotes(argparse_app):
+ out, err = run_cmd(argparse_app, 'test_argparse_with_list_quotes "hello" person')
+ assert out[0] == '"hello" person'
+
+def test_argparse_with_list_custom_namespace(argparse_app):
+ out, err = run_cmd(argparse_app, 'test_argparse_with_list_ns')
+ assert out[0] == 'custom'
+
def test_argparse_with_list_and_empty_doc(argparse_app):
out, err = run_cmd(argparse_app, 'speak -s hello world!')
assert out == ['HELLO WORLD!']
|
Pass a custom Namespace to args
Kind of a follow up on https://github.com/python-cmd2/cmd2/issues/498
I want to pass a custom Namespace when parsing arguments while keeping the autocompletion:
```
@with_argparser(parser)
def do_load_pcap(self, cmdline):
myNamespace = Namespace()
myNamespace.toto = self.data
args = parser.parse_args(shlex.split(cmdline), myNamespace)
```
I modified
https://github.com/python-cmd2/cmd2/blob/b6c39365e0331ab64aad074565fe73fb074a3a7f/cmd2/cmd2.py#L270-L271
so that it doesn't parse stuff.
```
def with_argparser_test(argparser: argparse.ArgumentParser,
preserve_quotes: bool=False) -> Callable[[argparse.Namespace], Optional[bool]]:
"""A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments
with the given instance of argparse.ArgumentParser.
:param argparser: unique instance of ArgumentParser
:param preserve_quotes: if True, then arguments passed to argparse maintain their quotes
:return: function that gets passed the argparse-parsed args
"""
import functools
# noinspection PyProtectedMember
def arg_decorator(func: Callable[[Any], Optional[bool]]):
@functools.wraps(func)
def cmd_wrapper(instance, cmdline):
# lexed_arglist = parse_quoted_string(cmdline, preserve_quotes)
# try:
# args = argparser.parse_args(lexed_arglist)
# except SystemExit:
# return
# else:
return func(instance, cmdline)
# argparser defaults the program name to sys.argv[0]
# we want it to be the name of our command
# argparser.prog = func.__name__[len(COMMAND_FUNC_PREFIX):]
# If the description has not been set, then use the method docstring if one exists
if argparser.description is None and func.__doc__:
argparser.description = func.__doc__
# Set the command's help text as argparser.description (which can be None)
# cmd_wrapper.__doc__ = argparser.description
# Mark this function as having an argparse ArgumentParser
setattr(cmd_wrapper, 'argparser', argparser)
return cmd_wrapper
return arg_decorator
```
which can be used like
```
@with_argparser_test(parser)
def do_load_pcap(self, args):
"""
Load the file as the current one
"""
args = shlex.split(args)
parser = self.do_load_pcap.argparser
args = parser.parse_args(args)
self.poutput("Loading %s" % args.input_file)
```
I wonder if cmd2 could propose some better interface. This is just an example, that adds a parameter "dont_parse" to the with_argparser decorator. If it's true, cmd2 could pass the parser along to the member function (instead of `parser = self.do_load_pcap.argparser` which requires some knowledge about cmd2 implementation)
```
@with_argparser(dont_quote, dont_parse=True)
def func(self, parser, args):
parser.parse_args(args)
```
|
0.0
|
3ee97d121887d3055fc6326b1d9bc290f5235866
|
[
"tests/test_argparse.py::test_invalid_syntax",
"tests/test_argparse.py::test_argparse_basic_command",
"tests/test_argparse.py::test_argparse_remove_quotes",
"tests/test_argparse.py::test_argparse_preserve_quotes",
"tests/test_argparse.py::test_argparse_custom_namespace",
"tests/test_argparse.py::test_argparse_with_list",
"tests/test_argparse.py::test_argparse_with_list_remove_quotes",
"tests/test_argparse.py::test_argparse_with_list_preserve_quotes",
"tests/test_argparse.py::test_argparse_with_list_custom_namespace",
"tests/test_argparse.py::test_argparse_with_list_and_empty_doc",
"tests/test_argparse.py::test_argparser_correct_args_with_quotes_and_midline_options",
"tests/test_argparse.py::test_argparse_quoted_arguments_multiple",
"tests/test_argparse.py::test_argparse_help_docstring",
"tests/test_argparse.py::test_argparse_help_description",
"tests/test_argparse.py::test_argparse_prog",
"tests/test_argparse.py::test_arglist",
"tests/test_argparse.py::test_preservelist",
"tests/test_argparse.py::test_subcommand_foo",
"tests/test_argparse.py::test_subcommand_bar",
"tests/test_argparse.py::test_subcommand_base_help",
"tests/test_argparse.py::test_subcommand_help",
"tests/test_argparse.py::test_subcommand_invalid_help"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-15 04:07:43+00:00
|
mit
| 5,062 |
|
python-cmd2__cmd2-721
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e3a64c8..615e282d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,12 @@
* Made optional arguments on the following completer methods keyword-only:
`delimiter_complete`, `flag_based_complete`, `index_based_complete`. `path_complete`, `shell_cmd_complete`
* Renamed history option from `--output-file` to `--output_file`
+ * Renamed `matches_sort_key` to `default_sort_key`. This value determines the default sort ordering of string
+ results like alias, command, category, macro, settable, and shortcut names. Unsorted tab-completion results
+ also are sorted with this key. Its default value (ALPHABETICAL_SORT_KEY) performs a case-insensitive alphabetical
+ sort, but it can be changed to a natural sort by setting the value to NATURAL_SORT_KEY.
+ * `StatementParser` now expects shortcuts to be passed in as dictionary. This eliminates the step of converting the
+ shortcuts dictionary into a tuple before creating `StatementParser`.
## 0.9.14 (June 29, 2019)
* Enhancements
diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py
index 737286c1..95ccf7b4 100644
--- a/cmd2/argparse_completer.py
+++ b/cmd2/argparse_completer.py
@@ -391,7 +391,7 @@ class AutoCompleter(object):
# If the user has not already sorted the CompletionItems, then sort them before appending the descriptions
if not self._cmd2_app.matches_sorted:
- completions.sort(key=self._cmd2_app.matches_sort_key)
+ completions.sort(key=self._cmd2_app.default_sort_key)
self._cmd2_app.matches_sorted = True
token_width = ansi_safe_wcswidth(action.dest)
diff --git a/cmd2/argparse_custom.py b/cmd2/argparse_custom.py
index 1cdb7840..5d8e76ef 100644
--- a/cmd2/argparse_custom.py
+++ b/cmd2/argparse_custom.py
@@ -74,7 +74,7 @@ Tab Completion:
completer_method
This is exactly like completer_function, but the function needs to be an instance method of a cmd2-based class.
When AutoCompleter calls the method, it will pass the app instance as the self argument. cmd2 provides
- a few completer methods for convenience (e.g. path_complete, delimiter_complete)
+ a few completer methods for convenience (e.g., path_complete, delimiter_complete)
Example:
This adds file-path completion to an argument
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index f094a9d7..0255d1ce 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -397,9 +397,6 @@ class Cmd(cmd.Cmd):
self._py_history = []
self.pyscript_name = 'app'
- if shortcuts is None:
- shortcuts = constants.DEFAULT_SHORTCUTS
- shortcuts = sorted(shortcuts.items(), reverse=True)
self.statement_parser = StatementParser(allow_redirection=allow_redirection,
terminators=terminators,
multiline_commands=multiline_commands,
@@ -468,11 +465,13 @@ class Cmd(cmd.Cmd):
elif transcript_files:
self._transcript_files = transcript_files
- # The default key for sorting tab completion matches. This only applies when the matches are not
- # already marked as sorted by setting self.matches_sorted to True. Its default value performs a
- # case-insensitive alphabetical sort. If natural sorting preferred, then set this to NATURAL_SORT_KEY.
- # Otherwise it can be set to any custom key to meet your needs.
- self.matches_sort_key = ALPHABETICAL_SORT_KEY
+ # The default key for sorting string results. Its default value performs a case-insensitive alphabetical sort.
+ # If natural sorting is preferred, then set this to NATURAL_SORT_KEY.
+ # cmd2 uses this key for sorting:
+ # command and category names
+ # alias, macro, settable, and shortcut names
+ # tab completion results when self.matches_sorted is False
+ self.default_sort_key = ALPHABETICAL_SORT_KEY
############################################################################################################
# The following variables are used by tab-completion functions. They are reset each time complete() is run
@@ -501,8 +500,8 @@ class Cmd(cmd.Cmd):
# quote matches that are completed in a delimited fashion
self.matches_delimited = False
- # Set to True before returning matches to complete() in cases where matches are sorted with custom ordering.
- # If False, then complete() will sort the matches using self.matches_sort_key before they are displayed.
+ # Set to True before returning matches to complete() in cases where matches have already been sorted.
+ # If False, then complete() will sort the matches using self.default_sort_key before they are displayed.
self.matches_sorted = False
# Set the pager(s) for use with the ppaged() method for displaying output using a pager
@@ -1107,7 +1106,7 @@ class Cmd(cmd.Cmd):
self.allow_closing_quote = False
# Sort the matches before any trailing slashes are added
- matches.sort(key=self.matches_sort_key)
+ matches.sort(key=self.default_sort_key)
self.matches_sorted = True
# Build display_matches and add a slash to directories
@@ -1553,8 +1552,8 @@ class Cmd(cmd.Cmd):
# Sort matches if they haven't already been sorted
if not self.matches_sorted:
- self.completion_matches.sort(key=self.matches_sort_key)
- self.display_matches.sort(key=self.matches_sort_key)
+ self.completion_matches.sort(key=self.default_sort_key)
+ self.display_matches.sort(key=self.default_sort_key)
self.matches_sorted = True
try:
@@ -2326,8 +2325,7 @@ class Cmd(cmd.Cmd):
else:
self.perror("Alias '{}' not found".format(cur_name))
else:
- sorted_aliases = utils.alphabetical_sort(self.aliases)
- for cur_alias in sorted_aliases:
+ for cur_alias in sorted(self.aliases, key=self.default_sort_key):
self.poutput("alias create {} {}".format(cur_alias, self.aliases[cur_alias]))
# Top-level parser for alias
@@ -2507,8 +2505,7 @@ class Cmd(cmd.Cmd):
else:
self.perror("Macro '{}' not found".format(cur_name))
else:
- sorted_macros = utils.alphabetical_sort(self.macros)
- for cur_macro in sorted_macros:
+ for cur_macro in sorted(self.macros, key=self.default_sort_key):
self.poutput("macro create {} {}".format(cur_macro, self.macros[cur_macro].value))
# Top-level parser for macro
@@ -2692,10 +2689,10 @@ class Cmd(cmd.Cmd):
"""Show a list of commands which help can be displayed for.
"""
# Get a sorted list of help topics
- help_topics = utils.alphabetical_sort(self.get_help_topics())
+ help_topics = sorted(self.get_help_topics(), key=self.default_sort_key)
# Get a sorted list of visible command names
- visible_commands = utils.alphabetical_sort(self.get_visible_commands())
+ visible_commands = sorted(self.get_visible_commands(), key=self.default_sort_key)
cmds_doc = []
cmds_undoc = []
@@ -2730,7 +2727,7 @@ class Cmd(cmd.Cmd):
# Categories found, Organize all commands by category
self.poutput('{}'.format(str(self.doc_leader)))
self.poutput('{}'.format(str(self.doc_header)), end="\n\n")
- for category in sorted(cmds_cats.keys()):
+ for category in sorted(cmds_cats.keys(), key=self.default_sort_key):
self._print_topics(category, cmds_cats[category], verbose)
self._print_topics('Other', cmds_doc, verbose)
@@ -2816,7 +2813,9 @@ class Cmd(cmd.Cmd):
@with_argparser(ArgParser())
def do_shortcuts(self, _: argparse.Namespace) -> None:
"""List available shortcuts"""
- result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.statement_parser.shortcuts))
+ # Sort the shortcut tuples by name
+ sorted_shortcuts = sorted(self.statement_parser.shortcuts, key=lambda x: self.default_sort_key(x[0]))
+ result = "\n".join('{}: {}'.format(sc[0], sc[1]) for sc in sorted_shortcuts)
self.poutput("Shortcuts for other commands:\n{}".format(result))
@with_argparser(ArgParser(epilog=INTERNAL_COMMAND_EPILOG))
@@ -2903,7 +2902,7 @@ class Cmd(cmd.Cmd):
maxlen = max(maxlen, len(result[p]))
if result:
- for p in sorted(result):
+ for p in sorted(result, key=self.default_sort_key):
if args.long:
self.poutput('{} # {}'.format(result[p].ljust(maxlen), self.settable[p]))
else:
diff --git a/cmd2/parsing.py b/cmd2/parsing.py
index 2e94516a..dbfabc80 100644
--- a/cmd2/parsing.py
+++ b/cmd2/parsing.py
@@ -249,7 +249,7 @@ class StatementParser:
terminators: Optional[Iterable[str]] = None,
multiline_commands: Optional[Iterable[str]] = None,
aliases: Optional[Dict[str, str]] = None,
- shortcuts: Optional[Iterable[Tuple[str, str]]] = None) -> None:
+ shortcuts: Optional[Dict[str, str]] = None) -> None:
"""Initialize an instance of StatementParser.
The following will get converted to an immutable tuple before storing internally:
@@ -261,7 +261,7 @@ class StatementParser:
:param terminators: iterable containing strings which should terminate multiline commands
:param multiline_commands: iterable containing the names of commands that accept multiline input
:param aliases: dictionary containing aliases
- :param shortcuts: an iterable of tuples with each tuple containing the shortcut and the expansion
+ :param shortcuts: dictionary containing shortcuts
"""
self.allow_redirection = allow_redirection
if terminators is None:
@@ -276,10 +276,13 @@ class StatementParser:
self.aliases = dict()
else:
self.aliases = aliases
+
if shortcuts is None:
- self.shortcuts = tuple()
- else:
- self.shortcuts = tuple(shortcuts)
+ shortcuts = constants.DEFAULT_SHORTCUTS
+
+ # Sort the shortcuts in descending order by name length because the longest match
+ # should take precedence. (e.g., @@file should match '@@' and not '@'.
+ self.shortcuts = tuple(sorted(shortcuts.items(), key=lambda x: len(x[0]), reverse=True))
# commands have to be a word, so make a regular expression
# that matches the first word in the line. This regex has three
|
python-cmd2/cmd2
|
1707ab8d5ee53b809af0d6ebbe5c12a48850dbe5
|
diff --git a/tests/test_argparse_completer.py b/tests/test_argparse_completer.py
index 4ad4c560..19ec551b 100644
--- a/tests/test_argparse_completer.py
+++ b/tests/test_argparse_completer.py
@@ -263,7 +263,7 @@ def test_complete_help(ac_app, command, text, completions):
else:
assert first_match is None
- assert ac_app.completion_matches == sorted(completions, key=ac_app.matches_sort_key)
+ assert ac_app.completion_matches == sorted(completions, key=ac_app.default_sort_key)
@pytest.mark.parametrize('command_and_args, text, completions', [
@@ -320,7 +320,7 @@ def test_autcomp_flag_completion(ac_app, command_and_args, text, completions):
else:
assert first_match is None
- assert ac_app.completion_matches == sorted(completions, key=ac_app.matches_sort_key)
+ assert ac_app.completion_matches == sorted(completions, key=ac_app.default_sort_key)
@pytest.mark.parametrize('flag, text, completions', [
@@ -346,7 +346,7 @@ def test_autocomp_flag_choices_completion(ac_app, flag, text, completions):
else:
assert first_match is None
- assert ac_app.completion_matches == sorted(completions, key=ac_app.matches_sort_key)
+ assert ac_app.completion_matches == sorted(completions, key=ac_app.default_sort_key)
@pytest.mark.parametrize('pos, text, completions', [
@@ -369,7 +369,7 @@ def test_autocomp_positional_choices_completion(ac_app, pos, text, completions):
else:
assert first_match is None
- assert ac_app.completion_matches == sorted(completions, key=ac_app.matches_sort_key)
+ assert ac_app.completion_matches == sorted(completions, key=ac_app.default_sort_key)
@pytest.mark.parametrize('flag, text, completions', [
@@ -389,7 +389,7 @@ def test_autocomp_flag_completers(ac_app, flag, text, completions):
else:
assert first_match is None
- assert ac_app.completion_matches == sorted(completions, key=ac_app.matches_sort_key)
+ assert ac_app.completion_matches == sorted(completions, key=ac_app.default_sort_key)
@pytest.mark.parametrize('pos, text, completions', [
@@ -410,7 +410,7 @@ def test_autocomp_positional_completers(ac_app, pos, text, completions):
else:
assert first_match is None
- assert ac_app.completion_matches == sorted(completions, key=ac_app.matches_sort_key)
+ assert ac_app.completion_matches == sorted(completions, key=ac_app.default_sort_key)
def test_autocomp_blank_token(ac_app):
@@ -548,7 +548,7 @@ def test_autcomp_nargs(ac_app, args, completions):
else:
assert first_match is None
- assert ac_app.completion_matches == sorted(completions, key=ac_app.matches_sort_key)
+ assert ac_app.completion_matches == sorted(completions, key=ac_app.default_sort_key)
@pytest.mark.parametrize('command_and_args, text, is_error', [
diff --git a/tests/test_completion.py b/tests/test_completion.py
index 1411cc49..3cee1955 100644
--- a/tests/test_completion.py
+++ b/tests/test_completion.py
@@ -174,20 +174,20 @@ def test_complete_macro(base_app, request):
assert first_match is not None and base_app.completion_matches == expected
-def test_matches_sort_key(cmd2_app):
+def test_default_sort_key(cmd2_app):
text = ''
line = 'test_sort_key {}'.format(text)
endidx = len(line)
begidx = endidx - len(text)
# First do alphabetical sorting
- cmd2_app.matches_sort_key = cmd2.cmd2.ALPHABETICAL_SORT_KEY
+ cmd2_app.default_sort_key = cmd2.cmd2.ALPHABETICAL_SORT_KEY
expected = ['1', '11', '2']
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
assert first_match is not None and cmd2_app.completion_matches == expected
# Now switch to natural sorting
- cmd2_app.matches_sort_key = cmd2.cmd2.NATURAL_SORT_KEY
+ cmd2_app.default_sort_key = cmd2.cmd2.NATURAL_SORT_KEY
expected = ['1', '2', '11']
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
assert first_match is not None and cmd2_app.completion_matches == expected
diff --git a/tests/test_history.py b/tests/test_history.py
index add93ea6..88f38172 100644
--- a/tests/test_history.py
+++ b/tests/test_history.py
@@ -276,7 +276,7 @@ def parser():
'l': '!ls -al',
'anothermultiline': 'multiline',
'fake': 'run_pyscript'},
- shortcuts=[('?', 'help'), ('!', 'shell')]
+ shortcuts={'?': 'help', '!': 'shell'}
)
return parser
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index 13a535c0..a629d9fa 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -21,7 +21,7 @@ def parser():
'l': '!ls -al',
'anothermultiline': 'multiline',
'fake': 'run_pyscript'},
- shortcuts=[('?', 'help'), ('!', 'shell')]
+ shortcuts={'?': 'help', '!': 'shell'}
)
return parser
|
Change `matches_sort_key` to `default_sort_key`
Currently `matches_sort_key` only applies to the default order in which tab completions are sorted. Consider renaming it to `default_sort_key` and have it apply to how all strings are sorted when displayed. This would affect:
- command names in **help** output
- category ordering
- alias and macro lists
- settable value lists
|
0.0
|
1707ab8d5ee53b809af0d6ebbe5c12a48850dbe5
|
[
"tests/test_argparse_completer.py::test_complete_help[-mu-completions0]",
"tests/test_argparse_completer.py::test_complete_help[music-cre-completions1]",
"tests/test_argparse_completer.py::test_complete_help[music",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---completions0]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag----completions1]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--n-completions2]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---n-completions3]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--r-completions5]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---r-completions6]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--s-completions9]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---s-completions10]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag-+-completions13]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag-++-completions14]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-l--completions0]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--list-s-completions1]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-f--completions2]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--function-ch-completions3]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-m--completions4]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--method-m-completions5]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-i--completions6]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int-1-completions7]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int---completions8]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int--1-completions9]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[1--completions0]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[1-s-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[2--completions2]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[2-ch-completions3]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[3--completions4]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[3-m-completions5]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[-f--completions0]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[--function-f-completions1]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[-m--completions2]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[--method-m-completions3]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[1--completions0]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[1-c-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[2--completions2]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[2-m-completions3]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--set_value-completions0]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--set_value",
"tests/test_argparse_completer.py::test_autcomp_nargs[--one_or_more-completions4]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--one_or_more",
"tests/test_argparse_completer.py::test_autcomp_nargs[--optional-completions6]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--optional",
"tests/test_argparse_completer.py::test_autcomp_nargs[--range-completions8]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--range",
"tests/test_argparse_completer.py::test_autcomp_nargs[--remainder-completions11]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--remainder",
"tests/test_argparse_completer.py::test_autcomp_nargs[--",
"tests/test_argparse_completer.py::test_autcomp_nargs[-completions17]",
"tests/test_argparse_completer.py::test_autcomp_nargs[positional-completions18]",
"tests/test_argparse_completer.py::test_autcomp_nargs[positional",
"tests/test_argparse_completer.py::test_autcomp_nargs[the",
"tests/test_completion.py::test_default_sort_key",
"tests/test_history.py::test_multiline_histitem",
"tests/test_history.py::test_multiline_histitem_verbose",
"tests/test_parsing.py::test_parse_empty_string",
"tests/test_parsing.py::test_tokenize[command-tokens0]",
"tests/test_parsing.py::test_tokenize[#",
"tests/test_parsing.py::test_tokenize[not",
"tests/test_parsing.py::test_tokenize[42",
"tests/test_parsing.py::test_tokenize[l-tokens4]",
"tests/test_parsing.py::test_tokenize[termbare",
"tests/test_parsing.py::test_tokenize[termbare;",
"tests/test_parsing.py::test_tokenize[termbare&",
"tests/test_parsing.py::test_tokenize[help|less-tokens9]",
"tests/test_parsing.py::test_tokenize[l|less-tokens10]",
"tests/test_parsing.py::test_parse_single_word[plainword]",
"tests/test_parsing.py::test_parse_single_word[\"one",
"tests/test_parsing.py::test_parse_single_word['one",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare;-;]",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare&-&]",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare;",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare&",
"tests/test_parsing.py::test_parse_command_with_args",
"tests/test_parsing.py::test_parse_command_with_quoted_args",
"tests/test_parsing.py::test_parse_command_with_args_terminator_and_suffix",
"tests/test_parsing.py::test_parse_comment",
"tests/test_parsing.py::test_parse_embedded_comment_char",
"tests/test_parsing.py::test_parse_simple_pipe[simple",
"tests/test_parsing.py::test_parse_simple_pipe[simple|piped]",
"tests/test_parsing.py::test_parse_double_pipe_is_not_a_pipe",
"tests/test_parsing.py::test_parse_complex_pipe",
"tests/test_parsing.py::test_parse_redirect[help",
"tests/test_parsing.py::test_parse_redirect[help>out.txt->]",
"tests/test_parsing.py::test_parse_redirect[help>>out.txt->>]",
"tests/test_parsing.py::test_parse_redirect_with_args",
"tests/test_parsing.py::test_parse_redirect_with_dash_in_path",
"tests/test_parsing.py::test_parse_redirect_append",
"tests/test_parsing.py::test_parse_pipe_then_redirect",
"tests/test_parsing.py::test_parse_multiple_pipes",
"tests/test_parsing.py::test_redirect_then_pipe",
"tests/test_parsing.py::test_append_then_pipe",
"tests/test_parsing.py::test_append_then_redirect",
"tests/test_parsing.py::test_redirect_then_append",
"tests/test_parsing.py::test_redirect_to_quoted_string",
"tests/test_parsing.py::test_redirect_to_single_quoted_string",
"tests/test_parsing.py::test_redirect_to_empty_quoted_string",
"tests/test_parsing.py::test_redirect_to_empty_single_quoted_string",
"tests/test_parsing.py::test_parse_output_to_paste_buffer",
"tests/test_parsing.py::test_parse_redirect_inside_terminator",
"tests/test_parsing.py::test_parse_multiple_terminators[multiline",
"tests/test_parsing.py::test_parse_unfinished_multiliine_command",
"tests/test_parsing.py::test_parse_basic_multiline_command",
"tests/test_parsing.py::test_parse_multiline_command_ignores_redirectors_within_it[multiline",
"tests/test_parsing.py::test_parse_multiline_terminated_by_empty_line",
"tests/test_parsing.py::test_parse_multiline_with_embedded_newline[multiline",
"tests/test_parsing.py::test_parse_multiline_ignores_terminators_in_quotes",
"tests/test_parsing.py::test_parse_command_with_unicode_args",
"tests/test_parsing.py::test_parse_unicode_command",
"tests/test_parsing.py::test_parse_redirect_to_unicode_filename",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias-help-]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42-theanswer-]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls-shell-ls]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[l-shell-ls",
"tests/test_parsing.py::test_parse_alias_on_multiline_command",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>out.txt->]",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>>out.txt->>]",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias|less]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias",
"tests/test_parsing.py::test_parse_command_only_command_and_args",
"tests/test_parsing.py::test_parse_command_only_strips_line",
"tests/test_parsing.py::test_parse_command_only_expands_alias",
"tests/test_parsing.py::test_parse_command_only_expands_shortcuts",
"tests/test_parsing.py::test_parse_command_only_quoted_args",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>out.txt->out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>>out.txt->>out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help|less-|less]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias;-;]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help",
"tests/test_parsing.py::test_parse_command_only_specialchars[help;",
"tests/test_parsing.py::test_parse_command_only_empty[]",
"tests/test_parsing.py::test_parse_command_only_empty[;]",
"tests/test_parsing.py::test_parse_command_only_empty[;;]",
"tests/test_parsing.py::test_parse_command_only_empty[;;",
"tests/test_parsing.py::test_parse_command_only_empty[&]",
"tests/test_parsing.py::test_parse_command_only_empty[&",
"tests/test_parsing.py::test_parse_command_only_empty[",
"tests/test_parsing.py::test_parse_command_only_empty[>]",
"tests/test_parsing.py::test_parse_command_only_empty[']",
"tests/test_parsing.py::test_parse_command_only_empty[\"]",
"tests/test_parsing.py::test_parse_command_only_empty[|]",
"tests/test_parsing.py::test_parse_command_only_multiline",
"tests/test_parsing.py::test_is_valid_command_invalid",
"tests/test_parsing.py::test_is_valid_command_valid"
] |
[
"tests/test_argparse_completer.py::test_help[music]",
"tests/test_argparse_completer.py::test_help[music",
"tests/test_argparse_completer.py::test_autocomp_blank_token",
"tests/test_argparse_completer.py::test_completion_items[1-False]",
"tests/test_argparse_completer.py::test_completion_items[5-True]",
"tests/test_argparse_completer.py::test_completion_items[100-False]",
"tests/test_argparse_completer.py::test_unfinished_flag_error[hint",
"tests/test_argparse_completer.py::test_unfinished_flag_error[nargs",
"tests/test_argparse_completer.py::test_completion_items_default_header",
"tests/test_argparse_completer.py::test_autocomp_hint[hint--True]",
"tests/test_argparse_completer.py::test_autocomp_hint[hint",
"tests/test_argparse_completer.py::test_autocomp_hint[nargs",
"tests/test_argparse_completer.py::test_autocomp_hint[hint---False]",
"tests/test_argparse_completer.py::test_autocomp_hint_multiple_lines",
"tests/test_argparse_completer.py::test_autocomp_hint_no_help_text",
"tests/test_argparse_completer.py::test_single_prefix_char",
"tests/test_argparse_completer.py::test_looks_like_flag",
"tests/test_argparse_completer.py::test_complete_command_no_tokens",
"tests/test_argparse_completer.py::test_complete_command_help_no_tokens",
"tests/test_completion.py::test_cmd2_command_completion_single",
"tests/test_completion.py::test_complete_command_single",
"tests/test_completion.py::test_complete_empty_arg",
"tests/test_completion.py::test_complete_bogus_command",
"tests/test_completion.py::test_complete_exception",
"tests/test_completion.py::test_complete_macro",
"tests/test_completion.py::test_cmd2_command_completion_multiple",
"tests/test_completion.py::test_cmd2_command_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_completion_single",
"tests/test_completion.py::test_cmd2_help_completion_multiple",
"tests/test_completion.py::test_cmd2_help_completion_nomatch",
"tests/test_completion.py::test_shell_command_completion_shortcut",
"tests/test_completion.py::test_shell_command_completion_doesnt_match_wildcards",
"tests/test_completion.py::test_shell_command_completion_multiple",
"tests/test_completion.py::test_shell_command_completion_nomatch",
"tests/test_completion.py::test_shell_command_completion_doesnt_complete_when_just_shell",
"tests/test_completion.py::test_shell_command_completion_does_path_completion_when_after_command",
"tests/test_completion.py::test_shell_commmand_complete_in_path",
"tests/test_completion.py::test_path_completion_single_end",
"tests/test_completion.py::test_path_completion_multiple",
"tests/test_completion.py::test_path_completion_nomatch",
"tests/test_completion.py::test_default_to_shell_completion",
"tests/test_completion.py::test_path_completion_no_text",
"tests/test_completion.py::test_path_completion_no_path",
"tests/test_completion.py::test_path_completion_cwd_is_root_dir",
"tests/test_completion.py::test_path_completion_doesnt_match_wildcards",
"tests/test_completion.py::test_path_completion_complete_user",
"tests/test_completion.py::test_path_completion_user_path_expansion",
"tests/test_completion.py::test_path_completion_directories_only",
"tests/test_completion.py::test_basic_completion_single",
"tests/test_completion.py::test_basic_completion_multiple",
"tests/test_completion.py::test_basic_completion_nomatch",
"tests/test_completion.py::test_delimiter_completion",
"tests/test_completion.py::test_flag_based_completion_single",
"tests/test_completion.py::test_flag_based_completion_multiple",
"tests/test_completion.py::test_flag_based_completion_nomatch",
"tests/test_completion.py::test_flag_based_default_completer",
"tests/test_completion.py::test_flag_based_callable_completer",
"tests/test_completion.py::test_index_based_completion_single",
"tests/test_completion.py::test_index_based_completion_multiple",
"tests/test_completion.py::test_index_based_completion_nomatch",
"tests/test_completion.py::test_index_based_default_completer",
"tests/test_completion.py::test_index_based_callable_completer",
"tests/test_completion.py::test_tokens_for_completion_quoted",
"tests/test_completion.py::test_tokens_for_completion_unclosed_quote",
"tests/test_completion.py::test_tokens_for_completion_redirect",
"tests/test_completion.py::test_tokens_for_completion_quoted_redirect",
"tests/test_completion.py::test_tokens_for_completion_redirect_off",
"tests/test_completion.py::test_add_opening_quote_basic_no_text",
"tests/test_completion.py::test_add_opening_quote_basic_nothing_added",
"tests/test_completion.py::test_add_opening_quote_basic_quote_added",
"tests/test_completion.py::test_add_opening_quote_basic_single_quote_added",
"tests/test_completion.py::test_add_opening_quote_basic_text_is_common_prefix",
"tests/test_completion.py::test_add_opening_quote_delimited_no_text",
"tests/test_completion.py::test_add_opening_quote_delimited_nothing_added",
"tests/test_completion.py::test_add_opening_quote_delimited_quote_added",
"tests/test_completion.py::test_add_opening_quote_delimited_text_is_common_prefix",
"tests/test_completion.py::test_add_opening_quote_delimited_space_in_prefix",
"tests/test_completion.py::test_no_completer",
"tests/test_completion.py::test_quote_as_command",
"tests/test_completion.py::test_redirect_complete[fake-RedirCompType.DEFAULT]",
"tests/test_completion.py::test_redirect_complete[fake",
"tests/test_completion.py::test_cmd2_subcommand_completion_single_end",
"tests/test_completion.py::test_cmd2_subcommand_completion_multiple",
"tests/test_completion.py::test_cmd2_subcommand_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_single",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_multiple",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_nomatch",
"tests/test_completion.py::test_subcommand_tab_completion",
"tests/test_completion.py::test_subcommand_tab_completion_with_no_completer",
"tests/test_completion.py::test_subcommand_tab_completion_space_in_text",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_single_end",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_multiple",
"tests/test_completion.py::test_cmd2_subcmd_with_unknown_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_single_scu",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_multiple_scu",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_with_flags_before_command",
"tests/test_completion.py::test_complete_help_subcommand_with_no_command",
"tests/test_completion.py::test_cmd2_help_subcommand_completion_nomatch_scu",
"tests/test_completion.py::test_subcommand_tab_completion_scu",
"tests/test_completion.py::test_subcommand_tab_completion_with_no_completer_scu",
"tests/test_completion.py::test_subcommand_tab_completion_space_in_text_scu",
"tests/test_history.py::test_readline_remove_history_item",
"tests/test_history.py::test_history_class_span",
"tests/test_history.py::test_persisted_history_span",
"tests/test_history.py::test_history_class_get",
"tests/test_history.py::test_history_str_search",
"tests/test_history.py::test_history_regex_search",
"tests/test_history.py::test_history_max_length_zero",
"tests/test_history.py::test_history_max_length_negative",
"tests/test_history.py::test_history_max_length",
"tests/test_history.py::test_history_item_instantiate",
"tests/test_history.py::test_history_item_properties",
"tests/test_history.py::test_base_history",
"tests/test_history.py::test_history_script_format",
"tests/test_history.py::test_history_with_string_argument",
"tests/test_history.py::test_history_expanded_with_string_argument",
"tests/test_history.py::test_history_expanded_with_regex_argument",
"tests/test_history.py::test_history_with_integer_argument",
"tests/test_history.py::test_history_with_integer_span",
"tests/test_history.py::test_history_with_span_start",
"tests/test_history.py::test_history_with_span_end",
"tests/test_history.py::test_history_with_span_index_error",
"tests/test_history.py::test_history_output_file",
"tests/test_history.py::test_history_bad_output_file",
"tests/test_history.py::test_history_edit",
"tests/test_history.py::test_history_run_all_commands",
"tests/test_history.py::test_history_run_one_command",
"tests/test_history.py::test_history_clear",
"tests/test_history.py::test_history_verbose_with_other_options",
"tests/test_history.py::test_history_verbose",
"tests/test_history.py::test_history_script_with_invalid_options",
"tests/test_history.py::test_history_script",
"tests/test_history.py::test_history_expanded_with_invalid_options",
"tests/test_history.py::test_history_expanded",
"tests/test_history.py::test_history_script_expanded",
"tests/test_history.py::test_base_help_history",
"tests/test_history.py::test_exclude_from_history",
"tests/test_history.py::test_history_file_is_directory",
"tests/test_history.py::test_history_file_permission_error",
"tests/test_history.py::test_history_file_conversion_no_truncate_on_init",
"tests/test_history.py::test_history_populates_readline",
"tests/test_history.py::test_persist_history_ensure_no_error_if_no_histfile",
"tests/test_history.py::test_persist_history_permission_error",
"tests/test_parsing.py::test_parse_empty_string_default",
"tests/test_parsing.py::test_tokenize_default[command-tokens0]",
"tests/test_parsing.py::test_tokenize_default[#comment-tokens1]",
"tests/test_parsing.py::test_tokenize_default[not",
"tests/test_parsing.py::test_tokenize_default[termbare",
"tests/test_parsing.py::test_tokenize_default[termbare;",
"tests/test_parsing.py::test_tokenize_default[termbare&",
"tests/test_parsing.py::test_tokenize_default[help|less-tokens7]",
"tests/test_parsing.py::test_tokenize_unclosed_quotes",
"tests/test_parsing.py::test_command_and_args[tokens0--]",
"tests/test_parsing.py::test_command_and_args[tokens1-command-]",
"tests/test_parsing.py::test_command_and_args[tokens2-command-arg1",
"tests/test_parsing.py::test_parse_unclosed_quotes",
"tests/test_parsing.py::test_empty_statement_raises_exception",
"tests/test_parsing.py::test_statement_initialization",
"tests/test_parsing.py::test_statement_is_immutable",
"tests/test_parsing.py::test_macro_normal_arg_pattern",
"tests/test_parsing.py::test_macro_escaped_arg_pattern"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-07-16 15:03:43+00:00
|
mit
| 5,063 |
|
python-cmd2__cmd2-781
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f6e14f11..c69a0549 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@
argparse argument. This is helpful when one argument determines what is tab completed for another argument.
If these functions have an argument called `arg_tokens`, then AutoCompleter will automatically pass this
dictionary to them.
+ * Added CompletionError class that can be raised during argparse-based tab completion and printed to the user
## 0.9.16 (August 7, 2019)
* Bug Fixes
diff --git a/cmd2/__init__.py b/cmd2/__init__.py
index 2653051a..c496a4f7 100644
--- a/cmd2/__init__.py
+++ b/cmd2/__init__.py
@@ -11,7 +11,7 @@ except DistributionNotFound:
pass
from .ansi import style
-from .argparse_custom import Cmd2ArgumentParser, CompletionItem
+from .argparse_custom import Cmd2ArgumentParser, CompletionError, CompletionItem
from .cmd2 import Cmd, Statement, EmptyStatement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
from .constants import DEFAULT_SHORTCUTS
diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py
index fb485348..a866b3ff 100644
--- a/cmd2/argparse_completer.py
+++ b/cmd2/argparse_completer.py
@@ -15,8 +15,9 @@ from typing import Dict, List, Optional, Union
from . import cmd2
from . import utils
from .ansi import ansi_safe_wcswidth, style_error
+from .argparse_custom import ATTR_CHOICES_CALLABLE, INFINITY, generate_range_error
from .argparse_custom import ATTR_SUPPRESS_TAB_HINT, ATTR_DESCRIPTIVE_COMPLETION_HEADER, ATTR_NARGS_RANGE
-from .argparse_custom import ChoicesCallable, CompletionItem, ATTR_CHOICES_CALLABLE, INFINITY, generate_range_error
+from .argparse_custom import ChoicesCallable, CompletionError, CompletionItem
from .rl_utils import rl_force_redisplay
# If no descriptive header is supplied, then this will be used instead
@@ -319,8 +320,12 @@ class AutoCompleter(object):
# Check if we are completing a flag's argument
if flag_arg_state is not None:
- completion_results = self._complete_for_arg(flag_arg_state.action, text, line,
- begidx, endidx, consumed_arg_values)
+ try:
+ completion_results = self._complete_for_arg(flag_arg_state.action, text, line,
+ begidx, endidx, consumed_arg_values)
+ except CompletionError as ex:
+ self._print_completion_error(flag_arg_state.action, ex)
+ return []
# If we have results, then return them
if completion_results:
@@ -341,8 +346,12 @@ class AutoCompleter(object):
action = self._positional_actions[pos_index]
pos_arg_state = AutoCompleter._ArgumentState(action)
- completion_results = self._complete_for_arg(pos_arg_state.action, text, line,
- begidx, endidx, consumed_arg_values)
+ try:
+ completion_results = self._complete_for_arg(pos_arg_state.action, text, line,
+ begidx, endidx, consumed_arg_values)
+ except CompletionError as ex:
+ self._print_completion_error(pos_arg_state.action, ex)
+ return []
# If we have results, then return them
if completion_results:
@@ -456,7 +465,11 @@ class AutoCompleter(object):
def _complete_for_arg(self, arg_action: argparse.Action,
text: str, line: str, begidx: int, endidx: int,
consumed_arg_values: Dict[str, List[str]]) -> List[str]:
- """Tab completion routine for an argparse argument"""
+ """
+ Tab completion routine for an argparse argument
+ :return: list of completions
+ :raises CompletionError if the completer or choices function this calls raises one
+ """
# Check if the arg provides choices to the user
if arg_action.choices is not None:
arg_choices = arg_action.choices
@@ -520,24 +533,35 @@ class AutoCompleter(object):
return self._format_completions(arg_action, results)
@staticmethod
- def _print_arg_hint(arg_action: argparse.Action) -> None:
- """Print argument hint to the terminal when tab completion results in no results"""
-
- # Check if hinting is disabled
- suppress_hint = getattr(arg_action, ATTR_SUPPRESS_TAB_HINT, False)
- if suppress_hint or arg_action.help == argparse.SUPPRESS or arg_action.dest == argparse.SUPPRESS:
- return
-
+ def _format_message_prefix(arg_action: argparse.Action) -> str:
+ """Format the arg prefix text that appears before messages printed to the user"""
# Check if this is a flag
if arg_action.option_strings:
flags = ', '.join(arg_action.option_strings)
param = ' ' + str(arg_action.dest).upper()
- prefix = '{}{}'.format(flags, param)
+ return '{}{}'.format(flags, param)
# Otherwise this is a positional
else:
- prefix = '{}'.format(str(arg_action.dest).upper())
+ return '{}'.format(str(arg_action.dest).upper())
+
+ @staticmethod
+ def _print_message(msg: str) -> None:
+ """Print a message instead of tab completions and redraw the prompt and input line"""
+ print(msg)
+ rl_force_redisplay()
+
+ def _print_arg_hint(self, arg_action: argparse.Action) -> None:
+ """
+ Print argument hint to the terminal when tab completion results in no results
+ :param arg_action: action being tab completed
+ """
+ # Check if hinting is disabled
+ suppress_hint = getattr(arg_action, ATTR_SUPPRESS_TAB_HINT, False)
+ if suppress_hint or arg_action.help == argparse.SUPPRESS or arg_action.dest == argparse.SUPPRESS:
+ return
+ prefix = self._format_message_prefix(arg_action)
prefix = ' {0: <{width}} '.format(prefix, width=20)
pref_len = len(prefix)
@@ -545,28 +569,36 @@ class AutoCompleter(object):
help_lines = help_text.splitlines()
if len(help_lines) == 1:
- print('\nHint:\n{}{}\n'.format(prefix, help_lines[0]))
+ self._print_message('\nHint:\n{}{}\n'.format(prefix, help_lines[0]))
else:
out_str = '\n{}'.format(prefix)
out_str += '\n{0: <{width}}'.format('', width=pref_len).join(help_lines)
- print('\nHint:' + out_str + '\n')
+ self._print_message('\nHint:' + out_str + '\n')
- # Redraw prompt and input line
- rl_force_redisplay()
-
- @staticmethod
- def _print_unfinished_flag_error(flag_arg_state: _ArgumentState) -> None:
- """Print an error during tab completion when the user has not finished the current flag"""
- flags = ', '.join(flag_arg_state.action.option_strings)
- param = ' ' + str(flag_arg_state.action.dest).upper()
- prefix = '{}{}'.format(flags, param)
+ def _print_unfinished_flag_error(self, flag_arg_state: _ArgumentState) -> None:
+ """
+ Print an error during tab completion when the user has not finished the current flag
+ :param flag_arg_state: information about the unfinished flag action
+ """
+ prefix = self._format_message_prefix(flag_arg_state.action)
out_str = "\nError:\n"
out_str += ' {0: <{width}} '.format(prefix, width=20)
out_str += generate_range_error(flag_arg_state.min, flag_arg_state.max)
out_str += ' ({} entered)'.format(flag_arg_state.count)
- print(style_error('{}\n'.format(out_str)))
+ self._print_message(style_error('{}\n'.format(out_str)))
- # Redraw prompt and input line
- rl_force_redisplay()
+ def _print_completion_error(self, arg_action: argparse.Action, completion_error: CompletionError) -> None:
+ """
+ Print a CompletionError to the user
+ :param arg_action: action being tab completed
+ :param completion_error: error that occurred
+ """
+ prefix = self._format_message_prefix(arg_action)
+
+ out_str = "\nError:\n"
+ out_str += ' {0: <{width}} '.format(prefix, width=20)
+ out_str += str(completion_error)
+
+ self._print_message(style_error('{}\n'.format(out_str)))
diff --git a/cmd2/argparse_custom.py b/cmd2/argparse_custom.py
index 940d6064..f7dbc8a3 100644
--- a/cmd2/argparse_custom.py
+++ b/cmd2/argparse_custom.py
@@ -94,7 +94,7 @@ Tab Completion:
as dynamic. Therefore it is up to the developer to validate if the user has typed an acceptable value for these
arguments.
- The following functions exist in cases where you may want to manually add choice providing function/methods to
+ The following functions exist in cases where you may want to manually a add choice-providing function/method to
an existing argparse action. For instance, in __init__() of a custom action class.
set_choices_function(action, func)
@@ -116,6 +116,13 @@ Tab Completion:
their values. All tokens are stored in the dictionary as the raw strings provided on the command line. It is up to
the developer to determine if the user entered the correct argument type (e.g. int) and validate their values.
+CompletionError Class:
+ Raised during tab-completion operations to report any sort of error you want printed by the AutoCompleter
+
+ Example use cases
+ - Reading a database to retrieve a tab completion data set failed
+ - A previous command line argument that determines the data set being completed is invalid
+
CompletionItem Class:
This class was added to help in cases where uninformative data is being tab completed. For instance,
tab completing ID numbers isn't very helpful to a user without context. Returning a list of CompletionItems
@@ -221,6 +228,17 @@ def generate_range_error(range_min: int, range_max: Union[int, float]) -> str:
return err_str
+class CompletionError(Exception):
+ """
+ Raised during tab-completion operations to report any sort of error you want printed by the AutoCompleter
+
+ Example use cases
+ - Reading a database to retrieve a tab completion data set failed
+ - A previous command line argument that determines the data set being completed is invalid
+ """
+ pass
+
+
class CompletionItem(str):
"""
Completion item with descriptive text attached
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 87f8684d..6bfcfdc8 100755
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -341,7 +341,7 @@ class Cmd(cmd.Cmd):
def __init__(self, completekey: str = 'tab', stdin=None, stdout=None, *,
persistent_history_file: str = '', persistent_history_length: int = 1000,
- startup_script: Optional[str] = None, use_ipython: bool = False,
+ startup_script: str = '', use_ipython: bool = False,
allow_cli_args: bool = True, transcript_files: Optional[List[str]] = None,
allow_redirection: bool = True, multiline_commands: Optional[List[str]] = None,
terminators: Optional[List[str]] = None, shortcuts: Optional[Dict[str, str]] = None) -> None:
@@ -499,7 +499,7 @@ class Cmd(cmd.Cmd):
self._startup_commands = []
# If a startup script is provided, then execute it in the startup commands
- if startup_script is not None:
+ if startup_script:
startup_script = os.path.abspath(os.path.expanduser(startup_script))
if os.path.exists(startup_script) and os.path.getsize(startup_script) > 0:
self._startup_commands.append("run_script '{}'".format(startup_script))
|
python-cmd2/cmd2
|
27a0adbe53c7cdeda240c325a6f59b7cca0e7bfd
|
diff --git a/tests/test_argparse_completer.py b/tests/test_argparse_completer.py
index 788a7e59..308a4d95 100644
--- a/tests/test_argparse_completer.py
+++ b/tests/test_argparse_completer.py
@@ -9,7 +9,7 @@ from typing import List
import pytest
import cmd2
-from cmd2 import with_argparser, Cmd2ArgumentParser, CompletionItem
+from cmd2 import with_argparser, Cmd2ArgumentParser, CompletionError, CompletionItem
from cmd2.utils import StdSim, basic_complete
from .conftest import run_cmd, complete_tester
@@ -210,6 +210,27 @@ class AutoCompleteTester(cmd2.Cmd):
def do_hint(self, args: argparse.Namespace) -> None:
pass
+ ############################################################################################################
+ # Begin code related to CompletionError
+ ############################################################################################################
+ def completer_raise_error(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
+ """Raises CompletionError"""
+ raise CompletionError('completer broke something')
+
+ def choice_raise_error(self) -> List[str]:
+ """Raises CompletionError"""
+ raise CompletionError('choice broke something')
+
+ comp_error_parser = Cmd2ArgumentParser()
+ comp_error_parser.add_argument('completer', help='positional arg',
+ completer_method=completer_raise_error)
+ comp_error_parser.add_argument('--choice', help='flag arg',
+ choices_method=choice_raise_error)
+
+ @with_argparser(comp_error_parser)
+ def do_raise_completion_error(self, args: argparse.Namespace) -> None:
+ pass
+
############################################################################################################
# Begin code related to receiving arg_tokens
############################################################################################################
@@ -723,6 +744,25 @@ Hint:
'''
[email protected]('args, text', [
+ # Exercise a flag arg and choices function that raises a CompletionError
+ ('--choice ', 'choice'),
+
+ # Exercise a positional arg and completer that raises a CompletionError
+ ('', 'completer')
+])
+def test_completion_error(ac_app, capsys, args, text):
+ line = 'raise_completion_error {} {}'.format(args, text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ first_match = complete_tester(text, line, begidx, endidx, ac_app)
+ out, err = capsys.readouterr()
+
+ assert first_match is None
+ assert "{} broke something".format(text) in out
+
+
@pytest.mark.parametrize('command_and_args, completions', [
# Exercise a choices function that receives arg_tokens dictionary
('arg_tokens choice subcmd', ['choice', 'subcmd']),
|
Create CompletionError exception
Add an exception that can be raised during tab completion to print an error to the user.
Possible use cases
1. Reading a database to retrieve a tab completion data set failed
2. A previous command line argument that determines the data set being completed is invalid
|
0.0
|
27a0adbe53c7cdeda240c325a6f59b7cca0e7bfd
|
[
"tests/test_argparse_completer.py::test_help[music]",
"tests/test_argparse_completer.py::test_help[music",
"tests/test_argparse_completer.py::test_complete_help[-mu-completions0]",
"tests/test_argparse_completer.py::test_complete_help[music-cre-completions1]",
"tests/test_argparse_completer.py::test_complete_help[music-creab-completions2]",
"tests/test_argparse_completer.py::test_complete_help[music",
"tests/test_argparse_completer.py::test_complete_help[fake",
"tests/test_argparse_completer.py::test_subcommand_completions[create--completions0]",
"tests/test_argparse_completer.py::test_subcommand_completions[create-ja-completions1]",
"tests/test_argparse_completer.py::test_subcommand_completions[create-foo-completions2]",
"tests/test_argparse_completer.py::test_subcommand_completions[creab-ja-completions3]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---completions0]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag----completions1]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--n-completions2]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---n-completions3]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--r-completions5]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---r-completions6]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--s-completions9]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---s-completions10]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag-+-completions13]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag-++-completions14]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-l--completions0]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--list-s-completions1]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-f--completions2]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--function-ch-completions3]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-m--completions4]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--method-m-completions5]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-i--completions6]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int-1-completions7]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int---completions8]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int--1-completions9]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[1--completions0]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[1-s-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[2--completions2]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[2-ch-completions3]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[3--completions4]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[3-m-completions5]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[-f--completions0]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[--function-f-completions1]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[-m--completions2]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[--method-m-completions3]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[1--completions0]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[1-c-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[2--completions2]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[2-m-completions3]",
"tests/test_argparse_completer.py::test_autocomp_blank_token",
"tests/test_argparse_completer.py::test_completion_items[1-False]",
"tests/test_argparse_completer.py::test_completion_items[5-True]",
"tests/test_argparse_completer.py::test_completion_items[100-False]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--set_value-completions0]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--set_value",
"tests/test_argparse_completer.py::test_autcomp_nargs[--one_or_more-completions4]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--one_or_more",
"tests/test_argparse_completer.py::test_autcomp_nargs[--optional-completions6]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--optional",
"tests/test_argparse_completer.py::test_autcomp_nargs[--range-completions8]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--range",
"tests/test_argparse_completer.py::test_autcomp_nargs[--remainder-completions11]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--remainder",
"tests/test_argparse_completer.py::test_autcomp_nargs[--",
"tests/test_argparse_completer.py::test_autcomp_nargs[-completions17]",
"tests/test_argparse_completer.py::test_autcomp_nargs[positional-completions18]",
"tests/test_argparse_completer.py::test_autcomp_nargs[positional",
"tests/test_argparse_completer.py::test_autcomp_nargs[the",
"tests/test_argparse_completer.py::test_unfinished_flag_error[hint",
"tests/test_argparse_completer.py::test_unfinished_flag_error[nargs",
"tests/test_argparse_completer.py::test_completion_items_default_header",
"tests/test_argparse_completer.py::test_autocomp_hint[hint--True]",
"tests/test_argparse_completer.py::test_autocomp_hint[hint",
"tests/test_argparse_completer.py::test_autocomp_hint[nargs",
"tests/test_argparse_completer.py::test_autocomp_hint[hint---False]",
"tests/test_argparse_completer.py::test_autocomp_hint_multiple_lines",
"tests/test_argparse_completer.py::test_autocomp_hint_no_help_text",
"tests/test_argparse_completer.py::test_completion_error[--choice",
"tests/test_argparse_completer.py::test_completion_error[-completer]",
"tests/test_argparse_completer.py::test_arg_tokens[arg_tokens",
"tests/test_argparse_completer.py::test_single_prefix_char",
"tests/test_argparse_completer.py::test_looks_like_flag",
"tests/test_argparse_completer.py::test_complete_command_no_tokens",
"tests/test_argparse_completer.py::test_complete_command_help_no_tokens"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-09-23 19:12:01+00:00
|
mit
| 5,064 |
|
python-cmd2__cmd2-890
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4d662cf3..cb328f11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@
* Setting the following pyscript variables:
* `__name__`: __main__
* `__file__`: script path (as typed, ~ will be expanded)
+ * Only tab complete after redirection tokens if redirection is allowed
* Other
* Removed undocumented `py run` command since it was replaced by `run_pyscript` a while ago
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 3b1fbb6f..5a728e56 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -1050,8 +1050,8 @@ class Cmd(cmd.Cmd):
in_pipe = False
in_file_redir = True
- # Not a redirection token
- else:
+ # Only tab complete after redirection tokens if redirection is allowed
+ elif self.allow_redirection:
do_shell_completion = False
do_path_completion = False
|
python-cmd2/cmd2
|
729e152c525bc30d36f130f8dc8442aeb00d1de8
|
diff --git a/tests/test_completion.py b/tests/test_completion.py
index f545c8f9..e13d87de 100755
--- a/tests/test_completion.py
+++ b/tests/test_completion.py
@@ -902,11 +902,6 @@ class RedirCompType(enum.Enum):
DEFAULT = 3,
NONE = 4
- """
- fake > >
- fake | grep > file
- fake | grep > file >
- """
@pytest.mark.parametrize('line, comp_type', [
('fake', RedirCompType.DEFAULT),
@@ -933,31 +928,40 @@ class RedirCompType(enum.Enum):
('fake > file >>', RedirCompType.NONE),
])
def test_redirect_complete(cmd2_app, monkeypatch, line, comp_type):
- shell_cmd_complete_mock = mock.MagicMock(name='shell_cmd_complete')
- monkeypatch.setattr("cmd2.Cmd.shell_cmd_complete", shell_cmd_complete_mock)
-
- path_complete_mock = mock.MagicMock(name='path_complete')
- monkeypatch.setattr("cmd2.Cmd.path_complete", path_complete_mock)
-
- default_complete_mock = mock.MagicMock(name='fake_completer')
-
- text = ''
- line = '{} {}'.format(line, text)
- endidx = len(line)
- begidx = endidx - len(text)
+ # Test both cases of allow_redirection
+ cmd2_app.allow_redirection = True
+ for count in range(2):
+ shell_cmd_complete_mock = mock.MagicMock(name='shell_cmd_complete')
+ monkeypatch.setattr("cmd2.Cmd.shell_cmd_complete", shell_cmd_complete_mock)
+
+ path_complete_mock = mock.MagicMock(name='path_complete')
+ monkeypatch.setattr("cmd2.Cmd.path_complete", path_complete_mock)
+
+ default_complete_mock = mock.MagicMock(name='fake_completer')
+
+ text = ''
+ line = '{} {}'.format(line, text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ cmd2_app._redirect_complete(text, line, begidx, endidx, default_complete_mock)
+
+ if comp_type == RedirCompType.SHELL_CMD:
+ shell_cmd_complete_mock.assert_called_once()
+ elif comp_type == RedirCompType.PATH:
+ path_complete_mock.assert_called_once()
+ elif comp_type == RedirCompType.DEFAULT:
+ default_complete_mock.assert_called_once()
+ else:
+ shell_cmd_complete_mock.assert_not_called()
+ path_complete_mock.assert_not_called()
+ default_complete_mock.assert_not_called()
- cmd2_app._redirect_complete(text, line, begidx, endidx, default_complete_mock)
+ # Do the next test with allow_redirection as False
+ cmd2_app.allow_redirection = False
+ if comp_type != RedirCompType.DEFAULT:
+ comp_type = RedirCompType.NONE
- if comp_type == RedirCompType.SHELL_CMD:
- shell_cmd_complete_mock.assert_called_once()
- elif comp_type == RedirCompType.PATH:
- path_complete_mock.assert_called_once()
- elif comp_type == RedirCompType.DEFAULT:
- default_complete_mock.assert_called_once()
- else:
- shell_cmd_complete_mock.assert_not_called()
- path_complete_mock.assert_not_called()
- default_complete_mock.assert_not_called()
def test_complete_set_value(cmd2_app):
text = ''
|
Tab completions after pipe | is still active on disabled redirection
With
self.allow_redirection = False
I can list system commands using any_command | <TAB>
My goal is to lock user in CLI without any way to run system command or access system files and with that in mind default cmd2 is quite "open"
|
0.0
|
729e152c525bc30d36f130f8dc8442aeb00d1de8
|
[
"tests/test_completion.py::test_redirect_complete[fake"
] |
[
"tests/test_completion.py::test_cmd2_command_completion_single",
"tests/test_completion.py::test_complete_command_single",
"tests/test_completion.py::test_complete_empty_arg",
"tests/test_completion.py::test_complete_bogus_command",
"tests/test_completion.py::test_complete_exception",
"tests/test_completion.py::test_complete_macro",
"tests/test_completion.py::test_default_sort_key",
"tests/test_completion.py::test_cmd2_command_completion_multiple",
"tests/test_completion.py::test_cmd2_command_completion_nomatch",
"tests/test_completion.py::test_cmd2_help_completion_single",
"tests/test_completion.py::test_cmd2_help_completion_multiple",
"tests/test_completion.py::test_cmd2_help_completion_nomatch",
"tests/test_completion.py::test_shell_command_completion_shortcut",
"tests/test_completion.py::test_shell_command_completion_doesnt_match_wildcards",
"tests/test_completion.py::test_shell_command_completion_multiple",
"tests/test_completion.py::test_shell_command_completion_nomatch",
"tests/test_completion.py::test_shell_command_completion_doesnt_complete_when_just_shell",
"tests/test_completion.py::test_shell_command_completion_does_path_completion_when_after_command",
"tests/test_completion.py::test_shell_commmand_complete_in_path",
"tests/test_completion.py::test_path_completion_single_end",
"tests/test_completion.py::test_path_completion_multiple",
"tests/test_completion.py::test_path_completion_nomatch",
"tests/test_completion.py::test_default_to_shell_completion",
"tests/test_completion.py::test_path_completion_no_text",
"tests/test_completion.py::test_path_completion_no_path",
"tests/test_completion.py::test_path_completion_cwd_is_root_dir",
"tests/test_completion.py::test_path_completion_doesnt_match_wildcards",
"tests/test_completion.py::test_path_completion_complete_user",
"tests/test_completion.py::test_path_completion_user_path_expansion",
"tests/test_completion.py::test_path_completion_directories_only",
"tests/test_completion.py::test_basic_completion_single",
"tests/test_completion.py::test_basic_completion_multiple",
"tests/test_completion.py::test_basic_completion_nomatch",
"tests/test_completion.py::test_delimiter_completion",
"tests/test_completion.py::test_flag_based_completion_single",
"tests/test_completion.py::test_flag_based_completion_multiple",
"tests/test_completion.py::test_flag_based_completion_nomatch",
"tests/test_completion.py::test_flag_based_default_completer",
"tests/test_completion.py::test_flag_based_callable_completer",
"tests/test_completion.py::test_index_based_completion_single",
"tests/test_completion.py::test_index_based_completion_multiple",
"tests/test_completion.py::test_index_based_completion_nomatch",
"tests/test_completion.py::test_index_based_default_completer",
"tests/test_completion.py::test_index_based_callable_completer",
"tests/test_completion.py::test_tokens_for_completion_quoted",
"tests/test_completion.py::test_tokens_for_completion_unclosed_quote",
"tests/test_completion.py::test_tokens_for_completion_punctuation",
"tests/test_completion.py::test_tokens_for_completion_quoted_punctuation",
"tests/test_completion.py::test_add_opening_quote_basic_no_text",
"tests/test_completion.py::test_add_opening_quote_basic_nothing_added",
"tests/test_completion.py::test_add_opening_quote_basic_quote_added",
"tests/test_completion.py::test_add_opening_quote_basic_single_quote_added",
"tests/test_completion.py::test_add_opening_quote_basic_text_is_common_prefix",
"tests/test_completion.py::test_add_opening_quote_delimited_no_text",
"tests/test_completion.py::test_add_opening_quote_delimited_nothing_added",
"tests/test_completion.py::test_add_opening_quote_delimited_quote_added",
"tests/test_completion.py::test_add_opening_quote_delimited_text_is_common_prefix",
"tests/test_completion.py::test_add_opening_quote_delimited_space_in_prefix",
"tests/test_completion.py::test_no_completer",
"tests/test_completion.py::test_quote_as_command",
"tests/test_completion.py::test_complete_multiline_on_single_line",
"tests/test_completion.py::test_complete_multiline_on_multiple_lines",
"tests/test_completion.py::test_redirect_complete[fake-RedirCompType.DEFAULT]",
"tests/test_completion.py::test_complete_set_value",
"tests/test_completion.py::test_complete_set_value_invalid_settable",
"tests/test_completion.py::test_cmd2_subcommand_completion_single_end",
"tests/test_completion.py::test_cmd2_subcommand_completion_multiple",
"tests/test_completion.py::test_cmd2_subcommand_completion_nomatch",
"tests/test_completion.py::test_help_subcommand_completion_single",
"tests/test_completion.py::test_help_subcommand_completion_multiple",
"tests/test_completion.py::test_help_subcommand_completion_nomatch",
"tests/test_completion.py::test_subcommand_tab_completion",
"tests/test_completion.py::test_subcommand_tab_completion_with_no_completer",
"tests/test_completion.py::test_subcommand_tab_completion_space_in_text",
"tests/test_completion.py::test_subcmd_with_unknown_completion_single_end",
"tests/test_completion.py::test_subcmd_with_unknown_completion_multiple",
"tests/test_completion.py::test_subcmd_with_unknown_completion_nomatch",
"tests/test_completion.py::test_help_subcommand_completion_single_scu",
"tests/test_completion.py::test_help_subcommand_completion_multiple_scu",
"tests/test_completion.py::test_help_subcommand_completion_with_flags_before_command",
"tests/test_completion.py::test_complete_help_subcommands_with_blank_command",
"tests/test_completion.py::test_help_subcommand_completion_nomatch_scu",
"tests/test_completion.py::test_subcommand_tab_completion_scu",
"tests/test_completion.py::test_subcommand_tab_completion_with_no_completer_scu",
"tests/test_completion.py::test_subcommand_tab_completion_space_in_text_scu"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-17 17:13:28+00:00
|
mit
| 5,065 |
|
python-cmd2__cmd2-893
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb81ab17..6d91aaca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,4 +1,4 @@
-## 0.10.1 (TBD)
+## 0.10.1 (February TBD, 2020)
* Bug Fixes
* Corrected issue where the actual new value was not always being printed in do_set. This occurred in cases where
the typed value differed from what the setter had converted it to.
@@ -19,6 +19,7 @@
* Other
* Removed undocumented `py run` command since it was replaced by `run_pyscript` a while ago
* Renamed `AutoCompleter` to `ArgparseCompleter` for clarity
+ * Custom `EmptyStatement` exception is no longer part of the documented public API
## 0.10.0 (February 7, 2020)
* Enhancements
diff --git a/cmd2/__init__.py b/cmd2/__init__.py
index 73d70821..63e27812 100644
--- a/cmd2/__init__.py
+++ b/cmd2/__init__.py
@@ -22,7 +22,7 @@ if cmd2_parser_module is not None:
# Get the current value for argparse_custom.DEFAULT_ARGUMENT_PARSER
from .argparse_custom import DEFAULT_ARGUMENT_PARSER
-from .cmd2 import Cmd, EmptyStatement
+from .cmd2 import Cmd
from .constants import COMMAND_NAME, DEFAULT_SHORTCUTS
from .decorators import categorize, with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
from .parsing import Statement
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 0bb4921e..7b88eaf8 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -50,6 +50,7 @@ from . import utils
from .argparse_custom import CompletionItem, DEFAULT_ARGUMENT_PARSER
from .clipboard import can_clip, get_paste_buffer, write_to_paste_buffer
from .decorators import with_argparser
+from .exceptions import EmbeddedConsoleExit, EmptyStatement
from .history import History, HistoryItem
from .parsing import StatementParser, Statement, Macro, MacroArg, shlex_split
from .rl_utils import rl_type, RlType, rl_get_point, rl_set_prompt, vt100_support, rl_make_safe_prompt, rl_warning
@@ -106,16 +107,6 @@ class _SavedCmd2Env:
self.sys_stdin = None
-class EmbeddedConsoleExit(SystemExit):
- """Custom exception class for use with the py command."""
- pass
-
-
-class EmptyStatement(Exception):
- """Custom exception class for handling behavior when the user just presses <Enter>."""
- pass
-
-
# Contains data about a disabled command which is used to restore its original functions when the command is enabled
DisabledCommand = namedtuple('DisabledCommand', ['command_function', 'help_function', 'completer_function'])
diff --git a/cmd2/exceptions.py b/cmd2/exceptions.py
new file mode 100644
index 00000000..747e2368
--- /dev/null
+++ b/cmd2/exceptions.py
@@ -0,0 +1,12 @@
+# coding=utf-8
+"""Custom exceptions for cmd2. These are NOT part of the public API and are intended for internal use only."""
+
+
+class EmbeddedConsoleExit(SystemExit):
+ """Custom exception class for use with the py command."""
+ pass
+
+
+class EmptyStatement(Exception):
+ """Custom exception class for handling behavior when the user just presses <Enter>."""
+ pass
diff --git a/docs/api/exceptions.rst b/docs/api/exceptions.rst
deleted file mode 100644
index 400993aa..00000000
--- a/docs/api/exceptions.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-Exceptions
-==========
-
-.. autoexception:: cmd2.EmptyStatement
diff --git a/docs/api/index.rst b/docs/api/index.rst
index f0324eab..346fc274 100644
--- a/docs/api/index.rst
+++ b/docs/api/index.rst
@@ -6,7 +6,6 @@ API Reference
cmd
decorators
- exceptions
ansi
utility_classes
utility_functions
diff --git a/docs/features/hooks.rst b/docs/features/hooks.rst
index ee1d5fbc..ba9af573 100644
--- a/docs/features/hooks.rst
+++ b/docs/features/hooks.rst
@@ -102,12 +102,7 @@ called each time it was registered.
Postparsing, precommand, and postcommand hook methods share some common ways to
influence the command processing loop.
-If a hook raises a ``cmd2.EmptyStatement`` exception:
-- no more hooks (except command finalization hooks) of any kind will be called
-- if the command has not yet been executed, it will not be executed
-- no error message will be displayed to the user
-
-If a hook raises any other exception:
+If a hook raises an exception:
- no more hooks (except command finalization hooks) of any kind will be called
- if the command has not yet been executed, it will not be executed
- the exception message will be displayed for the user.
|
python-cmd2/cmd2
|
970c5fc42c69c1c03640c979df341e85e3c38848
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index dc9a3fa1..2db52d39 100755
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -20,7 +20,7 @@ except ImportError:
from unittest import mock
import cmd2
-from cmd2 import ansi, clipboard, constants, plugin, utils, COMMAND_NAME
+from cmd2 import ansi, clipboard, constants, exceptions, plugin, utils, COMMAND_NAME
from .conftest import (run_cmd, normalize, verify_help_text, HELP_HISTORY, SHORTCUTS_TXT, SHOW_TXT,
SHOW_LONG, complete_tester, odd_file_names)
@@ -1258,7 +1258,7 @@ def multiline_app():
return app
def test_multiline_complete_empty_statement_raises_exception(multiline_app):
- with pytest.raises(cmd2.EmptyStatement):
+ with pytest.raises(exceptions.EmptyStatement):
multiline_app._complete_statement('')
def test_multiline_complete_statement_without_terminator(multiline_app):
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index 2114bfaa..435f22eb 100755
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -7,7 +7,7 @@ import attr
import pytest
import cmd2
-from cmd2 import constants, utils
+from cmd2 import constants, exceptions, utils
from cmd2.parsing import StatementParser, shlex_split
@pytest.fixture
@@ -588,10 +588,10 @@ def test_parse_unclosed_quotes(parser):
def test_empty_statement_raises_exception():
app = cmd2.Cmd()
- with pytest.raises(cmd2.EmptyStatement):
+ with pytest.raises(exceptions.EmptyStatement):
app._complete_statement('')
- with pytest.raises(cmd2.EmptyStatement):
+ with pytest.raises(exceptions.EmptyStatement):
app._complete_statement(' ')
@pytest.mark.parametrize('line,command,args', [
diff --git a/tests/test_plugin.py b/tests/test_plugin.py
index f7065db5..c118b60d 100644
--- a/tests/test_plugin.py
+++ b/tests/test_plugin.py
@@ -14,7 +14,7 @@ except ImportError:
from unittest import mock
import cmd2
-from cmd2 import plugin
+from cmd2 import exceptions, plugin
class Plugin:
@@ -81,7 +81,7 @@ class Plugin:
def postparse_hook_emptystatement(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""A postparsing hook with raises an EmptyStatement exception"""
self.called_postparsing += 1
- raise cmd2.EmptyStatement
+ raise exceptions.EmptyStatement
def postparse_hook_exception(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""A postparsing hook which raises an exception"""
@@ -126,7 +126,7 @@ class Plugin:
def precmd_hook_emptystatement(self, data: plugin.PrecommandData) -> plugin.PrecommandData:
"""A precommand hook which raises an EmptyStatement exception"""
self.called_precmd += 1
- raise cmd2.EmptyStatement
+ raise exceptions.EmptyStatement
def precmd_hook_exception(self, data: plugin.PrecommandData) -> plugin.PrecommandData:
"""A precommand hook which raises an exception"""
|
Re-evaluate visibility of EmptyStatement exception
In `cmd2.py` we define an `EmptyStatement` exception. In `__init__.py` we import that exception, making it available as `cmd2.EmptyStatement`. As far as I can tell, we only use this exception for internal purposes: no methods available as part of our public API throw this exception.
If this is true, then it seem like:
1. We shouldn't document `EmptyStatement` as part of our public API, and
2. We should remove the package level import of `EmptyStatement` from `__init__.py`.
What do you think?
|
0.0
|
970c5fc42c69c1c03640c979df341e85e3c38848
|
[
"tests/test_cmd2.py::test_version",
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_invalid_option",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_command_starts_with_shortcut",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_set",
"tests/test_cmd2.py::test_set_val_empty",
"tests/test_cmd2.py::test_set_val_is_flag",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_no_settables",
"tests/test_cmd2.py::test_set_allow_style[Never-True-Never]",
"tests/test_cmd2.py::test_set_allow_style[neVeR-True-Never]",
"tests/test_cmd2.py::test_set_allow_style[Terminal-True-Terminal]",
"tests/test_cmd2.py::test_set_allow_style[TeRMInal-True-Terminal]",
"tests/test_cmd2.py::test_set_allow_style[Always-True-Always]",
"tests/test_cmd2.py::test_set_allow_style[AlWaYs-True-Always]",
"tests/test_cmd2.py::test_set_allow_style[invalid-False-Terminal]",
"tests/test_cmd2.py::test_set_onchange_hook",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_base_py",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_run_script",
"tests/test_cmd2.py::test_run_script_with_empty_args",
"tests/test_cmd2.py::test_run_script_with_nonexistent_file",
"tests/test_cmd2.py::test_run_script_with_directory",
"tests/test_cmd2.py::test_run_script_with_empty_file",
"tests/test_cmd2.py::test_run_script_with_binary_file",
"tests/test_cmd2.py::test_run_script_with_python_file",
"tests/test_cmd2.py::test_run_script_with_utf8_file",
"tests/test_cmd2.py::test_run_script_nested_run_scripts",
"tests/test_cmd2.py::test_runcmds_plus_hooks",
"tests/test_cmd2.py::test_relative_run_script",
"tests/test_cmd2.py::test_relative_run_script_with_odd_file_names[nothingweird]",
"tests/test_cmd2.py::test_relative_run_script_with_odd_file_names[has",
"tests/test_cmd2.py::test_relative_run_script_with_odd_file_names[\"is_double_quoted\"]",
"tests/test_cmd2.py::test_relative_run_script_with_odd_file_names['is_single_quoted']",
"tests/test_cmd2.py::test_relative_run_script_requires_an_argument",
"tests/test_cmd2.py::test_in_script",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory",
"tests/test_cmd2.py::test_output_redirection_to_too_long_filename",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_disallow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_and_redirect",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_debug_not_settable",
"tests/test_cmd2.py::test_remove_settable_keyerror",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_odd_file_names[nothingweird]",
"tests/test_cmd2.py::test_edit_file_with_odd_file_names[has",
"tests/test_cmd2.py::test_edit_file_with_odd_file_names[\"is_double_quoted\"]",
"tests/test_cmd2.py::test_edit_file_with_odd_file_names['is_single_quoted']",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_base_cmdloop_with_startup_commands",
"tests/test_cmd2.py::test_base_cmdloop_without_startup_commands",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_stty_sane",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option_too_big",
"tests/test_cmd2.py::test_select_invalid_option_too_small",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_select_eof",
"tests/test_cmd2.py::test_select_ctrl_c",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes",
"tests/test_cmd2.py::test_multiline_input_line_to_statement",
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_cmd2.py::test_commandresult_truthy",
"tests/test_cmd2.py::test_commandresult_falsy",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_read_input_rawinput_true",
"tests/test_cmd2.py::test_read_input_rawinput_false",
"tests/test_cmd2.py::test_read_command_line_eof",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_poutput_ansi_always",
"tests/test_cmd2.py::test_poutput_ansi_never",
"tests/test_cmd2.py::test_get_alias_completion_items",
"tests/test_cmd2.py::test_get_macro_completion_items",
"tests/test_cmd2.py::test_get_settable_completion_items",
"tests/test_cmd2.py::test_alias_no_subcommand",
"tests/test_cmd2.py::test_alias_create",
"tests/test_cmd2.py::test_alias_create_with_quoted_value",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[#]",
"tests/test_cmd2.py::test_alias_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_alias_create_with_command_name",
"tests/test_cmd2.py::test_alias_create_with_macro_name",
"tests/test_cmd2.py::test_alias_that_resolves_into_comment",
"tests/test_cmd2.py::test_alias_list_invalid_alias",
"tests/test_cmd2.py::test_alias_delete",
"tests/test_cmd2.py::test_alias_delete_all",
"tests/test_cmd2.py::test_alias_delete_non_existing",
"tests/test_cmd2.py::test_alias_delete_no_name",
"tests/test_cmd2.py::test_multiple_aliases",
"tests/test_cmd2.py::test_macro_no_subcommand",
"tests/test_cmd2.py::test_macro_create",
"tests/test_cmd2.py::test_macro_create_with_quoted_value",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[#]",
"tests/test_cmd2.py::test_macro_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_macro_create_with_command_name",
"tests/test_cmd2.py::test_macro_create_with_alias_name",
"tests/test_cmd2.py::test_macro_create_with_args",
"tests/test_cmd2.py::test_macro_create_with_escaped_args",
"tests/test_cmd2.py::test_macro_usage_with_missing_args",
"tests/test_cmd2.py::test_macro_usage_with_exta_args",
"tests/test_cmd2.py::test_macro_create_with_missing_arg_nums",
"tests/test_cmd2.py::test_macro_create_with_invalid_arg_num",
"tests/test_cmd2.py::test_macro_create_with_unicode_numbered_arg",
"tests/test_cmd2.py::test_macro_create_with_missing_unicode_arg_nums",
"tests/test_cmd2.py::test_macro_that_resolves_into_comment",
"tests/test_cmd2.py::test_macro_list_invalid_macro",
"tests/test_cmd2.py::test_macro_delete",
"tests/test_cmd2.py::test_macro_delete_all",
"tests/test_cmd2.py::test_macro_delete_non_existing",
"tests/test_cmd2.py::test_macro_delete_no_name",
"tests/test_cmd2.py::test_multiple_macros",
"tests/test_cmd2.py::test_nonexistent_macro",
"tests/test_cmd2.py::test_perror_style",
"tests/test_cmd2.py::test_perror_no_style",
"tests/test_cmd2.py::test_pwarning_style",
"tests/test_cmd2.py::test_pwarning_no_style",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_ppaged_blank",
"tests/test_cmd2.py::test_ppaged_none",
"tests/test_cmd2.py::test_ppaged_strips_ansi_when_redirecting",
"tests/test_cmd2.py::test_ppaged_strips_ansi_when_redirecting_if_always",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline",
"tests/test_cmd2.py::test_onecmd_raw_str_continue",
"tests/test_cmd2.py::test_onecmd_raw_str_quit",
"tests/test_cmd2.py::test_onecmd_add_to_history",
"tests/test_cmd2.py::test_get_all_commands",
"tests/test_cmd2.py::test_get_help_topics",
"tests/test_cmd2.py::test_get_help_topics_hidden",
"tests/test_cmd2.py::test_exit_code_default",
"tests/test_cmd2.py::test_exit_code_nonzero",
"tests/test_cmd2.py::test_ansi_pouterr_always_tty",
"tests/test_cmd2.py::test_ansi_pouterr_always_notty",
"tests/test_cmd2.py::test_ansi_terminal_tty",
"tests/test_cmd2.py::test_ansi_terminal_notty",
"tests/test_cmd2.py::test_ansi_never_tty",
"tests/test_cmd2.py::test_ansi_never_notty",
"tests/test_cmd2.py::test_disable_and_enable_category",
"tests/test_cmd2.py::test_enable_enabled_command",
"tests/test_cmd2.py::test_disable_fake_command",
"tests/test_cmd2.py::test_disable_command_twice",
"tests/test_cmd2.py::test_disabled_command_not_in_history",
"tests/test_cmd2.py::test_disabled_message_command_name",
"tests/test_cmd2.py::test_startup_script",
"tests/test_cmd2.py::test_startup_script_with_odd_file_names[nothingweird]",
"tests/test_cmd2.py::test_startup_script_with_odd_file_names[has",
"tests/test_cmd2.py::test_startup_script_with_odd_file_names[\"is_double_quoted\"]",
"tests/test_cmd2.py::test_startup_script_with_odd_file_names['is_single_quoted']",
"tests/test_cmd2.py::test_transcripts_at_init",
"tests/test_parsing.py::test_parse_empty_string",
"tests/test_parsing.py::test_parse_empty_string_default",
"tests/test_parsing.py::test_tokenize_default[command-tokens0]",
"tests/test_parsing.py::test_tokenize_default[#comment-tokens1]",
"tests/test_parsing.py::test_tokenize_default[not",
"tests/test_parsing.py::test_tokenize_default[termbare",
"tests/test_parsing.py::test_tokenize_default[termbare;",
"tests/test_parsing.py::test_tokenize_default[termbare&",
"tests/test_parsing.py::test_tokenize_default[help|less-tokens7]",
"tests/test_parsing.py::test_tokenize[command-tokens0]",
"tests/test_parsing.py::test_tokenize[#",
"tests/test_parsing.py::test_tokenize[not",
"tests/test_parsing.py::test_tokenize[42",
"tests/test_parsing.py::test_tokenize[l-tokens4]",
"tests/test_parsing.py::test_tokenize[termbare",
"tests/test_parsing.py::test_tokenize[termbare;",
"tests/test_parsing.py::test_tokenize[termbare&",
"tests/test_parsing.py::test_tokenize[help|less-tokens9]",
"tests/test_parsing.py::test_tokenize[l|less-tokens10]",
"tests/test_parsing.py::test_tokenize_unclosed_quotes",
"tests/test_parsing.py::test_command_and_args[tokens0--]",
"tests/test_parsing.py::test_command_and_args[tokens1-command-]",
"tests/test_parsing.py::test_command_and_args[tokens2-command-arg1",
"tests/test_parsing.py::test_parse_single_word[plainword]",
"tests/test_parsing.py::test_parse_single_word[\"one",
"tests/test_parsing.py::test_parse_single_word['one",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare;-;]",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare",
"tests/test_parsing.py::test_parse_word_plus_terminator[termbare&-&]",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare;",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare",
"tests/test_parsing.py::test_parse_suffix_after_terminator[termbare&",
"tests/test_parsing.py::test_parse_command_with_args",
"tests/test_parsing.py::test_parse_command_with_quoted_args",
"tests/test_parsing.py::test_parse_command_with_args_terminator_and_suffix",
"tests/test_parsing.py::test_parse_comment",
"tests/test_parsing.py::test_parse_embedded_comment_char",
"tests/test_parsing.py::test_parse_simple_pipe[simple",
"tests/test_parsing.py::test_parse_simple_pipe[simple|piped]",
"tests/test_parsing.py::test_parse_double_pipe_is_not_a_pipe",
"tests/test_parsing.py::test_parse_complex_pipe",
"tests/test_parsing.py::test_parse_redirect[help",
"tests/test_parsing.py::test_parse_redirect[help>out.txt->]",
"tests/test_parsing.py::test_parse_redirect[help>>out.txt->>]",
"tests/test_parsing.py::test_parse_redirect_with_args",
"tests/test_parsing.py::test_parse_redirect_with_dash_in_path",
"tests/test_parsing.py::test_parse_redirect_append",
"tests/test_parsing.py::test_parse_pipe_then_redirect",
"tests/test_parsing.py::test_parse_multiple_pipes",
"tests/test_parsing.py::test_redirect_then_pipe",
"tests/test_parsing.py::test_append_then_pipe",
"tests/test_parsing.py::test_append_then_redirect",
"tests/test_parsing.py::test_redirect_then_append",
"tests/test_parsing.py::test_redirect_to_quoted_string",
"tests/test_parsing.py::test_redirect_to_single_quoted_string",
"tests/test_parsing.py::test_redirect_to_empty_quoted_string",
"tests/test_parsing.py::test_redirect_to_empty_single_quoted_string",
"tests/test_parsing.py::test_parse_output_to_paste_buffer",
"tests/test_parsing.py::test_parse_redirect_inside_terminator",
"tests/test_parsing.py::test_parse_multiple_terminators[multiline",
"tests/test_parsing.py::test_parse_unfinished_multiliine_command",
"tests/test_parsing.py::test_parse_basic_multiline_command",
"tests/test_parsing.py::test_parse_multiline_command_ignores_redirectors_within_it[multiline",
"tests/test_parsing.py::test_parse_multiline_terminated_by_empty_line",
"tests/test_parsing.py::test_parse_multiline_with_embedded_newline[multiline",
"tests/test_parsing.py::test_parse_multiline_ignores_terminators_in_quotes",
"tests/test_parsing.py::test_parse_command_with_unicode_args",
"tests/test_parsing.py::test_parse_unicode_command",
"tests/test_parsing.py::test_parse_redirect_to_unicode_filename",
"tests/test_parsing.py::test_parse_unclosed_quotes",
"tests/test_parsing.py::test_empty_statement_raises_exception",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias-help-]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[helpalias",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42-theanswer-]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[42",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls-shell-ls]",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[!ls",
"tests/test_parsing.py::test_parse_alias_and_shortcut_expansion[l-shell-ls",
"tests/test_parsing.py::test_parse_alias_on_multiline_command",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>out.txt->]",
"tests/test_parsing.py::test_parse_alias_redirection[helpalias>>out.txt->>]",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias",
"tests/test_parsing.py::test_parse_alias_pipe[helpalias|less]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;]",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias;;",
"tests/test_parsing.py::test_parse_alias_terminator_no_whitespace[helpalias",
"tests/test_parsing.py::test_parse_command_only_command_and_args",
"tests/test_parsing.py::test_parse_command_only_strips_line",
"tests/test_parsing.py::test_parse_command_only_expands_alias",
"tests/test_parsing.py::test_parse_command_only_expands_shortcuts",
"tests/test_parsing.py::test_parse_command_only_quoted_args",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>out.txt->out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias>>out.txt->>out.txt]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help|less-|less]",
"tests/test_parsing.py::test_parse_command_only_specialchars[helpalias;-;]",
"tests/test_parsing.py::test_parse_command_only_specialchars[help",
"tests/test_parsing.py::test_parse_command_only_specialchars[help;",
"tests/test_parsing.py::test_parse_command_only_empty[]",
"tests/test_parsing.py::test_parse_command_only_empty[;]",
"tests/test_parsing.py::test_parse_command_only_empty[;;]",
"tests/test_parsing.py::test_parse_command_only_empty[;;",
"tests/test_parsing.py::test_parse_command_only_empty[&]",
"tests/test_parsing.py::test_parse_command_only_empty[&",
"tests/test_parsing.py::test_parse_command_only_empty[",
"tests/test_parsing.py::test_parse_command_only_empty[>]",
"tests/test_parsing.py::test_parse_command_only_empty[']",
"tests/test_parsing.py::test_parse_command_only_empty[\"]",
"tests/test_parsing.py::test_parse_command_only_empty[|]",
"tests/test_parsing.py::test_parse_command_only_multiline",
"tests/test_parsing.py::test_statement_initialization",
"tests/test_parsing.py::test_statement_is_immutable",
"tests/test_parsing.py::test_is_valid_command_invalid",
"tests/test_parsing.py::test_is_valid_command_valid",
"tests/test_parsing.py::test_macro_normal_arg_pattern",
"tests/test_parsing.py::test_macro_escaped_arg_pattern",
"tests/test_plugin.py::test_register_preloop_hook_too_many_parameters",
"tests/test_plugin.py::test_register_preloop_hook_with_return_annotation",
"tests/test_plugin.py::test_preloop_hook",
"tests/test_plugin.py::test_preloop_hooks",
"tests/test_plugin.py::test_register_postloop_hook_too_many_parameters",
"tests/test_plugin.py::test_register_postloop_hook_with_wrong_return_annotation",
"tests/test_plugin.py::test_postloop_hook",
"tests/test_plugin.py::test_postloop_hooks",
"tests/test_plugin.py::test_preparse",
"tests/test_plugin.py::test_postparsing_hook_too_many_parameters",
"tests/test_plugin.py::test_postparsing_hook_undeclared_parameter_annotation",
"tests/test_plugin.py::test_postparsing_hook_wrong_parameter_annotation",
"tests/test_plugin.py::test_postparsing_hook_undeclared_return_annotation",
"tests/test_plugin.py::test_postparsing_hook_wrong_return_annotation",
"tests/test_plugin.py::test_postparsing_hook",
"tests/test_plugin.py::test_postparsing_hook_stop_first",
"tests/test_plugin.py::test_postparsing_hook_stop_second",
"tests/test_plugin.py::test_postparsing_hook_emptystatement_first",
"tests/test_plugin.py::test_postparsing_hook_emptystatement_second",
"tests/test_plugin.py::test_postparsing_hook_exception",
"tests/test_plugin.py::test_register_precmd_hook_parameter_count",
"tests/test_plugin.py::test_register_precmd_hook_no_parameter_annotation",
"tests/test_plugin.py::test_register_precmd_hook_wrong_parameter_annotation",
"tests/test_plugin.py::test_register_precmd_hook_no_return_annotation",
"tests/test_plugin.py::test_register_precmd_hook_wrong_return_annotation",
"tests/test_plugin.py::test_precmd_hook",
"tests/test_plugin.py::test_precmd_hook_emptystatement_first",
"tests/test_plugin.py::test_precmd_hook_emptystatement_second",
"tests/test_plugin.py::test_register_postcmd_hook_parameter_count",
"tests/test_plugin.py::test_register_postcmd_hook_no_parameter_annotation",
"tests/test_plugin.py::test_register_postcmd_hook_wrong_parameter_annotation",
"tests/test_plugin.py::test_register_postcmd_hook_no_return_annotation",
"tests/test_plugin.py::test_register_postcmd_hook_wrong_return_annotation",
"tests/test_plugin.py::test_postcmd",
"tests/test_plugin.py::test_postcmd_exception_first",
"tests/test_plugin.py::test_postcmd_exception_second",
"tests/test_plugin.py::test_register_cmdfinalization_hook_parameter_count",
"tests/test_plugin.py::test_register_cmdfinalization_hook_no_parameter_annotation",
"tests/test_plugin.py::test_register_cmdfinalization_hook_wrong_parameter_annotation",
"tests/test_plugin.py::test_register_cmdfinalization_hook_no_return_annotation",
"tests/test_plugin.py::test_register_cmdfinalization_hook_wrong_return_annotation",
"tests/test_plugin.py::test_cmdfinalization",
"tests/test_plugin.py::test_cmdfinalization_stop_first",
"tests/test_plugin.py::test_cmdfinalization_stop_second",
"tests/test_plugin.py::test_cmdfinalization_hook_exception"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-19 02:11:30+00:00
|
mit
| 5,066 |
|
python-cmd2__cmd2-924
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01180001..03b88d03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,7 +3,9 @@
* Made `ipy` consistent with `py` in the following ways
* `ipy` returns whether any of the commands run in it returned True to stop command loop
* `Cmd.in_pyscript()` returns True while in `ipy`.
- * Starting `ipy` when `Cmd.in_pyscript()` is already True is not allowed.
+ * Starting `ipy` when `Cmd.in_pyscript()` is already True is not allowed.
+ * `with_argument_list`, `with_argparser`, and `with_argparser_and_unknown_args` wrappers now pass
+ `kwargs` through to their wrapped command function.
## 1.0.2 (April 06, 2020)
* Bug Fixes
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 98969d10..34f53044 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -3169,17 +3169,16 @@ class Cmd(cmd.Cmd):
py_parser.add_argument('command', nargs=argparse.OPTIONAL, help="command to run")
py_parser.add_argument('remainder', nargs=argparse.REMAINDER, help="remainder of command")
- # This is a hidden flag for telling do_py to run a pyscript. It is intended only to be used by run_pyscript
- # after it sets up sys.argv for the script being run. When this flag is present, it takes precedence over all
- # other arguments.
- py_parser.add_argument('--pyscript', help=argparse.SUPPRESS)
-
# Preserve quotes since we are passing these strings to Python
@with_argparser(py_parser, preserve_quotes=True)
- def do_py(self, args: argparse.Namespace) -> Optional[bool]:
+ def do_py(self, args: argparse.Namespace, *, pyscript: Optional[str] = None) -> Optional[bool]:
"""
Enter an interactive Python shell
+ :param args: Namespace of args on the command line
+ :param pyscript: optional path to a pyscript file to run. This is intended only to be used by run_pyscript
+ after it sets up sys.argv for the script. If populated, this takes precedence over all
+ other arguments. (Defaults to None)
:return: True if running of commands should stop
"""
def py_quit():
@@ -3211,9 +3210,9 @@ class Cmd(cmd.Cmd):
localvars['self'] = self
# Handle case where we were called by run_pyscript
- if args.pyscript:
+ if pyscript is not None:
# Read the script file
- expanded_filename = os.path.expanduser(utils.strip_quotes(args.pyscript))
+ expanded_filename = os.path.expanduser(pyscript)
try:
with open(expanded_filename) as f:
@@ -3320,7 +3319,7 @@ class Cmd(cmd.Cmd):
sys.argv = [args.script_path] + args.script_arguments
# noinspection PyTypeChecker
- py_return = self.do_py('--pyscript {}'.format(utils.quote_string(args.script_path)))
+ py_return = self.do_py('', pyscript=args.script_path)
finally:
# Restore command line arguments to original state
diff --git a/cmd2/decorators.py b/cmd2/decorators.py
index deac4701..dc196032 100644
--- a/cmd2/decorators.py
+++ b/cmd2/decorators.py
@@ -1,7 +1,7 @@
# coding=utf-8
"""Decorators for ``cmd2`` commands"""
import argparse
-from typing import Callable, List, Optional, Union
+from typing import Any, Callable, Dict, List, Optional, Union
from . import constants
from .exceptions import Cmd2ArgparseError
@@ -53,12 +53,20 @@ def with_argument_list(*args: List[Callable], preserve_quotes: bool = False) ->
def arg_decorator(func: Callable):
@functools.wraps(func)
- def cmd_wrapper(cmd2_app, statement: Union[Statement, str]):
+ def cmd_wrapper(cmd2_app, statement: Union[Statement, str], **kwargs: Dict[str, Any]) -> Optional[bool]:
+ """
+ Command function wrapper which translates command line into an argument list and calls actual command function
+
+ :param cmd2_app: CLI instance passed as self parameter to command function
+ :param statement: command line string or already generated Statement
+ :param kwargs: any keyword arguments being passed to command function
+ :return: return value of command function
+ """
_, parsed_arglist = cmd2_app.statement_parser.get_command_arg_list(command_name,
statement,
preserve_quotes)
- return func(cmd2_app, parsed_arglist)
+ return func(cmd2_app, parsed_arglist, **kwargs)
command_name = func.__name__[len(constants.COMMAND_FUNC_PREFIX):]
cmd_wrapper.__doc__ = func.__doc__
@@ -132,7 +140,17 @@ def with_argparser_and_unknown_args(parser: argparse.ArgumentParser, *,
def arg_decorator(func: Callable):
@functools.wraps(func)
- def cmd_wrapper(cmd2_app, statement: Union[Statement, str]):
+ def cmd_wrapper(cmd2_app, statement: Union[Statement, str], **kwargs: Dict[str, Any]) -> Optional[bool]:
+ """
+ Command function wrapper which translates command line into argparse Namespace and calls actual
+ command function
+
+ :param cmd2_app: CLI instance passed as self parameter to command function
+ :param statement: command line string or already generated Statement
+ :param kwargs: any keyword arguments being passed to command function
+ :return: return value of command function
+ :raises: Cmd2ArgparseError if argparse has error parsing command line
+ """
statement, parsed_arglist = cmd2_app.statement_parser.get_command_arg_list(command_name,
statement,
preserve_quotes)
@@ -148,7 +166,7 @@ def with_argparser_and_unknown_args(parser: argparse.ArgumentParser, *,
raise Cmd2ArgparseError
else:
setattr(args, '__statement__', statement)
- return func(cmd2_app, args, unknown)
+ return func(cmd2_app, args, unknown, **kwargs)
# argparser defaults the program name to sys.argv[0], but we want it to be the name of our command
command_name = func.__name__[len(constants.COMMAND_FUNC_PREFIX):]
@@ -204,7 +222,17 @@ def with_argparser(parser: argparse.ArgumentParser, *,
def arg_decorator(func: Callable):
@functools.wraps(func)
- def cmd_wrapper(cmd2_app, statement: Union[Statement, str]):
+ def cmd_wrapper(cmd2_app, statement: Union[Statement, str], **kwargs: Dict[str, Any]) -> Optional[bool]:
+ """
+ Command function wrapper which translates command line into argparse Namespace and calls actual
+ command function
+
+ :param cmd2_app: CLI instance passed as self parameter to command function
+ :param statement: command line string or already generated Statement
+ :param kwargs: any keyword arguments being passed to command function
+ :return: return value of command function
+ :raises: Cmd2ArgparseError if argparse has error parsing command line
+ """
statement, parsed_arglist = cmd2_app.statement_parser.get_command_arg_list(command_name,
statement,
preserve_quotes)
@@ -220,7 +248,7 @@ def with_argparser(parser: argparse.ArgumentParser, *,
raise Cmd2ArgparseError
else:
setattr(args, '__statement__', statement)
- return func(cmd2_app, args)
+ return func(cmd2_app, args, **kwargs)
# argparser defaults the program name to sys.argv[0], but we want it to be the name of our command
command_name = func.__name__[len(constants.COMMAND_FUNC_PREFIX):]
|
python-cmd2/cmd2
|
e7a0be4df68346ac15626c20c4a19c8fabb1bf49
|
diff --git a/tests/test_argparse.py b/tests/test_argparse.py
index 21ec17e8..9510e8f2 100644
--- a/tests/test_argparse.py
+++ b/tests/test_argparse.py
@@ -4,11 +4,11 @@
Cmd2 testing for argument parsing
"""
import argparse
+from typing import Optional
+
import pytest
import cmd2
-from cmd2.utils import StdSim
-
from .conftest import run_cmd
# Prefer statically linked gnureadline if available (for macOS compatibility due to issues with libedit)
@@ -41,7 +41,7 @@ class ArgparseApp(cmd2.Cmd):
say_parser.add_argument('words', nargs='+', help='words to say')
@cmd2.with_argparser(say_parser)
- def do_say(self, args):
+ def do_say(self, args, *, keyword_arg: Optional[str] = None):
"""Repeat what you tell me to."""
words = []
for word in args.words:
@@ -57,6 +57,9 @@ class ArgparseApp(cmd2.Cmd):
self.stdout.write(' '.join(words))
self.stdout.write('\n')
+ if keyword_arg is not None:
+ print(keyword_arg)
+
tag_parser = argparse.ArgumentParser(description='create a html tag')
tag_parser.add_argument('tag', help='tag')
tag_parser.add_argument('content', nargs='+', help='content to surround with tag')
@@ -71,12 +74,15 @@ class ArgparseApp(cmd2.Cmd):
self.stdout.write('{}'.format(args.custom_stuff))
@cmd2.with_argument_list
- def do_arglist(self, arglist):
+ def do_arglist(self, arglist, *, keyword_arg: Optional[str] = None):
if isinstance(arglist, list):
self.stdout.write('True')
else:
self.stdout.write('False')
+ if keyword_arg is not None:
+ print(keyword_arg)
+
@cmd2.with_argument_list(preserve_quotes=True)
def do_preservelist(self, arglist):
self.stdout.write('{}'.format(arglist))
@@ -86,7 +92,7 @@ class ArgparseApp(cmd2.Cmd):
known_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
known_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
@cmd2.with_argparser_and_unknown_args(known_parser)
- def do_speak(self, args, extra):
+ def do_speak(self, args, extra, *, keyword_arg: Optional[str] = None):
"""Repeat what you tell me to."""
words = []
for word in extra:
@@ -102,6 +108,9 @@ class ArgparseApp(cmd2.Cmd):
self.stdout.write(' '.join(words))
self.stdout.write('\n')
+ if keyword_arg is not None:
+ print(keyword_arg)
+
@cmd2.with_argparser_and_unknown_args(argparse.ArgumentParser(), preserve_quotes=True)
def do_test_argparse_with_list_quotes(self, args, extra):
self.stdout.write('{}'.format(' '.join(extra)))
@@ -129,6 +138,12 @@ def test_argparse_remove_quotes(argparse_app):
out, err = run_cmd(argparse_app, 'say "hello there"')
assert out == ['hello there']
+def test_argparser_kwargs(argparse_app, capsys):
+ """Test with_argparser wrapper passes through kwargs to command function"""
+ argparse_app.do_say('word', keyword_arg="foo")
+ out, err = capsys.readouterr()
+ assert out == "foo\n"
+
def test_argparse_preserve_quotes(argparse_app):
out, err = run_cmd(argparse_app, 'tag mytag "hello"')
assert out[0] == '<mytag>"hello"</mytag>'
@@ -161,6 +176,12 @@ def test_argparser_correct_args_with_quotes_and_midline_options(argparse_app):
out, err = run_cmd(argparse_app, "speak 'This is a' -s test of the emergency broadcast system!")
assert out == ['THIS IS A TEST OF THE EMERGENCY BROADCAST SYSTEM!']
+def test_argparser_and_unknown_args_kwargs(argparse_app, capsys):
+ """Test with_argparser_and_unknown_args wrapper passes through kwargs to command function"""
+ argparse_app.do_speak('', keyword_arg="foo")
+ out, err = capsys.readouterr()
+ assert out == "foo\n"
+
def test_argparse_quoted_arguments_multiple(argparse_app):
out, err = run_cmd(argparse_app, 'say "hello there" "rick & morty"')
assert out == ['hello there rick & morty']
@@ -186,6 +207,12 @@ def test_arglist(argparse_app):
out, err = run_cmd(argparse_app, 'arglist "we should" get these')
assert out[0] == 'True'
+def test_arglist_kwargs(argparse_app, capsys):
+ """Test with_argument_list wrapper passes through kwargs to command function"""
+ argparse_app.do_arglist('arg', keyword_arg="foo")
+ out, err = capsys.readouterr()
+ assert out == "foo\n"
+
def test_preservelist(argparse_app):
out, err = run_cmd(argparse_app, 'preservelist foo "bar baz"')
assert out[0] == "['foo', '\"bar baz\"']"
|
Allow passing extra args to **do_** functions
Please allow passing extra args to **do_** functions
In this example, I add __**kwargs__ to the decorator.
```python
def with_argparser(parser: argparse.ArgumentParser, *,
ns_provider: Optional[Callable[..., argparse.Namespace]] = None,
preserve_quotes: bool = False) -> Callable[[argparse.Namespace], Optional[bool]]:
"""A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments
with the given instance of argparse.ArgumentParser.
:param parser: unique instance of ArgumentParser
:param ns_provider: An optional function that accepts a cmd2.Cmd object as an argument and returns an
argparse.Namespace. This is useful if the Namespace needs to be prepopulated with
state data that affects parsing.
:param preserve_quotes: if True, then arguments passed to argparse maintain their quotes
:return: function that gets passed the argparse-parsed args in a Namespace
A member called __statement__ is added to the Namespace to provide command functions access to the
Statement object. This can be useful if the command function needs to know the command line.
:Example:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
>>> parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
>>> parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
>>> parser.add_argument('words', nargs='+', help='words to print')
>>>
>>> class MyApp(cmd2.Cmd):
>>> @cmd2.with_argparser(parser, preserve_quotes=True)
>>> def do_argprint(self, args):
>>> "Print the options and argument list this options command was called with."
>>> self.poutput('args: {!r}'.format(args))
"""
import functools
def arg_decorator(func: Callable):
@functools.wraps(func)
def cmd_wrapper(cmd2_app, statement: Union[Statement, str], **kwargs):
statement, parsed_arglist = cmd2_app.statement_parser.get_command_arg_list(command_name,
statement,
preserve_quotes)
if ns_provider is None:
namespace = None
else:
namespace = ns_provider(cmd2_app)
try:
args = parser.parse_args(parsed_arglist, namespace)
except SystemExit:
raise Cmd2ArgparseError
else:
setattr(args, '__statement__', statement)
return func(cmd2_app, args, **kwargs)
# argparser defaults the program name to sys.argv[0], but we want it to be the name of our command
command_name = func.__name__[len(constants.COMMAND_FUNC_PREFIX):]
_set_parser_prog(parser, command_name)
# If the description has not been set, then use the method docstring if one exists
if parser.description is None and func.__doc__:
parser.description = func.__doc__
# Set the command's help text as argparser.description (which can be None)
cmd_wrapper.__doc__ = parser.description
# Set some custom attributes for this command
setattr(cmd_wrapper, constants.CMD_ATTR_ARGPARSER, parser)
setattr(cmd_wrapper, constants.CMD_ATTR_PRESERVE_QUOTES, preserve_quotes)
return cmd_wrapper
# noinspection PyTypeChecker
return arg_decorator
```
**run_pyscript** now call like this:
```
self.do_stuff("arg1 --xxx --yyy hhh", stuff=True)
```
To do the same thing without **kwargs**, actually I must pass arguments like that:
```python
parser.add_argument('--stuff', action='store_true', help=argparse.SUPPRESS)
self.do_stuff("search xx --stuff")
```
|
0.0
|
e7a0be4df68346ac15626c20c4a19c8fabb1bf49
|
[
"tests/test_argparse.py::test_argparser_kwargs",
"tests/test_argparse.py::test_argparser_and_unknown_args_kwargs",
"tests/test_argparse.py::test_arglist_kwargs"
] |
[
"tests/test_argparse.py::test_invalid_syntax",
"tests/test_argparse.py::test_argparse_basic_command",
"tests/test_argparse.py::test_argparse_remove_quotes",
"tests/test_argparse.py::test_argparse_preserve_quotes",
"tests/test_argparse.py::test_argparse_custom_namespace",
"tests/test_argparse.py::test_argparse_with_list",
"tests/test_argparse.py::test_argparse_with_list_remove_quotes",
"tests/test_argparse.py::test_argparse_with_list_preserve_quotes",
"tests/test_argparse.py::test_argparse_with_list_custom_namespace",
"tests/test_argparse.py::test_argparse_with_list_and_empty_doc",
"tests/test_argparse.py::test_argparser_correct_args_with_quotes_and_midline_options",
"tests/test_argparse.py::test_argparse_quoted_arguments_multiple",
"tests/test_argparse.py::test_argparse_help_docstring",
"tests/test_argparse.py::test_argparse_help_description",
"tests/test_argparse.py::test_argparse_prog",
"tests/test_argparse.py::test_arglist",
"tests/test_argparse.py::test_preservelist",
"tests/test_argparse.py::test_subcommand_foo",
"tests/test_argparse.py::test_subcommand_bar",
"tests/test_argparse.py::test_subcommand_base_help",
"tests/test_argparse.py::test_subcommand_help",
"tests/test_argparse.py::test_subcommand_invalid_help"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-21 04:06:58+00:00
|
mit
| 5,067 |
|
python-cmd2__cmd2-975
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff37f57b..7361e195 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@
* Renamed `install_command_set()` and `uninstall_command_set()` to `register_command_set()` and
`unregister_command_set()` for better name consistency.
* Bug Fixes
+ * Fixed help formatting bug in `Cmd2ArgumentParser` when `metavar` is a tuple
+ * Fixed tab completion bug when using `CompletionItem` on an argument whose `metavar` is a tuple
* Added explicit testing against python 3.5.2 for Ubuntu 16.04, and 3.5.3 for Debian 9
* Added fallback definition of typing.Deque (taken from 3.5.4)
* Removed explicit type hints that fail due to a bug in 3.5.2 favoring comment-based hints instead
diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py
index 582f57f6..0efaebe9 100644
--- a/cmd2/argparse_completer.py
+++ b/cmd2/argparse_completer.py
@@ -25,7 +25,7 @@ from .argparse_custom import (
)
from .command_definition import CommandSet
from .table_creator import Column, SimpleTable
-from .utils import CompletionError, basic_complete, get_defining_class
+from .utils import CompletionError, basic_complete
# If no descriptive header is supplied, then this will be used instead
DEFAULT_DESCRIPTIVE_HEADER = 'Description'
@@ -405,7 +405,7 @@ class ArgparseCompleter:
# Check if we are completing a flag's argument
if flag_arg_state is not None:
- completion_results = self._complete_for_arg(flag_arg_state.action, text, line,
+ completion_results = self._complete_for_arg(flag_arg_state, text, line,
begidx, endidx, consumed_arg_values,
cmd_set=cmd_set)
@@ -426,7 +426,7 @@ class ArgparseCompleter:
action = remaining_positionals.popleft()
pos_arg_state = _ArgumentState(action)
- completion_results = self._complete_for_arg(pos_arg_state.action, text, line,
+ completion_results = self._complete_for_arg(pos_arg_state, text, line,
begidx, endidx, consumed_arg_values,
cmd_set=cmd_set)
@@ -461,7 +461,7 @@ class ArgparseCompleter:
return basic_complete(text, line, begidx, endidx, match_against)
- def _format_completions(self, action, completions: List[Union[str, CompletionItem]]) -> List[str]:
+ def _format_completions(self, arg_state: _ArgumentState, completions: List[Union[str, CompletionItem]]) -> List[str]:
# Check if the results are CompletionItems and that there aren't too many to display
if 1 < len(completions) <= self._cmd2_app.max_completion_items and \
isinstance(completions[0], CompletionItem):
@@ -472,9 +472,18 @@ class ArgparseCompleter:
self._cmd2_app.matches_sorted = True
# If a metavar was defined, use that instead of the dest field
- destination = action.metavar if action.metavar else action.dest
-
- desc_header = getattr(action, ATTR_DESCRIPTIVE_COMPLETION_HEADER, None)
+ destination = arg_state.action.metavar if arg_state.action.metavar else arg_state.action.dest
+
+ # Handle case where metavar was a tuple
+ if isinstance(destination, tuple):
+ # Figure out what string in the tuple to use based on how many of the arguments have been completed.
+ # Use min() to avoid going passed the end of the tuple to support nargs being ZERO_OR_MORE and
+ # ONE_OR_MORE. In those cases, argparse limits metavar tuple to 2 elements but we may be completing
+ # the 3rd or more argument here.
+ tuple_index = min(len(destination) - 1, arg_state.count)
+ destination = destination[tuple_index]
+
+ desc_header = getattr(arg_state.action, ATTR_DESCRIPTIVE_COMPLETION_HEADER, None)
if desc_header is None:
desc_header = DEFAULT_DESCRIPTIVE_HEADER
@@ -546,7 +555,7 @@ class ArgparseCompleter:
break
return self._parser.format_help()
- def _complete_for_arg(self, arg_action: argparse.Action,
+ def _complete_for_arg(self, arg_state: _ArgumentState,
text: str, line: str, begidx: int, endidx: int,
consumed_arg_values: Dict[str, List[str]], *,
cmd_set: Optional[CommandSet] = None) -> List[str]:
@@ -556,10 +565,10 @@ class ArgparseCompleter:
:raises: CompletionError if the completer or choices function this calls raises one
"""
# Check if the arg provides choices to the user
- if arg_action.choices is not None:
- arg_choices = arg_action.choices
+ if arg_state.action.choices is not None:
+ arg_choices = arg_state.action.choices
else:
- arg_choices = getattr(arg_action, ATTR_CHOICES_CALLABLE, None)
+ arg_choices = getattr(arg_state.action, ATTR_CHOICES_CALLABLE, None)
if arg_choices is None:
return []
@@ -586,8 +595,8 @@ class ArgparseCompleter:
arg_tokens = {**self._parent_tokens, **consumed_arg_values}
# Include the token being completed
- arg_tokens.setdefault(arg_action.dest, [])
- arg_tokens[arg_action.dest].append(text)
+ arg_tokens.setdefault(arg_state.action.dest, [])
+ arg_tokens[arg_state.action.dest].append(text)
# Add the namespace to the keyword arguments for the function we are calling
kwargs[ARG_TOKENS] = arg_tokens
@@ -617,10 +626,10 @@ class ArgparseCompleter:
arg_choices[index] = str(choice)
# Filter out arguments we already used
- used_values = consumed_arg_values.get(arg_action.dest, [])
+ used_values = consumed_arg_values.get(arg_state.action.dest, [])
arg_choices = [choice for choice in arg_choices if choice not in used_values]
# Do tab completion on the choices
results = basic_complete(text, line, begidx, endidx, arg_choices)
- return self._format_completions(arg_action, results)
+ return self._format_completions(arg_state, results)
diff --git a/cmd2/argparse_custom.py b/cmd2/argparse_custom.py
index d724cb88..12c18644 100644
--- a/cmd2/argparse_custom.py
+++ b/cmd2/argparse_custom.py
@@ -733,7 +733,8 @@ class Cmd2HelpFormatter(argparse.RawTextHelpFormatter):
return ', '.join(action.option_strings) + ' ' + args_string
# End cmd2 customization
- def _metavar_formatter(self, action, default_metavar) -> Callable:
+ def _determine_metavar(self, action, default_metavar) -> Union[str, Tuple]:
+ """Custom method to determine what to use as the metavar value of an action"""
if action.metavar is not None:
result = action.metavar
elif action.choices is not None:
@@ -743,38 +744,46 @@ class Cmd2HelpFormatter(argparse.RawTextHelpFormatter):
# End cmd2 customization
else:
result = default_metavar
+ return result
+
+ def _metavar_formatter(self, action, default_metavar) -> Callable:
+ metavar = self._determine_metavar(action, default_metavar)
# noinspection PyMissingOrEmptyDocstring
def format(tuple_size):
- if isinstance(result, tuple):
- return result
+ if isinstance(metavar, tuple):
+ return metavar
else:
- return (result, ) * tuple_size
+ return (metavar, ) * tuple_size
return format
# noinspection PyProtectedMember
def _format_args(self, action, default_metavar) -> str:
- get_metavar = self._metavar_formatter(action, default_metavar)
- # Begin cmd2 customization (less verbose)
- nargs_range = getattr(action, ATTR_NARGS_RANGE, None)
+ """Customized to handle ranged nargs and make other output less verbose"""
+ metavar = self._determine_metavar(action, default_metavar)
+ metavar_formatter = self._metavar_formatter(action, default_metavar)
+ # Handle nargs specified as a range
+ nargs_range = getattr(action, ATTR_NARGS_RANGE, None)
if nargs_range is not None:
if nargs_range[1] == constants.INFINITY:
range_str = '{}+'.format(nargs_range[0])
else:
range_str = '{}..{}'.format(nargs_range[0], nargs_range[1])
- result = '{}{{{}}}'.format('%s' % get_metavar(1), range_str)
- elif action.nargs == ZERO_OR_MORE:
- result = '[%s [...]]' % get_metavar(1)
- elif action.nargs == ONE_OR_MORE:
- result = '%s [...]' % get_metavar(1)
- elif isinstance(action.nargs, int) and action.nargs > 1:
- result = '{}{{{}}}'.format('%s' % get_metavar(1), action.nargs)
- # End cmd2 customization
- else:
- result = super()._format_args(action, default_metavar)
- return result
+ return '{}{{{}}}'.format('%s' % metavar_formatter(1), range_str)
+
+ # Make this output less verbose. Do not customize the output when metavar is a
+ # tuple of strings. Allow argparse's formatter to handle that instead.
+ elif isinstance(metavar, str):
+ if action.nargs == ZERO_OR_MORE:
+ return '[%s [...]]' % metavar_formatter(1)
+ elif action.nargs == ONE_OR_MORE:
+ return '%s [...]' % metavar_formatter(1)
+ elif isinstance(action.nargs, int) and action.nargs > 1:
+ return '{}{{{}}}'.format('%s' % metavar_formatter(1), action.nargs)
+
+ return super()._format_args(action, default_metavar)
# noinspection PyCompatibility
|
python-cmd2/cmd2
|
133e71a5a3074fc21fa52532d00c4d2364964cd3
|
diff --git a/tests/test_argparse_completer.py b/tests/test_argparse_completer.py
index 4313647b..151923ea 100644
--- a/tests/test_argparse_completer.py
+++ b/tests/test_argparse_completer.py
@@ -107,6 +107,10 @@ class AutoCompleteTester(cmd2.Cmd):
############################################################################################################
# Begin code related to testing choices, choices_function, and choices_method parameters
############################################################################################################
+ STR_METAVAR = "HEADLESS"
+ TUPLE_METAVAR = ('arg1', 'others')
+ CUSTOM_DESC_HEADER = "Custom Header"
+
def choices_method(self) -> List[str]:
"""Method that provides choices"""
return choices_from_method
@@ -128,8 +132,14 @@ class AutoCompleteTester(cmd2.Cmd):
choices_function=choices_function)
choices_parser.add_argument("-m", "--method", help="a flag populated with a choices method",
choices_method=choices_method)
- choices_parser.add_argument('-n', "--no_header", help='this arg has a no descriptive header',
- choices_method=completion_item_method)
+ choices_parser.add_argument('-d', "--desc_header", help='this arg has a descriptive header',
+ choices_method=completion_item_method,
+ descriptive_header=CUSTOM_DESC_HEADER)
+ choices_parser.add_argument('-n', "--no_header", help='this arg has no descriptive header',
+ choices_method=completion_item_method, metavar=STR_METAVAR)
+ choices_parser.add_argument('-t', "--tuple_metavar", help='this arg has tuple for a metavar',
+ choices_method=completion_item_method, metavar=TUPLE_METAVAR,
+ nargs=argparse.ONE_OR_MORE)
choices_parser.add_argument('-i', '--int', type=int, help='a flag with an int type',
choices=static_int_choices_list)
@@ -683,15 +693,73 @@ def test_unfinished_flag_error(ac_app, command_and_args, text, is_error, capsys)
assert is_error == all(x in out for x in ["Error: argument", "expected"])
-def test_completion_items_default_header(ac_app):
+def test_completion_items_arg_header(ac_app):
+ # Test when metavar is None
+ text = ''
+ line = 'choices --desc_header {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ complete_tester(text, line, begidx, endidx, ac_app)
+ assert "DESC_HEADER" in ac_app.completion_header
+
+ # Test when metavar is a string
+ text = ''
+ line = 'choices --no_header {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ complete_tester(text, line, begidx, endidx, ac_app)
+ assert ac_app.STR_METAVAR in ac_app.completion_header
+
+ # Test when metavar is a tuple
+ text = ''
+ line = 'choices --tuple_metavar {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ # We are completing the first argument of this flag. The first element in the tuple should be the column header.
+ complete_tester(text, line, begidx, endidx, ac_app)
+ assert ac_app.TUPLE_METAVAR[0].upper() in ac_app.completion_header
+
+ text = ''
+ line = 'choices --tuple_metavar token_1 {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ # We are completing the second argument of this flag. The second element in the tuple should be the column header.
+ complete_tester(text, line, begidx, endidx, ac_app)
+ assert ac_app.TUPLE_METAVAR[1].upper() in ac_app.completion_header
+
+ text = ''
+ line = 'choices --tuple_metavar token_1 token_2 {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ # We are completing the third argument of this flag. It should still be the second tuple element
+ # in the column header since the tuple only has two strings in it.
+ complete_tester(text, line, begidx, endidx, ac_app)
+ assert ac_app.TUPLE_METAVAR[1].upper() in ac_app.completion_header
+
+
+def test_completion_items_descriptive_header(ac_app):
from cmd2.argparse_completer import DEFAULT_DESCRIPTIVE_HEADER
+ # This argument provided a descriptive header
+ text = ''
+ line = 'choices --desc_header {}'.format(text)
+ endidx = len(line)
+ begidx = endidx - len(text)
+
+ complete_tester(text, line, begidx, endidx, ac_app)
+ assert ac_app.CUSTOM_DESC_HEADER in ac_app.completion_header
+
+ # This argument did not provide a descriptive header, so it should be DEFAULT_DESCRIPTIVE_HEADER
text = ''
- line = 'choices -n {}'.format(text)
+ line = 'choices --no_header {}'.format(text)
endidx = len(line)
begidx = endidx - len(text)
- # This positional argument did not provide a descriptive header, so it should be DEFAULT_DESCRIPTIVE_HEADER
complete_tester(text, line, begidx, endidx, ac_app)
assert DEFAULT_DESCRIPTIVE_HEADER in ac_app.completion_header
diff --git a/tests/test_argparse_custom.py b/tests/test_argparse_custom.py
index f4db12b6..3ce90118 100644
--- a/tests/test_argparse_custom.py
+++ b/tests/test_argparse_custom.py
@@ -260,3 +260,10 @@ def test_override_parser():
# Verify DEFAULT_ARGUMENT_PARSER is now our CustomParser
from examples.custom_parser import CustomParser
assert DEFAULT_ARGUMENT_PARSER == CustomParser
+
+
+def test_apcustom_metavar_tuple():
+ # Test the case when a tuple metavar is used with nargs an integer > 1
+ parser = Cmd2ArgumentParser()
+ parser.add_argument('--aflag', nargs=2, metavar=('foo', 'bar'), help='This is a test')
+ assert '[--aflag foo bar]' in parser.format_help()
|
Bug in Cmd2HelpFormatter and ArgparseCompleter when metavar is a tuple
The [Cmd2HelpFormatter](https://github.com/python-cmd2/cmd2/blob/master/cmd2/argparse_custom.py#L600-L716) class has a bug which causes a crash in the following circumstances:
- `nargs` is an int and > 1
- [metavar](https://docs.python.org/3/library/argparse.html#metavar) is a tuple
Tested with `cmd2` 1.2.0 but verified the bug exists in the current version as well.
In my case, the crash occurs on line 780 in the current code with the [_format_args](https://github.com/python-cmd2/cmd2/blob/master/cmd2/argparse_custom.py#L763-L784) method.
|
0.0
|
133e71a5a3074fc21fa52532d00c4d2364964cd3
|
[
"tests/test_argparse_completer.py::test_help[music]",
"tests/test_argparse_completer.py::test_help[music",
"tests/test_argparse_completer.py::test_bad_subcommand_help",
"tests/test_argparse_completer.py::test_complete_help[-mus-completions0]",
"tests/test_argparse_completer.py::test_complete_help[music-cre-completions1]",
"tests/test_argparse_completer.py::test_complete_help[music-creab-completions2]",
"tests/test_argparse_completer.py::test_complete_help[music",
"tests/test_argparse_completer.py::test_complete_help[fake",
"tests/test_argparse_completer.py::test_subcommand_completions[create--completions0]",
"tests/test_argparse_completer.py::test_subcommand_completions[create-ja-completions1]",
"tests/test_argparse_completer.py::test_subcommand_completions[create-foo-completions2]",
"tests/test_argparse_completer.py::test_subcommand_completions[creab-ja-completions3]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---completions0]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag----completions1]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--n-completions2]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---n-completions3]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--r-completions5]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---r-completions6]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag--s-completions9]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[flag---s-completions10]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag-+-completions13]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag-++-completions14]",
"tests/test_argparse_completer.py::test_autcomp_flag_completion[plus_flag",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-l--completions0]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--list-s-completions1]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-f--completions2]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--function-ch-completions3]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-m--completions4]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--method-m-completions5]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[-i--completions6]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int-1-completions7]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int---completions8]",
"tests/test_argparse_completer.py::test_autocomp_flag_choices_completion[--int--1-completions9]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[1--completions0]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[1-s-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[2--completions2]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[2-ch-completions3]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[3--completions4]",
"tests/test_argparse_completer.py::test_autocomp_positional_choices_completion[3-m-completions5]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[-f--completions0]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[--function-f-completions1]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[-m--completions2]",
"tests/test_argparse_completer.py::test_autocomp_flag_completers[--method-m-completions3]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[1--completions0]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[1-c-completions1]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[2--completions2]",
"tests/test_argparse_completer.py::test_autocomp_positional_completers[2-m-completions3]",
"tests/test_argparse_completer.py::test_autocomp_blank_token",
"tests/test_argparse_completer.py::test_completion_items[1-False]",
"tests/test_argparse_completer.py::test_completion_items[5-True]",
"tests/test_argparse_completer.py::test_completion_items[100-False]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--set_value-completions0]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--set_value",
"tests/test_argparse_completer.py::test_autcomp_nargs[--one_or_more-completions4]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--one_or_more",
"tests/test_argparse_completer.py::test_autcomp_nargs[--optional-completions6]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--optional",
"tests/test_argparse_completer.py::test_autcomp_nargs[--range-completions8]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--range",
"tests/test_argparse_completer.py::test_autcomp_nargs[--remainder-completions11]",
"tests/test_argparse_completer.py::test_autcomp_nargs[--remainder",
"tests/test_argparse_completer.py::test_autcomp_nargs[--",
"tests/test_argparse_completer.py::test_autcomp_nargs[-completions17]",
"tests/test_argparse_completer.py::test_autcomp_nargs[positional-completions18]",
"tests/test_argparse_completer.py::test_autcomp_nargs[positional",
"tests/test_argparse_completer.py::test_autcomp_nargs[the",
"tests/test_argparse_completer.py::test_unfinished_flag_error[hint",
"tests/test_argparse_completer.py::test_unfinished_flag_error[nargs",
"tests/test_argparse_completer.py::test_completion_items_arg_header",
"tests/test_argparse_completer.py::test_completion_items_descriptive_header",
"tests/test_argparse_completer.py::test_autocomp_hint[hint--True]",
"tests/test_argparse_completer.py::test_autocomp_hint[hint",
"tests/test_argparse_completer.py::test_autocomp_hint[nargs",
"tests/test_argparse_completer.py::test_autocomp_hint[hint---False]",
"tests/test_argparse_completer.py::test_autocomp_hint_no_help_text",
"tests/test_argparse_completer.py::test_completion_error[--choice",
"tests/test_argparse_completer.py::test_completion_error[-completer]",
"tests/test_argparse_completer.py::test_arg_tokens[arg_tokens",
"tests/test_argparse_completer.py::test_complete_mutex_group[mutex--the",
"tests/test_argparse_completer.py::test_complete_mutex_group[mutex---fl----flag",
"tests/test_argparse_completer.py::test_complete_mutex_group[mutex",
"tests/test_argparse_completer.py::test_single_prefix_char",
"tests/test_argparse_completer.py::test_looks_like_flag",
"tests/test_argparse_completer.py::test_complete_command_no_tokens",
"tests/test_argparse_completer.py::test_complete_command_help_no_tokens",
"tests/test_argparse_custom.py::test_apcustom_choices_callable_count[kwargs0-True]",
"tests/test_argparse_custom.py::test_apcustom_choices_callable_count[kwargs1-True]",
"tests/test_argparse_custom.py::test_apcustom_choices_callable_count[kwargs2-True]",
"tests/test_argparse_custom.py::test_apcustom_choices_callable_count[kwargs3-True]",
"tests/test_argparse_custom.py::test_apcustom_choices_callable_count[kwargs4-False]",
"tests/test_argparse_custom.py::test_apcustom_choices_callable_count[kwargs5-False]",
"tests/test_argparse_custom.py::test_apcustom_choices_callable_count[kwargs6-False]",
"tests/test_argparse_custom.py::test_apcustom_no_choices_callables_alongside_choices[kwargs0]",
"tests/test_argparse_custom.py::test_apcustom_no_choices_callables_alongside_choices[kwargs1]",
"tests/test_argparse_custom.py::test_apcustom_no_choices_callables_alongside_choices[kwargs2]",
"tests/test_argparse_custom.py::test_apcustom_no_choices_callables_alongside_choices[kwargs3]",
"tests/test_argparse_custom.py::test_apcustom_no_choices_callables_when_nargs_is_0[kwargs0]",
"tests/test_argparse_custom.py::test_apcustom_no_choices_callables_when_nargs_is_0[kwargs1]",
"tests/test_argparse_custom.py::test_apcustom_no_choices_callables_when_nargs_is_0[kwargs2]",
"tests/test_argparse_custom.py::test_apcustom_no_choices_callables_when_nargs_is_0[kwargs3]",
"tests/test_argparse_custom.py::test_apcustom_usage",
"tests/test_argparse_custom.py::test_apcustom_nargs_help_format",
"tests/test_argparse_custom.py::test_apcustom_nargs_range_validation",
"tests/test_argparse_custom.py::test_apcustom_narg_invalid_tuples[nargs_tuple0]",
"tests/test_argparse_custom.py::test_apcustom_narg_invalid_tuples[nargs_tuple1]",
"tests/test_argparse_custom.py::test_apcustom_narg_invalid_tuples[nargs_tuple2]",
"tests/test_argparse_custom.py::test_apcustom_narg_invalid_tuples[nargs_tuple3]",
"tests/test_argparse_custom.py::test_apcustom_narg_tuple_order",
"tests/test_argparse_custom.py::test_apcustom_narg_tuple_negative",
"tests/test_argparse_custom.py::test_apcustom_narg_tuple_zero_base",
"tests/test_argparse_custom.py::test_apcustom_narg_tuple_one_base",
"tests/test_argparse_custom.py::test_apcustom_narg_tuple_other_ranges",
"tests/test_argparse_custom.py::test_apcustom_print_message",
"tests/test_argparse_custom.py::test_generate_range_error",
"tests/test_argparse_custom.py::test_apcustom_required_options",
"tests/test_argparse_custom.py::test_override_parser",
"tests/test_argparse_custom.py::test_apcustom_metavar_tuple"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-12 22:02:51+00:00
|
mit
| 5,068 |
|
python-cmd2__cmd2-987
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index acb29c93..12478a29 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,8 @@
+## 1.3.7 (August 27, 2020)
+* Bug Fixes
+ * Fixes an issue introduced in 1.3.0 with processing command strings containing terminator/separator
+ character(s) that are manually passed to a command that uses argparse.
+
## 1.3.6 (August 27, 2020)
* Breaking changes
* The functions cmd2 adds to Namespaces (`get_statement()` and `get_handler()`) are now
diff --git a/cmd2/decorators.py b/cmd2/decorators.py
index c2689102..4ee61754 100644
--- a/cmd2/decorators.py
+++ b/cmd2/decorators.py
@@ -35,7 +35,7 @@ def with_category(category: str) -> Callable:
return cat_decorator
##########################
-# The _parse_positionals and _swap_args decorators allow for additional positional args to be preserved
+# The _parse_positionals and _arg_swap functions allow for additional positional args to be preserved
# in cmd2 command functions/callables. As long as the 2-ple of arguments we expect to be there can be
# found we can swap out the statement with each decorator's specific parameters
##########################
@@ -276,9 +276,9 @@ def with_argparser(parser: argparse.ArgumentParser, *,
:return: return value of command function
:raises: Cmd2ArgparseError if argparse has error parsing command line
"""
- cmd2_app, statement = _parse_positionals(args)
+ cmd2_app, statement_arg = _parse_positionals(args)
statement, parsed_arglist = cmd2_app.statement_parser.get_command_arg_list(command_name,
- statement,
+ statement_arg,
preserve_quotes)
if ns_provider is None:
@@ -314,7 +314,7 @@ def with_argparser(parser: argparse.ArgumentParser, *,
if hasattr(ns, constants.NS_ATTR_SUBCMD_HANDLER):
delattr(ns, constants.NS_ATTR_SUBCMD_HANDLER)
- args_list = _arg_swap(args, statement, *new_args)
+ args_list = _arg_swap(args, statement_arg, *new_args)
return func(*args_list, **kwargs)
# argparser defaults the program name to sys.argv[0], but we want it to be the name of our command
|
python-cmd2/cmd2
|
e3a07c59b541b4a0b937c62ef38be6d8c011c0a3
|
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index 8688e124..3b240e4e 100755
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -217,6 +217,23 @@ def test_shell_last_result(base_app):
run_cmd(base_app, 'shell fake')
assert base_app.last_result is not None
+
+def test_shell_manual_call(base_app):
+ # Verifies crash from Issue #986 doesn't happen
+ cmds = [
+ 'echo "hi"',
+ 'echo "there"',
+ 'echo "cmd2!"'
+ ]
+ cmd = ';'.join(cmds)
+
+ base_app.do_shell(cmd)
+
+ cmd = '&&'.join(cmds)
+
+ base_app.do_shell(cmd)
+
+
def test_base_py(base_app):
# Make sure py can't edit Cmd.py_locals. It used to be that cmd2 was passing its py_locals
# dictionary to the py environment instead of a shallow copy.
|
The do_shell() is not working correctly with multiple commands
When I call do_shell() with multiple commands using
* ";".join(commands) - it only executes the first command
* "&&".join(commands) - it throws an exception
Given the following script (which has all of the details), you can see the behavior I'm seeing.
```python
#!/usr/bin/env python
"""A simple cmd2 application."""
import cmd2
class App(cmd2.Cmd):
"""
A simple cmd2 application. Copied from "Basic Commands" in the manual.
I had a LOT of Cmd apps/scripts that I was using and then converted most
of them to use Cmd2 and all was working fine with this type of formatting,
(i.e. multiple commands in a string).
At some point, after updating to different versions of cmd2, many of my
commands started breaking like this one does.
I can run SINGLE commands, but not multiple ones -- especially when I just
"join" them from multiple lines to one line. Note though, in the "works"
command, I use just a string passed into *do_shell* and it works, which
surprised me. If I try that with a ";" as the seperator, it does not work,
which is what happens in the "fail1" and "fail2" commands.
I haven't dived into the why, but was able to replicate it quite easily in
something that is pretty small (the comments and me explaining it are
probably going to be much longer than the actual code).
Both failures should work just fine, as they are commands that will work
from:
* the bash prompt
* the Cmd2 shell prompt (i.e. using !<command>)
* the Cmd.do_shell() function (using Cmd, not Cmd2)
I use commands like this all the time. Cmd's do_shell() handles
this as expected. Even Cmd2's command prompt handles the exact same
commands just fine.
If I type something like the following commands, FROM the Cmd2/App command
prompt, they work as expected, so ...
- !echo "hi";echo "there";echo "cmd2"
- !echo "hi"&&echo "there"
- !ls && echo "-----done-----"
I'm not sure where a regression came in at. If needed, I can go back to
the different versions that I'm pretty sure it was working and give it a
try.
This used to work in Cmd2 as well, until a little while ago. I've not
narrowed down the exact date, but I think it's sometime around the new
addition of the CommandSet changes (which I was surprised to find and
wanted to use).
It was around that time (after CommandSet introduction to the code base),
so pretty sure it's after v1.2.1. It's probably after v1.3.0 or v1.3.1, as
I had it working and didn't see any problems with it. Multiple commands
doing just this were added at around that time as well.
I THINK was after v1.3.1, around the time that the CommandSet stuff broke
backward compatibility with itself (as I remember thinking I didn't realize
I was working on such the cutting edge! ;-) ) and I skipped at least one
version if not more, so can't say when, for sure, it broke this functionality.
It was definitely broken after v1.3.4. I upgraded to v1.3.5 today
(2020-08-27) to see if it had been fixed. I wasn't terribly surprised that
it still was broken.
Now for some system information:
OS: macOS Catalina v10.15.5
Python: v3.8.0
Cmd2: v1.3.5
"""
# common commands to show problem
cmds = [
'echo "hi"',
'echo "there"',
'echo "cmd2!"'
]
def __init__(self):
super().__init__()
self.debug = True
def _printMessage(self, cmd):
print(f"\n\n-----cmd=[{cmd}]-----")
print("this fails in 'self.do_shell(cmd)'")
print(f"BUT, it works if you do [!{cmd}] from the (Cmd) prompt\n\n")
def do_fail1(self, statementObj):
# this should work (and used to work),
# but ONLY executes the FIRST command - ignores the rest
cmd = ';'.join(self.cmds)
self._printMessage(cmd)
self.do_shell(cmd)
def do_fail2(self, statementObj):
# this should also work - better bash 'best practice' anyway
# this just fails though
cmd = '&&'.join(self.cmds)
self._printMessage(cmd)
self.do_shell(cmd)
def do_works(self, statementObj):
print("\n")
self.do_shell('echo "this works just fine!"')
print("\nas does this! \n")
self.do_shell('ls -la')
print("\nthis surprisingly DOES work -- not sure why :-( \n")
self.do_shell('ls&&echo "-----done-----"')
print("\n")
if __name__ == '__main__':
import sys
c = App()
sys.exit(c.cmdloop())
```
Thanks!
Mike
|
0.0
|
e3a07c59b541b4a0b937c62ef38be6d8c011c0a3
|
[
"tests/test_cmd2.py::test_shell_manual_call"
] |
[
"tests/test_cmd2.py::test_version",
"tests/test_cmd2.py::test_empty_statement",
"tests/test_cmd2.py::test_base_help",
"tests/test_cmd2.py::test_base_help_verbose",
"tests/test_cmd2.py::test_base_argparse_help",
"tests/test_cmd2.py::test_base_invalid_option",
"tests/test_cmd2.py::test_base_shortcuts",
"tests/test_cmd2.py::test_command_starts_with_shortcut",
"tests/test_cmd2.py::test_base_show",
"tests/test_cmd2.py::test_base_show_long",
"tests/test_cmd2.py::test_set",
"tests/test_cmd2.py::test_set_val_empty",
"tests/test_cmd2.py::test_set_val_is_flag",
"tests/test_cmd2.py::test_set_not_supported",
"tests/test_cmd2.py::test_set_no_settables",
"tests/test_cmd2.py::test_set_allow_style[Never-True-Never]",
"tests/test_cmd2.py::test_set_allow_style[neVeR-True-Never]",
"tests/test_cmd2.py::test_set_allow_style[Terminal-True-Terminal]",
"tests/test_cmd2.py::test_set_allow_style[TeRMInal-True-Terminal]",
"tests/test_cmd2.py::test_set_allow_style[Always-True-Always]",
"tests/test_cmd2.py::test_set_allow_style[AlWaYs-True-Always]",
"tests/test_cmd2.py::test_set_allow_style[invalid-False-Terminal]",
"tests/test_cmd2.py::test_set_onchange_hook",
"tests/test_cmd2.py::test_base_shell",
"tests/test_cmd2.py::test_shell_last_result",
"tests/test_cmd2.py::test_base_py",
"tests/test_cmd2.py::test_base_error",
"tests/test_cmd2.py::test_run_script",
"tests/test_cmd2.py::test_run_script_with_empty_args",
"tests/test_cmd2.py::test_run_script_with_nonexistent_file",
"tests/test_cmd2.py::test_run_script_with_directory",
"tests/test_cmd2.py::test_run_script_with_empty_file",
"tests/test_cmd2.py::test_run_script_with_binary_file",
"tests/test_cmd2.py::test_run_script_with_python_file",
"tests/test_cmd2.py::test_run_script_with_utf8_file",
"tests/test_cmd2.py::test_run_script_nested_run_scripts",
"tests/test_cmd2.py::test_runcmds_plus_hooks",
"tests/test_cmd2.py::test_runcmds_plus_hooks_ctrl_c",
"tests/test_cmd2.py::test_relative_run_script",
"tests/test_cmd2.py::test_relative_run_script_with_odd_file_names[nothingweird]",
"tests/test_cmd2.py::test_relative_run_script_with_odd_file_names[has",
"tests/test_cmd2.py::test_relative_run_script_with_odd_file_names[\"is_double_quoted\"]",
"tests/test_cmd2.py::test_relative_run_script_with_odd_file_names['is_single_quoted']",
"tests/test_cmd2.py::test_relative_run_script_requires_an_argument",
"tests/test_cmd2.py::test_in_script",
"tests/test_cmd2.py::test_system_exit_in_command",
"tests/test_cmd2.py::test_output_redirection",
"tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory",
"tests/test_cmd2.py::test_output_redirection_to_too_long_filename",
"tests/test_cmd2.py::test_feedback_to_output_true",
"tests/test_cmd2.py::test_feedback_to_output_false",
"tests/test_cmd2.py::test_disallow_redirection",
"tests/test_cmd2.py::test_pipe_to_shell",
"tests/test_cmd2.py::test_pipe_to_shell_and_redirect",
"tests/test_cmd2.py::test_pipe_to_shell_error",
"tests/test_cmd2.py::test_base_timing",
"tests/test_cmd2.py::test_base_debug",
"tests/test_cmd2.py::test_debug_not_settable",
"tests/test_cmd2.py::test_remove_settable_keyerror",
"tests/test_cmd2.py::test_edit_file",
"tests/test_cmd2.py::test_edit_file_with_odd_file_names[nothingweird]",
"tests/test_cmd2.py::test_edit_file_with_odd_file_names[has",
"tests/test_cmd2.py::test_edit_file_with_odd_file_names[\"is_double_quoted\"]",
"tests/test_cmd2.py::test_edit_file_with_odd_file_names['is_single_quoted']",
"tests/test_cmd2.py::test_edit_file_with_spaces",
"tests/test_cmd2.py::test_edit_blank",
"tests/test_cmd2.py::test_base_py_interactive",
"tests/test_cmd2.py::test_base_cmdloop_with_startup_commands",
"tests/test_cmd2.py::test_base_cmdloop_without_startup_commands",
"tests/test_cmd2.py::test_cmdloop_without_rawinput",
"tests/test_cmd2.py::test_stty_sane",
"tests/test_cmd2.py::test_precmd_hook_success",
"tests/test_cmd2.py::test_precmd_hook_failure",
"tests/test_cmd2.py::test_interrupt_quit",
"tests/test_cmd2.py::test_interrupt_noquit",
"tests/test_cmd2.py::test_default_to_shell",
"tests/test_cmd2.py::test_ansi_prompt_not_esacped",
"tests/test_cmd2.py::test_ansi_prompt_escaped",
"tests/test_cmd2.py::test_custom_command_help",
"tests/test_cmd2.py::test_custom_help_menu",
"tests/test_cmd2.py::test_help_undocumented",
"tests/test_cmd2.py::test_help_overridden_method",
"tests/test_cmd2.py::test_help_cat_base",
"tests/test_cmd2.py::test_help_cat_verbose",
"tests/test_cmd2.py::test_select_options",
"tests/test_cmd2.py::test_select_invalid_option_too_big",
"tests/test_cmd2.py::test_select_invalid_option_too_small",
"tests/test_cmd2.py::test_select_list_of_strings",
"tests/test_cmd2.py::test_select_list_of_tuples",
"tests/test_cmd2.py::test_select_uneven_list_of_tuples",
"tests/test_cmd2.py::test_select_eof",
"tests/test_cmd2.py::test_select_ctrl_c",
"tests/test_cmd2.py::test_help_with_no_docstring",
"tests/test_cmd2.py::test_which_editor_good",
"tests/test_cmd2.py::test_which_editor_bad",
"tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception",
"tests/test_cmd2.py::test_multiline_complete_statement_without_terminator",
"tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes",
"tests/test_cmd2.py::test_multiline_input_line_to_statement",
"tests/test_cmd2.py::test_clipboard_failure",
"tests/test_cmd2.py::test_commandresult_truthy",
"tests/test_cmd2.py::test_commandresult_falsy",
"tests/test_cmd2.py::test_is_text_file_bad_input",
"tests/test_cmd2.py::test_eof",
"tests/test_cmd2.py::test_echo",
"tests/test_cmd2.py::test_read_input_rawinput_true",
"tests/test_cmd2.py::test_read_input_rawinput_false",
"tests/test_cmd2.py::test_read_command_line_eof",
"tests/test_cmd2.py::test_poutput_string",
"tests/test_cmd2.py::test_poutput_zero",
"tests/test_cmd2.py::test_poutput_empty_string",
"tests/test_cmd2.py::test_poutput_none",
"tests/test_cmd2.py::test_poutput_ansi_always",
"tests/test_cmd2.py::test_poutput_ansi_never",
"tests/test_cmd2.py::test_get_alias_completion_items",
"tests/test_cmd2.py::test_get_macro_completion_items",
"tests/test_cmd2.py::test_get_settable_completion_items",
"tests/test_cmd2.py::test_alias_no_subcommand",
"tests/test_cmd2.py::test_alias_create",
"tests/test_cmd2.py::test_alias_create_with_quoted_value",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[#]",
"tests/test_cmd2.py::test_alias_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"no",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_alias_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_alias_create_with_command_name",
"tests/test_cmd2.py::test_alias_create_with_macro_name",
"tests/test_cmd2.py::test_alias_that_resolves_into_comment",
"tests/test_cmd2.py::test_alias_list_invalid_alias",
"tests/test_cmd2.py::test_alias_delete",
"tests/test_cmd2.py::test_alias_delete_all",
"tests/test_cmd2.py::test_alias_delete_non_existing",
"tests/test_cmd2.py::test_alias_delete_no_name",
"tests/test_cmd2.py::test_multiple_aliases",
"tests/test_cmd2.py::test_macro_no_subcommand",
"tests/test_cmd2.py::test_macro_create",
"tests/test_cmd2.py::test_macro_create_with_quoted_value",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[#]",
"tests/test_cmd2.py::test_macro_create_invalid_name[!no_shortcut]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\">\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no>pe\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"no",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"nopipe|\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[\"noterm;\"]",
"tests/test_cmd2.py::test_macro_create_invalid_name[noembedded\"quotes]",
"tests/test_cmd2.py::test_macro_create_with_command_name",
"tests/test_cmd2.py::test_macro_create_with_alias_name",
"tests/test_cmd2.py::test_macro_create_with_args",
"tests/test_cmd2.py::test_macro_create_with_escaped_args",
"tests/test_cmd2.py::test_macro_usage_with_missing_args",
"tests/test_cmd2.py::test_macro_usage_with_exta_args",
"tests/test_cmd2.py::test_macro_create_with_missing_arg_nums",
"tests/test_cmd2.py::test_macro_create_with_invalid_arg_num",
"tests/test_cmd2.py::test_macro_create_with_unicode_numbered_arg",
"tests/test_cmd2.py::test_macro_create_with_missing_unicode_arg_nums",
"tests/test_cmd2.py::test_macro_that_resolves_into_comment",
"tests/test_cmd2.py::test_macro_list_invalid_macro",
"tests/test_cmd2.py::test_macro_delete",
"tests/test_cmd2.py::test_macro_delete_all",
"tests/test_cmd2.py::test_macro_delete_non_existing",
"tests/test_cmd2.py::test_macro_delete_no_name",
"tests/test_cmd2.py::test_multiple_macros",
"tests/test_cmd2.py::test_nonexistent_macro",
"tests/test_cmd2.py::test_perror_style",
"tests/test_cmd2.py::test_perror_no_style",
"tests/test_cmd2.py::test_pwarning_style",
"tests/test_cmd2.py::test_pwarning_no_style",
"tests/test_cmd2.py::test_ppaged",
"tests/test_cmd2.py::test_ppaged_blank",
"tests/test_cmd2.py::test_ppaged_none",
"tests/test_cmd2.py::test_ppaged_strips_ansi_when_redirecting",
"tests/test_cmd2.py::test_ppaged_strips_ansi_when_redirecting_if_always",
"tests/test_cmd2.py::test_parseline_empty",
"tests/test_cmd2.py::test_parseline",
"tests/test_cmd2.py::test_onecmd_raw_str_continue",
"tests/test_cmd2.py::test_onecmd_raw_str_quit",
"tests/test_cmd2.py::test_onecmd_add_to_history",
"tests/test_cmd2.py::test_get_all_commands",
"tests/test_cmd2.py::test_get_help_topics",
"tests/test_cmd2.py::test_get_help_topics_hidden",
"tests/test_cmd2.py::test_exit_code_default",
"tests/test_cmd2.py::test_exit_code_nonzero",
"tests/test_cmd2.py::test_ansi_pouterr_always_tty",
"tests/test_cmd2.py::test_ansi_pouterr_always_notty",
"tests/test_cmd2.py::test_ansi_terminal_tty",
"tests/test_cmd2.py::test_ansi_terminal_notty",
"tests/test_cmd2.py::test_ansi_never_tty",
"tests/test_cmd2.py::test_ansi_never_notty",
"tests/test_cmd2.py::test_disable_and_enable_category",
"tests/test_cmd2.py::test_enable_enabled_command",
"tests/test_cmd2.py::test_disable_fake_command",
"tests/test_cmd2.py::test_disable_command_twice",
"tests/test_cmd2.py::test_disabled_command_not_in_history",
"tests/test_cmd2.py::test_disabled_message_command_name",
"tests/test_cmd2.py::test_startup_script",
"tests/test_cmd2.py::test_startup_script_with_odd_file_names[nothingweird]",
"tests/test_cmd2.py::test_startup_script_with_odd_file_names[has",
"tests/test_cmd2.py::test_startup_script_with_odd_file_names[\"is_double_quoted\"]",
"tests/test_cmd2.py::test_startup_script_with_odd_file_names['is_single_quoted']",
"tests/test_cmd2.py::test_transcripts_at_init"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-27 21:08:50+00:00
|
mit
| 5,069 |
|
python-control__python-control-834
|
diff --git a/control/sisotool.py b/control/sisotool.py
index 2b735c0..8a3b3d9 100644
--- a/control/sisotool.py
+++ b/control/sisotool.py
@@ -158,9 +158,11 @@ def _SisotoolUpdate(sys, fig, K, bode_plot_params, tvect=None):
ax_phase.set_xlabel(ax_phase.get_xlabel(),fontsize=label_font_size)
ax_phase.set_ylabel(ax_phase.get_ylabel(),fontsize=label_font_size)
ax_phase.get_xaxis().set_label_coords(0.5, -0.15)
- ax_phase.get_shared_x_axes().join(ax_phase, ax_mag)
ax_phase.tick_params(axis='both', which='major', labelsize=label_font_size)
+ if not ax_phase.get_shared_x_axes().joined(ax_phase, ax_mag):
+ ax_phase.sharex(ax_mag)
+
ax_step.set_title('Step response',fontsize = title_font_size)
ax_step.set_xlabel('Time (seconds)',fontsize=label_font_size)
ax_step.set_ylabel('Output',fontsize=label_font_size)
diff --git a/doc/conf.py b/doc/conf.py
index 9611791..e2e4201 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -202,7 +202,7 @@ def linkcode_resolve(domain, info):
linespec = ""
base_url = "https://github.com/python-control/python-control/blob/"
- if 'dev' in control.__version__ or 'post' in control.__version__:
+ if 'dev' in control.__version__:
return base_url + "main/control/%s%s" % (fn, linespec)
else:
return base_url + "%s/control/%s%s" % (
diff --git a/pyproject.toml b/pyproject.toml
index 0800bd5..01b2155 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -11,6 +11,7 @@ name = "control"
description = "Python Control Systems Library"
authors = [{name = "Python Control Developers", email = "[email protected]"}]
license = {text = "BSD-3-Clause"}
+readme = "README.rst"
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Science/Research",
|
python-control/python-control
|
18975c5162e8d6b3cd43730f8734c935b340161c
|
diff --git a/control/tests/sisotool_test.py b/control/tests/sisotool_test.py
index d4a2910..fde5eba 100644
--- a/control/tests/sisotool_test.py
+++ b/control/tests/sisotool_test.py
@@ -83,6 +83,12 @@ class TestSisotool:
'margins': True
}
+ # Check that the xaxes of the bode plot are shared before the rlocus click
+ assert ax_mag.get_xlim() == ax_phase.get_xlim()
+ ax_mag.set_xlim(2, 12)
+ assert ax_mag.get_xlim() == (2, 12)
+ assert ax_phase.get_xlim() == (2, 12)
+
# Move the rootlocus to another point
event = type('test', (object,), {'xdata': 2.31206868287,
'ydata': 15.5983051046,
@@ -116,6 +122,12 @@ class TestSisotool:
assert_array_almost_equal(
ax_step.lines[0].get_data()[1][:10], step_response_moved, 4)
+ # Check that the xaxes of the bode plot are still shared after the rlocus click
+ assert ax_mag.get_xlim() == ax_phase.get_xlim()
+ ax_mag.set_xlim(3, 13)
+ assert ax_mag.get_xlim() == (3, 13)
+ assert ax_phase.get_xlim() == (3, 13)
+
@pytest.mark.skipif(plt.get_current_fig_manager().toolbar is None,
reason="Requires the zoom toolbar")
@pytest.mark.parametrize('tsys', [0, True],
|
Matplotlib join() deprecated; need to update sisotool
In doing the release for v0.9.3, I found the following warning in the logs:
```
/home/runner/work/python-control/python-control/control/sisotool.py:161: MatplotlibDeprecationWarning: The join function was deprecated in Matplotlib 3.6 and will be removed two minor releases later.
[3339](https://github.com/python-control/python-control/actions/runs/3808966270/jobs/6480141305#step:6:3340)
ax_phase.get_shared_x_axes().join(ax_phase, ax_mag)
```
We should fix this at some point.
|
0.0
|
18975c5162e8d6b3cd43730f8734c935b340161c
|
[
"control/tests/sisotool_test.py::TestSisotool::test_sisotool_mimo"
] |
[
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-P-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-P-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-P-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-I-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-I-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-I-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-D-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-D-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-r-1-D-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-P-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-P-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-P-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-I-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-I-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-I-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-D-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-D-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-0-0.01-0.1-1.0-0-d-1-D-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-P-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-P-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-P-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-I-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-I-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-I-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-D-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-D-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-r-1-D-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-P-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-P-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-P-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-I-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-I-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-I-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-D-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-D-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-True-1-0.01-0.1-1.0-0-d-1-D-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-P-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-P-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-P-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-I-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-I-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-I-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-D-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-D-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-r-1-D-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-P-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-P-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-P-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-I-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-I-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-I-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-D-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-D-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-0-0.01-0.1-1.0-0-d-1-D-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-P-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-P-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-P-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-I-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-I-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-I-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-D-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-D-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-r-1-D-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-P-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-P-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-P-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-I-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-I-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-I-syscont221]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-D-syscont]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-D-sysdisc1]",
"control/tests/sisotool_test.py::TestPidDesigner::test_pid_designer_1[kwargs0-False-1-0.01-0.1-1.0-0-d-1-D-syscont221]"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-31 20:28:20+00:00
|
bsd-3-clause
| 5,070 |
|
python-control__python-control-892
|
diff --git a/control/iosys.py b/control/iosys.py
index 78444f7..dca00d3 100644
--- a/control/iosys.py
+++ b/control/iosys.py
@@ -1862,7 +1862,7 @@ def input_output_response(
return TimeResponseData(
t_eval, y, None, u, issiso=sys.issiso(),
- output_labels=sys.output_index, input_labels=sys.input_index,
+ output_labels=sys.output_labels, input_labels=sys.input_labels,
transpose=transpose, return_x=return_x, squeeze=squeeze)
# Create a lambda function for the right hand side
@@ -1941,8 +1941,8 @@ def input_output_response(
return TimeResponseData(
soln.t, y, soln.y, u, issiso=sys.issiso(),
- output_labels=sys.output_index, input_labels=sys.input_index,
- state_labels=sys.state_index,
+ output_labels=sys.output_labels, input_labels=sys.input_labels,
+ state_labels=sys.state_labels,
transpose=transpose, return_x=return_x, squeeze=squeeze)
@@ -2881,7 +2881,7 @@ def interconnect(
# Look for the signal name as a system input
for sys in syslist:
- if signal_name in sys.input_index.keys():
+ if signal_name in sys.input_labels:
connection.append(sign + sys.name + "." + signal_name)
# Make sure we found the name
diff --git a/control/statesp.py b/control/statesp.py
index 41f92ae..8661d87 100644
--- a/control/statesp.py
+++ b/control/statesp.py
@@ -1777,7 +1777,9 @@ def _mimo2siso(sys, input, output, warn_conversion=False):
new_B = sys.B[:, input]
new_C = sys.C[output, :]
new_D = sys.D[output, input]
- sys = StateSpace(sys.A, new_B, new_C, new_D, sys.dt)
+ sys = StateSpace(sys.A, new_B, new_C, new_D, sys.dt,
+ name=sys.name,
+ inputs=sys.input_labels[input], outputs=sys.output_labels[output])
return sys
@@ -1826,7 +1828,9 @@ def _mimo2simo(sys, input, warn_conversion=False):
# Y = C*X + D*U
new_B = sys.B[:, input:input+1]
new_D = sys.D[:, input:input+1]
- sys = StateSpace(sys.A, new_B, sys.C, new_D, sys.dt)
+ sys = StateSpace(sys.A, new_B, sys.C, new_D, sys.dt,
+ name=sys.name,
+ inputs=sys.input_labels[input], outputs=sys.output_labels)
return sys
diff --git a/control/timeresp.py b/control/timeresp.py
index 638a073..bd8595c 100644
--- a/control/timeresp.py
+++ b/control/timeresp.py
@@ -694,7 +694,10 @@ def _process_labels(labels, signal, length):
raise ValueError("Name dictionary for %s is incomplete" % signal)
# Convert labels to a list
- labels = list(labels)
+ if isinstance(labels, str):
+ labels = [labels]
+ else:
+ labels = list(labels)
# Make sure the signal list is the right length and type
if len(labels) != length:
@@ -1111,6 +1114,8 @@ def forced_response(sys, T=None, U=0., X0=0., transpose=False,
return TimeResponseData(
tout, yout, xout, U, issiso=sys.issiso(),
+ output_labels=sys.output_labels, input_labels=sys.input_labels,
+ state_labels=sys.state_labels,
transpose=transpose, return_x=return_x, squeeze=squeeze)
@@ -1374,8 +1379,16 @@ def step_response(sys, T=None, X0=0., input=None, output=None, T_num=None,
# Figure out if the system is SISO or not
issiso = sys.issiso() or (input is not None and output is not None)
+ # Select only the given input and output, if any
+ input_labels = sys.input_labels if input is None \
+ else sys.input_labels[input]
+ output_labels = sys.output_labels if output is None \
+ else sys.output_labels[output]
+
return TimeResponseData(
response.time, yout, xout, uout, issiso=issiso,
+ output_labels=output_labels, input_labels=input_labels,
+ state_labels=sys.state_labels,
transpose=transpose, return_x=return_x, squeeze=squeeze)
@@ -1704,9 +1717,15 @@ def initial_response(sys, T=None, X0=0., input=0, output=None, T_num=None,
# Figure out if the system is SISO or not
issiso = sys.issiso() or (input is not None and output is not None)
+ # Select only the given output, if any
+ output_labels = sys.output_labels if output is None \
+ else sys.output_labels[0]
+
# Store the response without an input
return TimeResponseData(
response.t, response.y, response.x, None, issiso=issiso,
+ output_labels=output_labels, input_labels=None,
+ state_labels=sys.state_labels,
transpose=transpose, return_x=return_x, squeeze=squeeze)
@@ -1798,7 +1817,7 @@ def impulse_response(sys, T=None, X0=0., input=None, output=None, T_num=None,
-----
This function uses the `forced_response` function to compute the time
response. For continuous time systems, the initial condition is altered to
- account for the initial impulse. For discrete-time aystems, the impulse is
+ account for the initial impulse. For discrete-time aystems, the impulse is
sized so that it has unit area.
Examples
@@ -1869,8 +1888,16 @@ def impulse_response(sys, T=None, X0=0., input=None, output=None, T_num=None,
# Figure out if the system is SISO or not
issiso = sys.issiso() or (input is not None and output is not None)
+ # Select only the given input and output, if any
+ input_labels = sys.input_labels if input is None \
+ else sys.input_labels[input]
+ output_labels = sys.output_labels if output is None \
+ else sys.output_labels[output]
+
return TimeResponseData(
response.time, yout, xout, uout, issiso=issiso,
+ output_labels=output_labels, input_labels=input_labels,
+ state_labels=sys.state_labels,
transpose=transpose, return_x=return_x, squeeze=squeeze)
|
python-control/python-control
|
9c26e2214f82e592b5b64cf8f581ac14c198a46f
|
diff --git a/control/tests/trdata_test.py b/control/tests/trdata_test.py
index 734d355..028e535 100644
--- a/control/tests/trdata_test.py
+++ b/control/tests/trdata_test.py
@@ -196,15 +196,20 @@ def test_response_copy():
with pytest.raises(ValueError, match="not enough"):
t, y, x = response_mimo
- # Labels
- assert response_mimo.output_labels is None
- assert response_mimo.state_labels is None
- assert response_mimo.input_labels is None
+ # Make sure labels are transferred to the response
+ assert response_siso.output_labels == sys_siso.output_labels
+ assert response_siso.state_labels == sys_siso.state_labels
+ assert response_siso.input_labels == sys_siso.input_labels
+ assert response_mimo.output_labels == sys_mimo.output_labels
+ assert response_mimo.state_labels == sys_mimo.state_labels
+ assert response_mimo.input_labels == sys_mimo.input_labels
+
+ # Check relabelling
response = response_mimo(
output_labels=['y1', 'y2'], input_labels='u',
- state_labels=["x[%d]" % i for i in range(4)])
+ state_labels=["x%d" % i for i in range(4)])
assert response.output_labels == ['y1', 'y2']
- assert response.state_labels == ['x[0]', 'x[1]', 'x[2]', 'x[3]']
+ assert response.state_labels == ['x0', 'x1', 'x2', 'x3']
assert response.input_labels == ['u']
# Unknown keyword
@@ -231,6 +236,17 @@ def test_trdata_labels():
np.testing.assert_equal(
response.input_labels, ["u[%d]" % i for i in range(sys.ninputs)])
+ # Make sure the selected input and output are both correctly transferred to the response
+ for nu in range(sys.ninputs):
+ for ny in range(sys.noutputs):
+ step_response = ct.step_response(sys, T, input=nu, output=ny)
+ assert step_response.input_labels == [sys.input_labels[nu]]
+ assert step_response.output_labels == [sys.output_labels[ny]]
+
+ init_response = ct.initial_response(sys, T, input=nu, output=ny)
+ assert init_response.input_labels == None
+ assert init_response.output_labels == [sys.output_labels[ny]]
+
def test_trdata_multitrace():
#
|
Missing labels from forced_response output
Hi,
I wrote a state-space system representation with labels, like:
``` Python
sys = ct.ss(
A, B, C, D,
name="motor",
states=("Ia", "Wm"),
inputs=("Va", "Tl"),
outputs=("Ia", "Wm", "Va", "Tl"),
)
```
But after simulating it, the result (a `TimeResponseData`), lacks information about the labels of the simulated system:
``` Python
T = np.linspace(0, 0.360, 360)
Va = np.ones_like(T) * 36
Tl = np.linspace(0, 15, len(T))
res = ct.forced_response(motor, T, U=[Va, Tl], X0=[0, 0])
print(res.output_labels) # this is None
print(res.input_labels) # this is None
print(res.state_labels) # this is None
```
I wanted to use `.to_pandas()`, and after assigning it manually, it works, so it's probably just a matter of passing it forward internally in the code:
``` Python
res.output_labels = motor.output_labels
res.input_labels = motor.input_labels
res.state_labels = motor.state_labels
df = res.to_pandas().set_index("time")
```
For completeness, this is the error if I try to use `.to_pandass()` without the abovementioned workaround:
``` Python
648 # Create a dict for setting up the data frame
649 data = {'time': self.time}
650 data.update(
--> 651 {name: self.u[i] for i, name in enumerate(self.input_labels)})
652 data.update(
653 {name: self.y[i] for i, name in enumerate(self.output_labels)})
654 data.update(
655 {name: self.x[i] for i, name in enumerate(self.state_labels)})
TypeError: 'NoneType' object is not iterable
```
Thanks
|
0.0
|
9c26e2214f82e592b5b64cf8f581ac14c198a46f
|
[
"control/tests/trdata_test.py::test_response_copy",
"control/tests/trdata_test.py::test_trdata_labels"
] |
[
"control/tests/trdata_test.py::test_trdata_shapes[1-1-None]",
"control/tests/trdata_test.py::test_trdata_shapes[1-1-True]",
"control/tests/trdata_test.py::test_trdata_shapes[1-1-False]",
"control/tests/trdata_test.py::test_trdata_shapes[1-2-None]",
"control/tests/trdata_test.py::test_trdata_shapes[1-2-True]",
"control/tests/trdata_test.py::test_trdata_shapes[1-2-False]",
"control/tests/trdata_test.py::test_trdata_shapes[2-1-None]",
"control/tests/trdata_test.py::test_trdata_shapes[2-1-True]",
"control/tests/trdata_test.py::test_trdata_shapes[2-1-False]",
"control/tests/trdata_test.py::test_trdata_shapes[2-3-None]",
"control/tests/trdata_test.py::test_trdata_shapes[2-3-True]",
"control/tests/trdata_test.py::test_trdata_shapes[2-3-False]",
"control/tests/trdata_test.py::test_trdata_multitrace",
"control/tests/trdata_test.py::test_trdata_exceptions"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-05-20 16:48:37+00:00
|
bsd-3-clause
| 5,071 |
|
python-jsonschema__check-jsonschema-166
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 8f1912c..b752e3d 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -12,6 +12,8 @@ Unreleased
- Update vendored schemas (2022-10-20)
- Tweak format checker usage to avoid deprecation warning from ``jsonschema``
+- The Azure Pipelines data transform is now more permissive, which should allow
+ it to handle a wider variety of pipelines files (:issue:`162`)
0.18.3
------
diff --git a/src/check_jsonschema/transforms/azure_pipelines.py b/src/check_jsonschema/transforms/azure_pipelines.py
index bdfd107..516ae6c 100644
--- a/src/check_jsonschema/transforms/azure_pipelines.py
+++ b/src/check_jsonschema/transforms/azure_pipelines.py
@@ -85,19 +85,39 @@ def traverse_dict(data: dict) -> dict:
if is_expression(key):
# WARNING -- correctness unclear
#
- # in the case that an expression in a dict does not map to a dict, the
- # azure-pipelines-language server will drop it from the data:
- # https://github.com/microsoft/azure-pipelines-language-server/blob/71b20f92874c02dfe82ad2cc2dcc7fa64996be91/language-service/src/parser/yamlParser.ts#L185
+ # "lift" any dict by moving its attributes up into the object being evaluated
+ #
+ # e.g.
+ # parent:
+ # ${{ each x in xs }}:
+ # - k: v-${{ x }}
+ #
+ # becomes
#
- # instead, we'll raise an error
+ # parent:
+ # - k: v-${{ x }}
if isinstance(newvalue, dict):
for add_k, add_v in newvalue.items():
newdata[add_k] = add_v
+ # In all other cases, drop the content from the data. This is based on the
+ # azure-pipelines-language server behavior:
+ # https://github.com/microsoft/azure-pipelines-language-server/blob/71b20f92874c02dfe82ad2cc2dcc7fa64996be91/language-service/src/parser/yamlParser.ts#L185
+ #
+ # earlier versions would raise an error here, but this caused issues with
+ # data in which expressions were mapped to simple strings
+ #
+ # e.g.
+ #
+ # parent:
+ # ${{ x }}: ${{ y }}
+ #
+ # which occurs naturally *after* a lifting operation, as in
+ #
+ # parent:
+ # ${{ each x, y in attrs }}:
+ # ${{ x }}: ${{ y }}
else:
- raise AzurePipelinesDataError(
- "found non-object data under an expression in an object, "
- f"expression={key}"
- )
+ continue
else:
newdata[key] = newvalue
return newdata
|
python-jsonschema/check-jsonschema
|
179a3d4307800940889dc29ff0a05f4c66a4b4ab
|
diff --git a/tests/example-files/hooks/positive/azure-pipelines/object-defined-by-expression-map.yaml b/tests/example-files/hooks/positive/azure-pipelines/object-defined-by-expression-map.yaml
new file mode 100644
index 0000000..b789a27
--- /dev/null
+++ b/tests/example-files/hooks/positive/azure-pipelines/object-defined-by-expression-map.yaml
@@ -0,0 +1,15 @@
+parameters:
+ - name: env
+ default:
+ - key: FOO
+ value: foo
+ - key: BAR
+ value: bar
+
+jobs:
+ - job: echo-foo-bar
+ steps:
+ - bash: 'echo "$FOO-$BAR"'
+ env:
+ ${{ each pair in parameters.env }}:
+ ${{ pair.key }}: ${{ pair.value }}
|
AzurePipelinesDataError on valid expression syntax
Looking to validate my Azure pipelines and have run into a blocker. I currently have a pipeline in production ( working and running ) with the following syntax
steps:
- bash: |
pipenv run pip install ansible-lint-junit --upgrade
pipenv run ansible-lint -c ../.config/ansible-lint.yml -p --nocolor > ansible-lint.txt
pipenv run ansible-lint-junit ansible-lint.txt -o AnsibleLintReport.xml
displayName: "Lint"
workingDirectory: ${{parameters.workdir}}
env:
${{ each pair in parameters.env }}:
${{ pair.key }}: ${{ pair.value }}
when running with the pre-commit hook
- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.18.3
hooks:
- id: check-azure-pipelines
files: '^.azure/.*\.yml'
it currently raises the error
raise AzurePipelinesDataError(
check_jsonschema.transforms.azure_pipelines.AzurePipelinesDataError: azure-pipelines transform: found non-object data under an expression in an object, expression=${{ pair.key }}
|
0.0
|
179a3d4307800940889dc29ff0a05f4c66a4b4ab
|
[
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/azure-pipelines/object-defined-by-expression-map.yaml]"
] |
[
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/metaschema/almost_empty.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/metaschema/draft3.json]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/metaschema/draft7.json]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/azure-pipelines/expression-from-lang-server.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/azure-pipelines/expression-transform.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/azure-pipelines/marshmallow.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/github-actions/redis-simple.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/github-workflows/self-build.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/github-workflows/has-unicode.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/gitlab-ci/reference-tag.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/readthedocs/simple.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/renovate/starter-config.json]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[positive/travis/python-build.yaml]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[negative/metaschema/draft7_title_array.json]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[negative/metaschema/draft7_title_array.yaml]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[negative/github-workflows/empty.json]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[negative/readthedocs/pyversion-float.yml]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[complex-yaml]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[simple-toml]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[integer-keys-yaml]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[complex-toml]",
"tests/acceptance/test_format_failure.py::test_format_check_passing",
"tests/acceptance/test_format_failure.py::test_format_failure_exit_error",
"tests/acceptance/test_format_failure.py::test_format_failure_ignore",
"tests/acceptance/test_format_failure.py::test_format_failure_ignore_multidoc",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_good[disabled]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_good[default]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_good[python]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_accepts_non_str_inputs[disabled]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_accepts_non_str_inputs[default]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_accepts_non_str_inputs[python]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_bad[disabled]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_bad[default]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_bad[python]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_js_specific[disabled]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_js_specific[default]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_js_specific[python]",
"tests/acceptance/test_format_regex_opts.py::test_regex_format_in_renovate_config",
"tests/acceptance/test_gitlab_reference_handling.py::test_gitlab_reference_handling_on_bad_data",
"tests/acceptance/test_invalid_schema_files.py::test_checker_non_json_schemafile",
"tests/acceptance/test_invalid_schema_files.py::test_checker_invalid_schemafile",
"tests/acceptance/test_invalid_schema_files.py::test_checker_invalid_schemafile_scheme",
"tests/acceptance/test_local_relative_ref.py::test_local_ref_schema[True-main_schema0-other_schema_data0-instance0]",
"tests/acceptance/test_local_relative_ref.py::test_local_ref_schema[True-main_schema1-other_schema_data1-instance1]",
"tests/acceptance/test_local_relative_ref.py::test_local_ref_schema[False-main_schema0-other_schema_data0-instance0]",
"tests/acceptance/test_local_relative_ref.py::test_local_ref_schema[False-main_schema1-other_schema_data1-instance1]",
"tests/acceptance/test_local_relative_ref.py::test_local_ref_schema_failure_case[True-main_schema0-other_schema_data0-instance0-None]",
"tests/acceptance/test_local_relative_ref.py::test_local_ref_schema_failure_case[True-main_schema1-other_schema_data1-instance1-{'foo':",
"tests/acceptance/test_local_relative_ref.py::test_local_ref_schema_failure_case[False-main_schema0-other_schema_data0-instance0-None]",
"tests/acceptance/test_local_relative_ref.py::test_local_ref_schema_failure_case[False-main_schema1-other_schema_data1-instance1-{'foo':",
"tests/acceptance/test_malformed_instances.py::test_non_json_instance",
"tests/acceptance/test_malformed_instances.py::test_non_json_instance_mixed_with_valid_data[TEXT]",
"tests/acceptance/test_malformed_instances.py::test_non_json_instance_mixed_with_valid_data[JSON]",
"tests/acceptance/test_malformed_instances.py::test_non_json_instance_mixed_with_valid_and_invalid_data[TEXT]",
"tests/acceptance/test_malformed_instances.py::test_non_json_instance_mixed_with_valid_and_invalid_data[JSON]",
"tests/acceptance/test_nonjson_schema_handling.py::test_warning_on_yaml_reference_passes[True]",
"tests/acceptance/test_nonjson_schema_handling.py::test_warning_on_yaml_reference_passes[False]",
"tests/acceptance/test_nonjson_schema_handling.py::test_warning_on_json5_reference[True]",
"tests/acceptance/test_nonjson_schema_handling.py::test_warning_on_json5_reference[False]",
"tests/acceptance/custom_schemas/test_github_workflow_require_explicit_timeout.py::test_github_require_timeouts_passing[github-workflows-github-workflows-require-timeout]",
"tests/acceptance/custom_schemas/test_github_workflow_require_explicit_timeout.py::test_github_require_timeouts_passing[github-workflows-custom.github-workflows-require-timeout]",
"tests/acceptance/custom_schemas/test_github_workflow_require_explicit_timeout.py::test_github_require_timeouts_passing[vendor.github-workflows-github-workflows-require-timeout]",
"tests/acceptance/custom_schemas/test_github_workflow_require_explicit_timeout.py::test_github_require_timeouts_passing[vendor.github-workflows-custom.github-workflows-require-timeout]",
"tests/acceptance/custom_schemas/test_github_workflow_require_explicit_timeout.py::test_github_require_timeouts_failing[github-workflows-github-workflows-require-timeout]",
"tests/acceptance/custom_schemas/test_github_workflow_require_explicit_timeout.py::test_github_require_timeouts_failing[github-workflows-custom.github-workflows-require-timeout]",
"tests/acceptance/custom_schemas/test_github_workflow_require_explicit_timeout.py::test_github_require_timeouts_failing[vendor.github-workflows-github-workflows-require-timeout]",
"tests/acceptance/custom_schemas/test_github_workflow_require_explicit_timeout.py::test_github_require_timeouts_failing[vendor.github-workflows-custom.github-workflows-require-timeout]",
"tests/unit/test_cachedownloader.py::test_default_filename_from_uri",
"tests/unit/test_cachedownloader.py::test_default_cache_dir[Windows-fakeenv0-None]",
"tests/unit/test_cachedownloader.py::test_default_cache_dir[Windows-fakeenv1-localappdata]",
"tests/unit/test_cachedownloader.py::test_default_cache_dir[Windows-fakeenv2-localappdata]",
"tests/unit/test_cachedownloader.py::test_default_cache_dir[Windows-fakeenv3-appdata]",
"tests/unit/test_cachedownloader.py::test_default_cache_dir[Darwin-fakeenv4-<expanduser>]",
"tests/unit/test_cachedownloader.py::test_default_cache_dir[Linux-fakeenv5-<expanduser>]",
"tests/unit/test_cachedownloader.py::test_default_cache_dir[Linux-fakeenv6-xdg-cache]",
"tests/unit/test_cachedownloader.py::test_cache_hit_by_mtime",
"tests/unit/test_cachedownloader.py::test_cachedownloader_cached_file",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[0-filename]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[0-filename_otherdir]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[0-cache_dir]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[0-disable_cache]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[1-filename]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[1-filename_otherdir]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[1-cache_dir]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[1-disable_cache]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[10-filename]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[10-filename_otherdir]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[10-cache_dir]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[10-disable_cache]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[ConnectionError-filename]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[ConnectionError-filename_otherdir]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[ConnectionError-cache_dir]",
"tests/unit/test_cachedownloader.py::test_cachedownloader_e2e[ConnectionError-disable_cache]",
"tests/unit/test_catalog.py::test_schema_catalog_is_alphabetized",
"tests/unit/test_catalog.py::test_hooks_cover_catalog",
"tests/unit/test_cli_parse.py::test_parse_result_set_schema[foo.json-None-False-SchemaLoadingMode.filepath]",
"tests/unit/test_cli_parse.py::test_parse_result_set_schema[None-foo-False-SchemaLoadingMode.builtin]",
"tests/unit/test_cli_parse.py::test_parse_result_set_schema[None-None-True-SchemaLoadingMode.metaschema]",
"tests/unit/test_cli_parse.py::test_requires_some_args",
"tests/unit/test_cli_parse.py::test_schemafile_and_instancefile",
"tests/unit/test_cli_parse.py::test_requires_at_least_one_instancefile",
"tests/unit/test_cli_parse.py::test_requires_schemafile",
"tests/unit/test_cli_parse.py::test_no_cache_defaults_false",
"tests/unit/test_cli_parse.py::test_no_cache_flag_is_true",
"tests/unit/test_cli_parse.py::test_mutex_schema_opts[cmd_args0]",
"tests/unit/test_cli_parse.py::test_mutex_schema_opts[cmd_args1]",
"tests/unit/test_cli_parse.py::test_mutex_schema_opts[cmd_args2]",
"tests/unit/test_cli_parse.py::test_mutex_schema_opts[cmd_args3]",
"tests/unit/test_cli_parse.py::test_supports_common_option[cmd_args0]",
"tests/unit/test_cli_parse.py::test_supports_common_option[cmd_args1]",
"tests/unit/test_cli_parse.py::test_supports_common_option[cmd_args2]",
"tests/unit/test_cli_parse.py::test_no_color_env_var[None-None]",
"tests/unit/test_cli_parse.py::test_no_color_env_var[1-False]",
"tests/unit/test_cli_parse.py::test_no_color_env_var[0-False]",
"tests/unit/test_gitlab_data_transform.py::test_can_parse_yaml_with_transform",
"tests/unit/test_gitlab_data_transform.py::test_can_parse_ok_gitlab_yaml_with_transform",
"tests/unit/test_gitlab_data_transform.py::test_cannot_parse_bad_gitlab_yaml_with_transform",
"tests/unit/test_instance_loader.py::test_instanceloader_json_data[foo.json-None]",
"tests/unit/test_instance_loader.py::test_instanceloader_json_data[foo.json-json]",
"tests/unit/test_instance_loader.py::test_instanceloader_json_data[foo.json-yaml]",
"tests/unit/test_instance_loader.py::test_instanceloader_json_data[foo-json]",
"tests/unit/test_instance_loader.py::test_instanceloader_json_data[foo-yaml]",
"tests/unit/test_instance_loader.py::test_instanceloader_yaml_data[foo.yaml-None]",
"tests/unit/test_instance_loader.py::test_instanceloader_yaml_data[foo.yml-None]",
"tests/unit/test_instance_loader.py::test_instanceloader_yaml_data[foo.yaml-json]",
"tests/unit/test_instance_loader.py::test_instanceloader_yaml_data[foo.yml-json]",
"tests/unit/test_instance_loader.py::test_instanceloader_yaml_data[foo.yaml-yaml]",
"tests/unit/test_instance_loader.py::test_instanceloader_yaml_data[foo.yml-yaml]",
"tests/unit/test_instance_loader.py::test_instanceloader_yaml_data[foo-yaml]",
"tests/unit/test_instance_loader.py::test_instanceloader_unknown_type",
"tests/unit/test_instance_loader.py::test_instanceloader_optional_format_handling[False-json5-{}-expect_data0-pip",
"tests/unit/test_instance_loader.py::test_instanceloader_optional_format_handling[True-toml-[foo]\\nbar",
"tests/unit/test_instance_loader.py::test_instanceloader_yaml_dup_anchor",
"tests/unit/test_instance_loader.py::test_instanceloader_invalid_data[json-foo.json-{\"a\":\\n]",
"tests/unit/test_instance_loader.py::test_instanceloader_invalid_data[yaml-foo.yaml-a:",
"tests/unit/test_instance_loader.py::test_instanceloader_invalid_data[toml-foo.toml-abc\\n]",
"tests/unit/test_instance_loader.py::test_instanceloader_invalid_data_mixed_with_valid_data",
"tests/unit/test_reporters.py::test_text_format_success[False-0]",
"tests/unit/test_reporters.py::test_text_format_success[False-1]",
"tests/unit/test_reporters.py::test_text_format_success[False-2]",
"tests/unit/test_reporters.py::test_text_format_success[True-0]",
"tests/unit/test_reporters.py::test_text_format_success[True-1]",
"tests/unit/test_reporters.py::test_text_format_success[True-2]",
"tests/unit/test_reporters.py::test_json_format_success[False-0]",
"tests/unit/test_reporters.py::test_json_format_success[False-1]",
"tests/unit/test_reporters.py::test_json_format_success[True-0]",
"tests/unit/test_reporters.py::test_json_format_success[True-1]",
"tests/unit/test_reporters.py::test_text_format_validation_error_message_simple",
"tests/unit/test_reporters.py::test_text_print_validation_error_nested[0]",
"tests/unit/test_reporters.py::test_text_print_validation_error_nested[1]",
"tests/unit/test_reporters.py::test_text_print_validation_error_nested[2]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[0-True]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[0-False]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[1-True]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[1-False]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[2-True]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[2-False]",
"tests/unit/test_schema_loader.py::test_schemaloader_path_handling_relative_local_path[schema.json]",
"tests/unit/test_schema_loader.py::test_schemaloader_path_handling_relative_local_path[schema.yaml]",
"tests/unit/test_schema_loader.py::test_schemaloader_local_yaml_data[schema.yaml]",
"tests/unit/test_schema_loader.py::test_schemaloader_local_yaml_data[schema.yml]",
"tests/unit/test_schema_loader.py::test_schemaloader_remote_path[https://foo.example.com/schema.json]",
"tests/unit/test_schema_loader.py::test_schemaloader_remote_path[http://foo.example.com/schema.json]",
"tests/unit/test_schema_loader.py::test_schemaloader_local_yaml_dup_anchor",
"tests/unit/test_schema_loader.py::test_schemaloader_invalid_yaml_data"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-22 20:03:38+00:00
|
apache-2.0
| 5,072 |
|
python-jsonschema__check-jsonschema-215
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index df28630..c7b5594 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -11,6 +11,9 @@ Unreleased
.. vendor-insert-here
- Update vendored schemas (2023-01-02)
+- Add ``--fill-defaults`` argument which eagerly populates ``"default"``
+ values whenever they are encountered and a value is not already present
+ (:issue:`200`)
0.19.2
------
diff --git a/docs/usage.rst b/docs/usage.rst
index 7c84b71..d114ced 100644
--- a/docs/usage.rst
+++ b/docs/usage.rst
@@ -152,6 +152,22 @@ checked. The following transforms are supported:
interpret ``!reference`` usages -- it only expands them to lists of strings
to pass schema validation
+``--fill-defaults``
+-------------------
+
+JSON Schema specifies the ``"default"`` keyword as potentially meaningful for
+consumers of schemas, but not for validators. Therefore, the default behavior
+for ``check-jsonschema`` is to ignore ``"default"``.
+
+``--fill-defaults`` changes this behavior, filling in ``"default"`` values
+whenever they are encountered prior to validation.
+
+.. warning::
+
+ There are many schemas which make the meaning of ``"default"`` unclear.
+ In particular, the behavior of ``check-jsonschema`` is undefined when multiple
+ defaults are specified via ``anyOf``, ``oneOf``, or other forms of polymorphism.
+
"format" Validation Options
---------------------------
diff --git a/src/check_jsonschema/checker.py b/src/check_jsonschema/checker.py
index c8cf007..1ecb9c8 100644
--- a/src/check_jsonschema/checker.py
+++ b/src/check_jsonschema/checker.py
@@ -29,6 +29,7 @@ class SchemaChecker:
*,
format_opts: FormatOptions | None = None,
traceback_mode: str = "short",
+ fill_defaults: bool = False,
):
self._schema_loader = schema_loader
self._instance_loader = instance_loader
@@ -36,6 +37,7 @@ class SchemaChecker:
self._format_opts = format_opts if format_opts is not None else FormatOptions()
self._traceback_mode = traceback_mode
+ self._fill_defaults = fill_defaults
def _fail(self, msg: str, err: Exception | None = None) -> t.NoReturn:
click.echo(msg, err=True)
@@ -47,7 +49,9 @@ class SchemaChecker:
self, path: pathlib.Path, doc: dict[str, t.Any]
) -> jsonschema.Validator:
try:
- return self._schema_loader.get_validator(path, doc, self._format_opts)
+ return self._schema_loader.get_validator(
+ path, doc, self._format_opts, self._fill_defaults
+ )
except SchemaParseError as e:
self._fail("Error: schemafile could not be parsed as JSON", e)
except jsonschema.SchemaError as e:
diff --git a/src/check_jsonschema/cli.py b/src/check_jsonschema/cli.py
index 61f384a..ebfff6b 100644
--- a/src/check_jsonschema/cli.py
+++ b/src/check_jsonschema/cli.py
@@ -52,6 +52,8 @@ class ParseResult:
self.default_filetype: str = "json"
# data-transform (for Azure Pipelines and potentially future transforms)
self.data_transform: Transform | None = None
+ # fill default values on instances during validation
+ self.fill_defaults: bool = False
# regex format options
self.disable_format: bool = False
self.format_regex: RegexFormatBehavior = RegexFormatBehavior.default
@@ -197,6 +199,11 @@ The '--builtin-schema' flag supports the following schema names:
),
type=click.Choice(tuple(TRANSFORM_LIBRARY.keys())),
)
[email protected](
+ "--fill-defaults",
+ help="Autofill 'default' values prior to validation.",
+ is_flag=True,
+)
@click.option(
"-o",
"--output-format",
@@ -234,6 +241,7 @@ def main(
default_filetype: str,
traceback_mode: str,
data_transform: str | None,
+ fill_defaults: bool,
output_format: str,
verbose: int,
quiet: int,
@@ -249,6 +257,7 @@ def main(
args.format_regex = RegexFormatBehavior(format_regex)
args.disable_cache = no_cache
args.default_filetype = default_filetype
+ args.fill_defaults = fill_defaults
if cache_filename is not None:
args.cache_filename = cache_filename
if data_transform is not None:
@@ -304,6 +313,7 @@ def build_checker(args: ParseResult) -> SchemaChecker:
reporter,
format_opts=args.format_opts,
traceback_mode=args.traceback_mode,
+ fill_defaults=args.fill_defaults,
)
diff --git a/src/check_jsonschema/schema_loader/main.py b/src/check_jsonschema/schema_loader/main.py
index b40e83d..3e1cae2 100644
--- a/src/check_jsonschema/schema_loader/main.py
+++ b/src/check_jsonschema/schema_loader/main.py
@@ -15,12 +15,41 @@ from .readers import HttpSchemaReader, LocalSchemaReader
from .resolver import make_ref_resolver
+def _extend_with_default(
+ validator_class: type[jsonschema.Validator],
+) -> type[jsonschema.Validator]:
+ validate_properties = validator_class.VALIDATORS["properties"]
+
+ def set_defaults_then_validate(
+ validator: jsonschema.Validator,
+ properties: dict[str, dict[str, t.Any]],
+ instance: dict[str, t.Any],
+ schema: dict[str, t.Any],
+ ) -> t.Iterator[jsonschema.ValidationError]:
+ for property_name, subschema in properties.items():
+ if "default" in subschema and property_name not in instance:
+ instance[property_name] = subschema["default"]
+
+ yield from validate_properties(
+ validator,
+ properties,
+ instance,
+ schema,
+ )
+
+ return jsonschema.validators.extend(
+ validator_class,
+ {"properties": set_defaults_then_validate},
+ )
+
+
class SchemaLoaderBase:
def get_validator(
self,
path: pathlib.Path,
instance_doc: dict[str, t.Any],
format_opts: FormatOptions,
+ fill_defaults: bool,
) -> jsonschema.Validator:
raise NotImplementedError
@@ -76,7 +105,9 @@ class SchemaLoader(SchemaLoaderBase):
def get_schema(self) -> dict[str, t.Any]:
return self.reader.read_schema()
- def make_validator(self, format_opts: FormatOptions) -> jsonschema.Validator:
+ def make_validator(
+ self, format_opts: FormatOptions, fill_defaults: bool
+ ) -> jsonschema.Validator:
schema_uri = self.get_schema_ref_base()
schema = self.get_schema()
@@ -95,6 +126,10 @@ class SchemaLoader(SchemaLoaderBase):
validator_cls = jsonschema.validators.validator_for(schema)
validator_cls.check_schema(schema)
+ # extend the validator class with default-filling behavior if appropriate
+ if fill_defaults:
+ validator_cls = _extend_with_default(validator_cls)
+
# now that we know it's safe to try to create the validator instance, do it
validator = validator_cls(
schema,
@@ -108,8 +143,9 @@ class SchemaLoader(SchemaLoaderBase):
path: pathlib.Path,
instance_doc: dict[str, t.Any],
format_opts: FormatOptions,
+ fill_defaults: bool,
) -> jsonschema.Validator:
- self._validator = self.make_validator(format_opts)
+ self._validator = self.make_validator(format_opts, fill_defaults)
return self._validator
@@ -130,6 +166,7 @@ class MetaSchemaLoader(SchemaLoaderBase):
path: pathlib.Path,
instance_doc: dict[str, t.Any],
format_opts: FormatOptions,
+ fill_defaults: bool,
) -> jsonschema.Validator:
validator = jsonschema.validators.validator_for(instance_doc)
return t.cast(jsonschema.Validator, validator(validator.META_SCHEMA))
|
python-jsonschema/check-jsonschema
|
67790e8fe5ccc6dd7936e02226ff83edad5d1a30
|
diff --git a/tests/acceptance/test_fill_defaults.py b/tests/acceptance/test_fill_defaults.py
new file mode 100644
index 0000000..5d96302
--- /dev/null
+++ b/tests/acceptance/test_fill_defaults.py
@@ -0,0 +1,82 @@
+import json
+
+SCHEMA = {
+ "$schema": "http://json-schema.org/draft-07/schema",
+ "properties": {
+ "title": {
+ "type": "string",
+ "default": "Untitled",
+ },
+ },
+ "required": ["title"],
+}
+
+VALID_DOC = {
+ "title": "doc one",
+}
+
+INVALID_DOC = {"title": {"foo": "bar"}}
+
+MISSING_FIELD_DOC = {}
+
+
+def test_run_with_fill_defaults_does_not_make_valid_doc_invalid(
+ run_line_simple, tmp_path
+):
+ schemafile = tmp_path / "schema.json"
+ schemafile.write_text(json.dumps(SCHEMA))
+
+ doc = tmp_path / "instance.json"
+ doc.write_text(json.dumps(VALID_DOC))
+
+ run_line_simple(["--fill-defaults", "--schemafile", str(schemafile), str(doc)])
+
+
+def test_run_with_fill_defaults_does_not_make_invalid_doc_valid(run_line, tmp_path):
+ schemafile = tmp_path / "schema.json"
+ schemafile.write_text(json.dumps(SCHEMA))
+
+ doc = tmp_path / "instance.json"
+ doc.write_text(json.dumps(INVALID_DOC))
+
+ res = run_line(
+ [
+ "check-jsonschema",
+ "--fill-defaults",
+ "--schemafile",
+ str(schemafile),
+ str(doc),
+ ]
+ )
+ assert res.exit_code == 1
+
+
+def test_run_with_fill_defaults_adds_required_field(run_line, tmp_path):
+ schemafile = tmp_path / "schema.json"
+ schemafile.write_text(json.dumps(SCHEMA))
+
+ doc = tmp_path / "instance.json"
+ doc.write_text(json.dumps(MISSING_FIELD_DOC))
+
+ # step 1: run without '--fill-defaults' and confirm failure
+ result_without_fill_defaults = run_line(
+ [
+ "check-jsonschema",
+ "--schemafile",
+ str(schemafile),
+ str(doc),
+ ]
+ )
+ assert result_without_fill_defaults.exit_code == 1
+
+ # step 2: run with '--fill-defaults' and confirm success
+ result_with_fill_defaults = run_line(
+ [
+ "check-jsonschema",
+ "--fill-defaults",
+ "--schemafile",
+ str(schemafile),
+ str(doc),
+ ]
+ )
+ assert result_with_fill_defaults.exit_code == 0
|
pre-populate default values from schema (command-line option)
Hi,
I think it would be very useful for validating json documents against schemas a command-line option that would allow to pre-populate defaults into the document like python-jsonshema docs suggest here:
https://python-jsonschema.readthedocs.io/en/stable/faq/#why-doesn-t-my-schema-s-default-property-set-the-default-on-my-instance
It would make easy to validate documents like it is suggested just from the command-line tool
|
0.0
|
67790e8fe5ccc6dd7936e02226ff83edad5d1a30
|
[
"tests/acceptance/test_fill_defaults.py::test_run_with_fill_defaults_does_not_make_valid_doc_invalid",
"tests/acceptance/test_fill_defaults.py::test_run_with_fill_defaults_does_not_make_invalid_doc_valid",
"tests/acceptance/test_fill_defaults.py::test_run_with_fill_defaults_adds_required_field"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-01-02 22:52:14+00:00
|
apache-2.0
| 5,073 |
|
python-jsonschema__check-jsonschema-295
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index a8df1f5..0214083 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -20,6 +20,9 @@ Unreleased
non-JSON format supported by `check-jsonschema`. The file type is inferred
only from the file extension in these cases and defaults to JSON if there is
no recognizable extension.
+- Remote schemafiles (http/s) now support YAML, TOML, and JSON5 formats, if the
+ URL ends with the appropriate extension and the matching parser is available.
+ Extensionless URLs are treated as JSON.
0.23.3
------
diff --git a/src/check_jsonschema/checker.py b/src/check_jsonschema/checker.py
index bf1aea0..28931d5 100644
--- a/src/check_jsonschema/checker.py
+++ b/src/check_jsonschema/checker.py
@@ -48,7 +48,7 @@ class SchemaChecker:
def get_validator(
self, path: pathlib.Path, doc: dict[str, t.Any]
- ) -> jsonschema.Validator:
+ ) -> jsonschema.protocols.Validator:
try:
return self._schema_loader.get_validator(
path, doc, self._format_opts, self._fill_defaults
diff --git a/src/check_jsonschema/schema_loader/main.py b/src/check_jsonschema/schema_loader/main.py
index c8c9045..4fa1c57 100644
--- a/src/check_jsonschema/schema_loader/main.py
+++ b/src/check_jsonschema/schema_loader/main.py
@@ -17,7 +17,7 @@ from .resolver import make_reference_registry
def _extend_with_default(
- validator_class: type[jsonschema.Validator],
+ validator_class: type[jsonschema.protocols.Validator],
) -> type[jsonschema.Validator]:
validate_properties = validator_class.VALIDATORS["properties"]
@@ -51,7 +51,7 @@ class SchemaLoaderBase:
instance_doc: dict[str, t.Any],
format_opts: FormatOptions,
fill_defaults: bool,
- ) -> jsonschema.Validator:
+ ) -> jsonschema.protocols.Validator:
raise NotImplementedError
@@ -112,7 +112,7 @@ class SchemaLoader(SchemaLoaderBase):
instance_doc: dict[str, t.Any],
format_opts: FormatOptions,
fill_defaults: bool,
- ) -> jsonschema.Validator:
+ ) -> jsonschema.protocols.Validator:
retrieval_uri = self.get_schema_retrieval_uri()
schema = self.get_schema()
@@ -141,7 +141,7 @@ class SchemaLoader(SchemaLoaderBase):
registry=reference_registry,
format_checker=format_checker,
)
- return t.cast(jsonschema.Validator, validator)
+ return t.cast(jsonschema.protocols.Validator, validator)
class BuiltinSchemaLoader(SchemaLoader):
@@ -163,7 +163,7 @@ class MetaSchemaLoader(SchemaLoaderBase):
instance_doc: dict[str, t.Any],
format_opts: FormatOptions,
fill_defaults: bool,
- ) -> jsonschema.Validator:
+ ) -> jsonschema.protocols.Validator:
schema_validator = jsonschema.validators.validator_for(instance_doc)
meta_validator_class = jsonschema.validators.validator_for(
schema_validator.META_SCHEMA, default=schema_validator
diff --git a/src/check_jsonschema/schema_loader/readers.py b/src/check_jsonschema/schema_loader/readers.py
index c2e4697..4c362dc 100644
--- a/src/check_jsonschema/schema_loader/readers.py
+++ b/src/check_jsonschema/schema_loader/readers.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-import json
+import io
import typing as t
import ruamel.yaml
@@ -48,19 +48,28 @@ class HttpSchemaReader:
disable_cache: bool,
) -> None:
self.url = url
+ self.parsers = ParserSet()
self.downloader = CacheDownloader(
url,
cache_filename,
disable_cache=disable_cache,
- validation_callback=json.loads,
+ validation_callback=self._parse,
)
+ self._parsed_schema: t.Any | None = None
+
+ def _parse(self, schema_bytes: bytes) -> t.Any:
+ if self._parsed_schema is None:
+ self._parsed_schema = self.parsers.parse_data_with_path(
+ io.BytesIO(schema_bytes), self.url, default_filetype="json"
+ )
+ return self._parsed_schema
def get_retrieval_uri(self) -> str:
return self.url
def _read_impl(self) -> t.Any:
with self.downloader.open() as fp:
- return json.load(fp)
+ return self._parse(fp.read())
def read_schema(self) -> dict:
return _run_load_callback(self.url, self._read_impl)
|
python-jsonschema/check-jsonschema
|
76b19fe93f7330dcf8892eea937dd351934a2ffa
|
diff --git a/tests/unit/test_schema_loader.py b/tests/unit/test_schema_loader.py
index b6938cb..ddc487f 100644
--- a/tests/unit/test_schema_loader.py
+++ b/tests/unit/test_schema_loader.py
@@ -2,6 +2,7 @@ import os
import pathlib
import pytest
+import responses
from check_jsonschema.schema_loader import SchemaLoader, SchemaParseError
from check_jsonschema.schema_loader.readers import HttpSchemaReader, LocalSchemaReader
@@ -40,12 +41,12 @@ def test_schemaloader_path_handling_relative_local_path(in_tmp_dir, filename):
[
"schema.yaml",
"schema.yml",
+ "https://foo.example.com/schema.yaml",
+ "https://foo.example.com/schema.yml",
],
)
-def test_schemaloader_local_yaml_data(tmp_path, filename):
- f = tmp_path / filename
- f.write_text(
- """
+def test_schemaloader_yaml_data(tmp_path, filename):
+ schema_text = """
---
"$schema": https://json-schema.org/draft/2020-12/schema
type: object
@@ -60,8 +61,14 @@ properties:
c:
type: string
"""
- )
- sl = SchemaLoader(str(f))
+ if filename.startswith("http"):
+ responses.add("GET", filename, body=schema_text)
+ path = filename
+ else:
+ f = tmp_path / filename
+ f.write_text(schema_text)
+ path = str(f)
+ sl = SchemaLoader(path)
schema = sl.get_schema()
assert schema == {
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
FailedDownloadError
In order to check files in config/*.yaml I am using:
```
- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.23.3
hooks:
- id: check-github-workflows
- id: check-jsonschema
name: Check test configs
files: ^config/[^/]+$
types: [yaml]
args: ["--schemafile", "https://raw.githubusercontent.com/EVerest/everest-framework/main/schemas/config.yaml"]
```
But it fails with:
```
Check test configs.......................................................Failed
- hook id: check-jsonschema
- duration: 0.56s
- exit code: 1
Error: Unexpected Error building schema validator
FailedDownloadError: got responses with status=200, retries exhausted
in "/Users/hendry/.cache/pre-commit/repoircq8841/py_env-python3.10/lib/python3.10/site-packages/check_jsonschema/checker.py", line 52
>>> return self._schema_loader.get_validator(
make: *** [run] Error 1
```
I don't understand why it fails with status 200 success?
|
0.0
|
76b19fe93f7330dcf8892eea937dd351934a2ffa
|
[
"tests/unit/test_schema_loader.py::test_schemaloader_yaml_data[https://foo.example.com/schema.yaml]",
"tests/unit/test_schema_loader.py::test_schemaloader_yaml_data[https://foo.example.com/schema.yml]"
] |
[
"tests/unit/test_schema_loader.py::test_schemaloader_path_handling_relative_local_path[schema.json]",
"tests/unit/test_schema_loader.py::test_schemaloader_path_handling_relative_local_path[schema.yaml]",
"tests/unit/test_schema_loader.py::test_schemaloader_yaml_data[schema.yaml]",
"tests/unit/test_schema_loader.py::test_schemaloader_yaml_data[schema.yml]",
"tests/unit/test_schema_loader.py::test_schemaloader_remote_path[https://foo.example.com/schema.json]",
"tests/unit/test_schema_loader.py::test_schemaloader_remote_path[http://foo.example.com/schema.json]",
"tests/unit/test_schema_loader.py::test_schemaloader_local_yaml_dup_anchor",
"tests/unit/test_schema_loader.py::test_schemaloader_invalid_yaml_data"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-08 16:29:26+00:00
|
apache-2.0
| 5,074 |
|
python-jsonschema__check-jsonschema-313
|
diff --git a/.github/workflows/publish_to_pypi.yaml b/.github/workflows/publish_to_pypi.yaml
index 1177fff..8872066 100644
--- a/.github/workflows/publish_to_pypi.yaml
+++ b/.github/workflows/publish_to_pypi.yaml
@@ -57,4 +57,4 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
- run: gh release upload "${{ github.ref }}" dist/*
+ run: gh release upload "${{ github.ref_name }}" dist/*
diff --git a/src/check_jsonschema/checker.py b/src/check_jsonschema/checker.py
index 28931d5..daa4f85 100644
--- a/src/check_jsonschema/checker.py
+++ b/src/check_jsonschema/checker.py
@@ -71,6 +71,8 @@ class SchemaChecker:
validator = self.get_validator(path, data)
for err in validator.iter_errors(data):
result.record_validation_error(path, err)
+ else:
+ result.record_validation_success(path)
return result
def _run(self) -> None:
diff --git a/src/check_jsonschema/reporter.py b/src/check_jsonschema/reporter.py
index 3303ae1..453dd9d 100644
--- a/src/check_jsonschema/reporter.py
+++ b/src/check_jsonschema/reporter.py
@@ -24,7 +24,7 @@ class Reporter(abc.ABC):
super().__init__(**kwargs)
@abc.abstractmethod
- def report_success(self) -> None:
+ def report_success(self, result: CheckResult) -> None:
raise NotImplementedError
@abc.abstractmethod
@@ -33,7 +33,7 @@ class Reporter(abc.ABC):
def report_result(self, result: CheckResult) -> None:
if result.success:
- self.report_success()
+ self.report_success(result)
else:
self.report_errors(result)
@@ -51,11 +51,15 @@ class TextReporter(Reporter):
def _echo(self, s: str, *, indent: int = 0) -> None:
click.echo(" " * indent + s, file=self.stream)
- def report_success(self) -> None:
+ def report_success(self, result: CheckResult) -> None:
if self.verbosity < 1:
return
ok = click.style("ok", fg="green")
self._echo(f"{ok} -- validation done")
+ if self.verbosity > 1:
+ self._echo("The following files were checked:")
+ for filename in result.successes:
+ self._echo(f" {filename}")
def _format_validation_error_message(
self, err: jsonschema.ValidationError, filename: str | None = None
@@ -140,10 +144,12 @@ class JsonReporter(Reporter):
else:
click.echo(json.dumps(data, separators=(",", ":")))
- def report_success(self) -> None:
+ def report_success(self, result: CheckResult) -> None:
report_obj: dict[str, t.Any] = {"status": "ok"}
if self.verbosity > 0:
report_obj["errors"] = []
+ if self.verbosity > 1:
+ report_obj["checked_paths"] = list(result.successes)
self._dump(report_obj)
def _dump_error_map(
@@ -192,6 +198,8 @@ class JsonReporter(Reporter):
def report_errors(self, result: CheckResult) -> None:
report_obj: dict[str, t.Any] = {"status": "fail"}
+ if self.verbosity > 1:
+ report_obj["checked_paths"] = list(result.successes)
if self.verbosity > 0:
report_obj["errors"] = list(self._dump_error_map(result.validation_errors))
report_obj["parse_errors"] = list(
diff --git a/src/check_jsonschema/result.py b/src/check_jsonschema/result.py
index 31a021c..0ac651a 100644
--- a/src/check_jsonschema/result.py
+++ b/src/check_jsonschema/result.py
@@ -9,11 +9,15 @@ class CheckResult:
def __init__(self) -> None:
self.validation_errors: dict[str, list[jsonschema.ValidationError]] = {}
self.parse_errors: dict[str, list[ParseError]] = {}
+ self.successes: list[str] = []
@property
def success(self) -> bool:
return not (bool(self.parse_errors) or bool(self.validation_errors))
+ def record_validation_success(self, path: pathlib.Path) -> None:
+ self.successes.append(str(path))
+
def record_validation_error(
self, path: pathlib.Path, err: jsonschema.ValidationError
) -> None:
|
python-jsonschema/check-jsonschema
|
8e208edf3ab4c4c5dbaa826161c1136b83cd2672
|
diff --git a/tests/unit/test_reporters.py b/tests/unit/test_reporters.py
index cdeef35..b02fed7 100644
--- a/tests/unit/test_reporters.py
+++ b/tests/unit/test_reporters.py
@@ -1,4 +1,5 @@
import json
+import textwrap
import pytest
from jsonschema import Draft7Validator
@@ -8,7 +9,9 @@ from check_jsonschema.result import CheckResult
def _make_success_result():
- return CheckResult()
+ res = CheckResult()
+ res.successes.append("foo.json")
+ return res
@pytest.mark.parametrize("verbosity", (0, 1, 2))
@@ -18,29 +21,41 @@ def test_text_format_success(capsys, verbosity, use_report_result_path):
if use_report_result_path:
reporter.report_result(_make_success_result())
else:
- reporter.report_success()
+ reporter.report_success(_make_success_result())
captured = capsys.readouterr()
assert captured.err == ""
if verbosity == 0:
assert captured.out == ""
- else:
+ elif verbosity == 1:
assert captured.out == "ok -- validation done\n"
+ else:
+ assert captured.out == textwrap.dedent(
+ """\
+ ok -- validation done
+ The following files were checked:
+ foo.json
+ """
+ )
[email protected]("verbosity", (0, 1))
[email protected]("verbosity", (0, 1, 2))
@pytest.mark.parametrize("use_report_result_path", (False, True))
def test_json_format_success(capsys, verbosity, use_report_result_path):
reporter = JsonReporter(verbosity=verbosity, pretty=False)
if use_report_result_path:
reporter.report_result(_make_success_result())
else:
- reporter.report_success()
+ reporter.report_success(_make_success_result())
captured = capsys.readouterr()
assert captured.err == ""
if verbosity == 0:
assert captured.out == '{"status":"ok"}\n'
- else:
+ elif verbosity == 1:
assert captured.out == '{"status":"ok","errors":[]}\n'
+ else:
+ assert (
+ captured.out == '{"status":"ok","errors":[],"checked_paths":["foo.json"]}\n'
+ )
def test_text_format_validation_error_message_simple():
|
Output of all validated files if verbose: true
I would love to see in the output a list of those files that been picked up by your tool and validated.
Maybe it's already possible. I am a new user.
|
0.0
|
8e208edf3ab4c4c5dbaa826161c1136b83cd2672
|
[
"tests/unit/test_reporters.py::test_text_format_success[False-0]",
"tests/unit/test_reporters.py::test_text_format_success[False-1]",
"tests/unit/test_reporters.py::test_text_format_success[False-2]",
"tests/unit/test_reporters.py::test_text_format_success[True-0]",
"tests/unit/test_reporters.py::test_text_format_success[True-1]",
"tests/unit/test_reporters.py::test_text_format_success[True-2]",
"tests/unit/test_reporters.py::test_json_format_success[False-0]",
"tests/unit/test_reporters.py::test_json_format_success[False-1]",
"tests/unit/test_reporters.py::test_json_format_success[False-2]",
"tests/unit/test_reporters.py::test_json_format_success[True-0]",
"tests/unit/test_reporters.py::test_json_format_success[True-1]",
"tests/unit/test_reporters.py::test_json_format_success[True-2]"
] |
[
"tests/unit/test_reporters.py::test_text_format_validation_error_message_simple",
"tests/unit/test_reporters.py::test_text_print_validation_error_nested[0]",
"tests/unit/test_reporters.py::test_text_print_validation_error_nested[1]",
"tests/unit/test_reporters.py::test_text_print_validation_error_nested[2]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[0-True]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[0-False]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[1-True]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[1-False]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[2-True]",
"tests/unit/test_reporters.py::test_json_format_validation_error_nested[2-False]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-27 21:49:17+00:00
|
apache-2.0
| 5,075 |
|
python-jsonschema__check-jsonschema-356
|
diff --git a/src/check_jsonschema/builtin_schemas/custom/github-workflows-require-timeout.json b/src/check_jsonschema/builtin_schemas/custom/github-workflows-require-timeout.json
index 59f427a..7d92081 100644
--- a/src/check_jsonschema/builtin_schemas/custom/github-workflows-require-timeout.json
+++ b/src/check_jsonschema/builtin_schemas/custom/github-workflows-require-timeout.json
@@ -1,6 +1,13 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$comment": "A schema which requires that github workflow jobs define job timeouts",
+ "definitions": {
+ "expressionSyntax": {
+ "type": "string",
+ "$comment": "pattern definition taken from schemastore 'github-workflow.json'",
+ "pattern": "^\\$\\{\\{(.|[\r\n])*\\}\\}$"
+ }
+ },
"properties": {
"jobs": {
"$comment": "https://help.github.com/en/github/automating-your-workflow-with-github-actions/workflow-syntax-for-github-actions#jobs",
@@ -15,8 +22,15 @@
"timeout-minutes": {
"$comment": "https://help.github.com/en/actions/automating-your-workflow-with-github-actions/workflow-syntax-for-github-actions#jobsjob_idtimeout-minutes",
"description": "The maximum number of minutes to let a workflow run before GitHub automatically cancels it. Default: 360",
- "type": "number",
- "default": 360
+ "default": 360,
+ "oneOf": [
+ {
+ "type": "number"
+ },
+ {
+ "$ref": "#/definitions/expressionSyntax"
+ }
+ ]
}
},
"required": [
|
python-jsonschema/check-jsonschema
|
d655126247ec42b44a8161723871b943ec2bcd08
|
diff --git a/tests/acceptance/test_example_files.py b/tests/acceptance/test_example_files.py
index 3b23e2c..94980f8 100644
--- a/tests/acceptance/test_example_files.py
+++ b/tests/acceptance/test_example_files.py
@@ -64,7 +64,7 @@ def test_hook_positive_examples(case_name, run_line):
hook_id = POSITIVE_HOOK_CASES[case_name]
ret = run_line(HOOK_CONFIG[hook_id] + [rcase.path] + rcase.add_args)
- assert ret.exit_code == 0
+ assert ret.exit_code == 0, _format_cli_result(rcase, ret)
@pytest.mark.parametrize("case_name", NEGATIVE_HOOK_CASES.keys())
@@ -73,7 +73,7 @@ def test_hook_negative_examples(case_name, run_line):
hook_id = NEGATIVE_HOOK_CASES[case_name]
ret = run_line(HOOK_CONFIG[hook_id] + [rcase.path] + rcase.add_args)
- assert ret.exit_code == 1
+ assert ret.exit_code == 1, _format_cli_result(rcase, ret)
@pytest.mark.parametrize("case_name", _get_explicit_cases("positive"))
@@ -167,3 +167,13 @@ def _package_is_installed(pkg: str) -> bool:
if spec is None:
return False
return True
+
+
+def _format_cli_result(rcase: ResolvedCase, result) -> str:
+ return (
+ "\n"
+ f"config.add_args={rcase.add_args}\n"
+ f"{result.exit_code=}\n"
+ f"result.stdout={result.output}\n"
+ f"{result.stderr=}"
+ )
diff --git a/tests/example-files/hooks/negative/jsonschema/_config.yaml b/tests/example-files/hooks/negative/jsonschema/_config.yaml
new file mode 100644
index 0000000..68e9596
--- /dev/null
+++ b/tests/example-files/hooks/negative/jsonschema/_config.yaml
@@ -0,0 +1,3 @@
+files:
+ github-workflow-timeout-minutes-expression.yaml:
+ add_args: ["--builtin-schema", "custom.github-workflows-require-timeout"]
diff --git a/tests/example-files/hooks/negative/jsonschema/github-workflow-timeout-minutes-expression.yaml b/tests/example-files/hooks/negative/jsonschema/github-workflow-timeout-minutes-expression.yaml
new file mode 100644
index 0000000..3a7324a
--- /dev/null
+++ b/tests/example-files/hooks/negative/jsonschema/github-workflow-timeout-minutes-expression.yaml
@@ -0,0 +1,12 @@
+on:
+ workflow-call:
+ inputs:
+ qemu:
+ default: ''
+ required: false
+
+jobs:
+ job-id:
+ runs-on: ubuntu-latest
+ # missing trailing '}'
+ timeout-minutes: ${{ inputs.qemu && '60' || '20' }
diff --git a/tests/example-files/hooks/positive/jsonschema/_config.yaml b/tests/example-files/hooks/positive/jsonschema/_config.yaml
new file mode 100644
index 0000000..68e9596
--- /dev/null
+++ b/tests/example-files/hooks/positive/jsonschema/_config.yaml
@@ -0,0 +1,3 @@
+files:
+ github-workflow-timeout-minutes-expression.yaml:
+ add_args: ["--builtin-schema", "custom.github-workflows-require-timeout"]
diff --git a/tests/example-files/hooks/positive/jsonschema/github-workflow-timeout-minutes-expression.yaml b/tests/example-files/hooks/positive/jsonschema/github-workflow-timeout-minutes-expression.yaml
new file mode 100644
index 0000000..4b30a1c
--- /dev/null
+++ b/tests/example-files/hooks/positive/jsonschema/github-workflow-timeout-minutes-expression.yaml
@@ -0,0 +1,11 @@
+on:
+ workflow-call:
+ inputs:
+ qemu:
+ default: ''
+ required: false
+
+jobs:
+ job-id:
+ runs-on: ubuntu-latest
+ timeout-minutes: ${{ inputs.qemu && '60' || '20' }}
|
[BUG] `github-workflows-require-timeout.json`: `timeout-minutes` should allow expressions
$sbj. I want to have `timeout-minutes: ${{ inputs.qemu && '60' || '20' }}` set for a job. The `inputs` is a context that exists in reusable workflows. Here's the table of context availability FTR: https://docs.github.com/en/actions/learn-github-actions/contexts.
Here's how it fails for me:
```console
.github/workflows/reusable-build-wheel.yml::$.jobs.build-wheel: {'name': 'Build wheels on ${{ inputs.os }} ${{ inputs.qemu }}', 'runs-on': '${{ inputs.os }}-latest', 'timeout-minutes': '${{ inputs.qemu && 60 || 20 }}', 'steps': [{'name': 'Retrieve the project source from an sdist inside the GHA artifact', 'uses': 're-actors/checkout-python-sdist@release/v1', 'with': {'source-tarball-name': '${{ inputs.source-tarball-name }}', 'workflow-artifact-name': '${{ inputs.dists-artifact-name }}'}}, {'name': 'Set up QEMU', 'if': 'inputs.qemu', 'uses': 'docker/setup-qemu-action@v3', 'with': {'platforms': 'all'}, 'id': 'qemu'}, {'name': 'Prepare emulation', 'if': 'inputs.qemu', 'run': '# Build emulated architectures only if QEMU is set,\n# use default "auto" otherwise\necho "CIBW_ARCHS_LINUX=${{ inputs.qemu }}" >> "${GITHUB_ENV}"\n', 'shell': 'bash'}, {'name': 'Setup Python', 'uses': 'actions/setup-python@v4'}, {'name': 'Build wheels', 'uses': 'pypa/[email protected]', 'env': {'CIBW_ARCHS_MACOS': 'x86_64 arm64 universal2'}}, {'name': 'Upload built artifacts for testing and publishing', 'uses': 'actions/upload-artifact@v3', 'with': {'name': '${{ inputs.dists-artifact-name }}', 'path': './wheelhouse/*.whl'}}]} is not valid under any of the given schemas
Underlying errors caused this.
Best Match:
$.jobs.build-wheel: 'uses' is a required property
Best Deep Match:
$.jobs.build-wheel.timeout-minutes: '${{ inputs.qemu && 60 || 20 }}' is not of type 'number'
```
Approximate reusable workflow look:
```yaml
# partial file, specific bit that is failing
on:
workflow-call:
inputs:
...
qemu:
default: ''
...
required: false
...
...
...
jobs:
job-id:
...
timeout-minutes: ${{ inputs.qemu && '60' || '20' }}
...
```
Haven't looked into how to fix this, but the upstream [`github-workflow.json`](https://github.com/webknjaz/schemastore/blob/master/src/schemas/json/github-workflow.json) doesn't error out, so this custom schema must be too strict...
|
0.0
|
d655126247ec42b44a8161723871b943ec2bcd08
|
[
"tests/acceptance/test_example_files.py::test_hook_positive_examples[jsonschema/github-workflow-timeout-minutes-expression.yaml]"
] |
[
"tests/acceptance/test_example_files.py::test_hook_positive_examples[metaschema/2020_invalid_format_value.json]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[metaschema/almost_empty.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[metaschema/draft3.json]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[metaschema/draft7.json]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[azure-pipelines/expression-from-lang-server.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[azure-pipelines/expression-transform.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[azure-pipelines/object-defined-by-expression-map.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[azure-pipelines/marshmallow.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[bitbucket-pipelines/bitbucket-pipelines.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[buildkite/matrix.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[drone-ci/ssh-pipeline.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[drone-ci/exec-pipeline.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[drone-ci/kubernetes-pipeline.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[drone-ci/macstadium-pipeline.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[drone-ci/digitalocean-pipeline.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[drone-ci/docker-pipeline.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[github-actions/redis-simple.yml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[github-workflows/self-build.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[github-workflows/has-unicode.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[gitlab-ci/reference-tag.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[readthedocs/simple.yaml]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[renovate/starter-config.json]",
"tests/acceptance/test_example_files.py::test_hook_positive_examples[travis/python-build.yaml]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[jsonschema/github-workflow-timeout-minutes-expression.yaml]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[metaschema/draft7_title_array.json]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[metaschema/draft7_title_array.yaml]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[drone-ci/unkown-type-pipeline.yml]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[github-workflows/empty.json]",
"tests/acceptance/test_example_files.py::test_hook_negative_examples[readthedocs/pyversion-float.yml]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[complex-yaml]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[simple-toml]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[2020-meta]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[integer-keys-yaml]",
"tests/acceptance/test_example_files.py::test_explicit_positive_examples[complex-toml]"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-24 16:45:55+00:00
|
apache-2.0
| 5,076 |
|
python-lsp__python-lsp-server-321
|
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index aed5627..f2626e4 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -32,6 +32,7 @@ This server can be configured using the `workspace/didChangeConfiguration` metho
| `pylsp.plugins.jedi_definition.enabled` | `boolean` | Enable or disable the plugin. | `true` |
| `pylsp.plugins.jedi_definition.follow_imports` | `boolean` | The goto call will follow imports. | `true` |
| `pylsp.plugins.jedi_definition.follow_builtin_imports` | `boolean` | If follow_imports is True will decide if it follow builtin imports. | `true` |
+| `pylsp.plugins.jedi_definition.follow_builtin_definitions` | `boolean` | Follow builtin and extension definitions to stubs. | `true` |
| `pylsp.plugins.jedi_hover.enabled` | `boolean` | Enable or disable the plugin. | `true` |
| `pylsp.plugins.jedi_references.enabled` | `boolean` | Enable or disable the plugin. | `true` |
| `pylsp.plugins.jedi_signature_help.enabled` | `boolean` | Enable or disable the plugin. | `true` |
diff --git a/pylsp/config/schema.json b/pylsp/config/schema.json
index 7e23500..4ac085d 100644
--- a/pylsp/config/schema.json
+++ b/pylsp/config/schema.json
@@ -176,6 +176,11 @@
"default": true,
"description": "If follow_imports is True will decide if it follow builtin imports."
},
+ "pylsp.plugins.jedi_definition.follow_builtin_definitions": {
+ "type": "boolean",
+ "default": true,
+ "description": "Follow builtin and extension definitions to stubs."
+ },
"pylsp.plugins.jedi_hover.enabled": {
"type": "boolean",
"default": true,
diff --git a/pylsp/plugins/definition.py b/pylsp/plugins/definition.py
index bf707b7..b2110af 100644
--- a/pylsp/plugins/definition.py
+++ b/pylsp/plugins/definition.py
@@ -17,6 +17,7 @@ def pylsp_definitions(config, workspace, document, position):
follow_builtin_imports=settings.get('follow_builtin_imports', True),
**code_position)
+ follow_builtin_defns = settings.get("follow_builtin_definitions", True)
return [
{
'uri': uris.uri_with(document.uri, path=str(d.module_path)),
@@ -25,7 +26,7 @@ def pylsp_definitions(config, workspace, document, position):
'end': {'line': d.line - 1, 'character': d.column + len(d.name)},
}
}
- for d in definitions if d.is_definition() and _not_internal_definition(d)
+ for d in definitions if d.is_definition() and (follow_builtin_defns or _not_internal_definition(d))
]
diff --git a/pylsp/plugins/symbols.py b/pylsp/plugins/symbols.py
index 939dcda..d5925db 100644
--- a/pylsp/plugins/symbols.py
+++ b/pylsp/plugins/symbols.py
@@ -91,7 +91,7 @@ def pylsp_document_symbols(config, document):
else:
continue
- if _include_def(d) and Path(document.path) == d.module_path:
+ if _include_def(d) and Path(document.path) == Path(d.module_path):
tuple_range = _tuple_range(d)
if tuple_range in exclude:
continue
|
python-lsp/python-lsp-server
|
a79c171da640edc2f0a0c7025b05fd7c37f733c4
|
diff --git a/test/plugins/test_definitions.py b/test/plugins/test_definitions.py
index bcc7648..a8972cd 100644
--- a/test/plugins/test_definitions.py
+++ b/test/plugins/test_definitions.py
@@ -42,9 +42,24 @@ def test_builtin_definition(config, workspace):
# Over 'i' in dict
cursor_pos = {'line': 8, 'character': 24}
- # No go-to def for builtins
doc = Document(DOC_URI, workspace, DOC)
- assert not pylsp_definitions(config, workspace, doc, cursor_pos)
+ orig_settings = config.settings()
+
+ # Check definition for `dict` goes to `builtins.pyi::dict`
+ follow_defns_setting = {'follow_builtin_definitions': True}
+ settings = {'plugins': {'jedi_definition': follow_defns_setting}}
+ config.update(settings)
+ defns = pylsp_definitions(config, workspace, doc, cursor_pos)
+ assert len(defns) == 1
+ assert defns[0]["uri"].endswith("builtins.pyi")
+
+ # Check no definitions for `dict`
+ follow_defns_setting['follow_builtin_definitions'] = False
+ config.update(settings)
+ defns = pylsp_definitions(config, workspace, doc, cursor_pos)
+ assert not defns
+
+ config.update(orig_settings)
def test_assignment(config, workspace):
|
Is there a configuration option to enable jumping to builtin module stubs?
I'm using Jupyter Lab's `Jump to definition`, and PR https://github.com/palantir/python-language-server/pull/687 completely disables jumping to `📜extension_module.pyi` for the following package arrangement:
```
📂site-packages
┗━📂my_package
┣━📜__init__.py
┣━📦extension_module.so
┗━📜extension_module.pyi
```
Personally, I also find the behaviour in the PR (disabling jumping to the Python standard library builtins stubs) quite frustrating, as I frequently refer to the Python standard library's stubs.
I've temporarily disabled the behaviour by making the following change,
```python
# pylsp/plugins/definition.py
def _not_internal_definition(definition):
return True
```
but am wondering if there's been an update to exposing a configuration for them (preferably accessible in both JupyterLab and VSCode)?
|
0.0
|
a79c171da640edc2f0a0c7025b05fd7c37f733c4
|
[
"test/plugins/test_definitions.py::test_builtin_definition"
] |
[
"test/plugins/test_definitions.py::test_definitions",
"test/plugins/test_definitions.py::test_assignment",
"test/plugins/test_definitions.py::test_document_path_definitions"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-27 21:00:56+00:00
|
mit
| 5,077 |
|
python-lsp__python-lsp-server-454
|
diff --git a/pylsp/python_lsp.py b/pylsp/python_lsp.py
index 3eeb2f7..e2b541d 100644
--- a/pylsp/python_lsp.py
+++ b/pylsp/python_lsp.py
@@ -295,7 +295,7 @@ class PythonLSPServer(MethodDispatcher):
"openClose": True,
},
"notebookDocumentSync": {
- "notebookSelector": {"cells": [{"language": "python"}]}
+ "notebookSelector": [{"cells": [{"language": "python"}]}]
},
"workspace": {
"workspaceFolders": {"supported": True, "changeNotifications": True}
|
python-lsp/python-lsp-server
|
05698fa11bfc566ae7e040a2ed272247f8d406b2
|
diff --git a/test/test_notebook_document.py b/test/test_notebook_document.py
index e8e7ac7..6050b58 100644
--- a/test/test_notebook_document.py
+++ b/test/test_notebook_document.py
@@ -33,7 +33,8 @@ def test_initialize(client_server_pair):
},
).result(timeout=CALL_TIMEOUT_IN_SECONDS)
assert server.workspace is not None
- assert "notebookDocumentSync" in response["capabilities"].keys()
+ selector = response["capabilities"]["notebookDocumentSync"]["notebookSelector"]
+ assert isinstance(selector, list)
@pytest.mark.skipif(IS_WIN, reason="Flaky on Windows")
|
notebookDocumentSync notebookSelector type error
https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notebookDocumentSyncOptions
The notebookSelector should be an array type. But now the object is returned.

|
0.0
|
05698fa11bfc566ae7e040a2ed272247f8d406b2
|
[
"test/test_notebook_document.py::test_initialize"
] |
[
"test/test_notebook_document.py::test_notebook__did_close",
"test/test_notebook_document.py::test_notebook_definition"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-08 18:53:57+00:00
|
mit
| 5,078 |
|
python-lsp__python-lsp-server-459
|
diff --git a/pylsp/config/config.py b/pylsp/config/config.py
index b458069..454ee4b 100644
--- a/pylsp/config/config.py
+++ b/pylsp/config/config.py
@@ -98,6 +98,10 @@ class Config:
self._plugin_settings, plugin_conf
)
+ self._plugin_settings = _utils.merge_dicts(
+ self._plugin_settings, self._init_opts.get("pylsp", {})
+ )
+
self._update_disabled_plugins()
@property
|
python-lsp/python-lsp-server
|
b864c4fccd1ad4bb4f125e321c5ac03c6c21f044
|
diff --git a/test/test_configuration.py b/test/test_configuration.py
new file mode 100644
index 0000000..91da421
--- /dev/null
+++ b/test/test_configuration.py
@@ -0,0 +1,53 @@
+# Copyright 2021- Python Language Server Contributors.
+
+from unittest.mock import patch
+
+from test.test_utils import send_initialize_request
+from test.test_notebook_document import wait_for_condition
+
+import pytest
+
+from pylsp import IS_WIN
+
+
+INITIALIZATION_OPTIONS = {
+ "pylsp": {
+ "plugins": {
+ "flake8": {"enabled": True},
+ "pycodestyle": {"enabled": False},
+ "pyflakes": {"enabled": False},
+ },
+ }
+}
+
+
[email protected](IS_WIN, reason="Flaky on Windows")
+def test_set_flake8_using_init_opts(client_server_pair):
+ client, server = client_server_pair
+ send_initialize_request(client, INITIALIZATION_OPTIONS)
+ for key, value in INITIALIZATION_OPTIONS["pylsp"]["plugins"].items():
+ assert server.workspace._config.settings().get("plugins").get(key).get(
+ "enabled"
+ ) == value.get("enabled")
+
+
[email protected](IS_WIN, reason="Flaky on Windows")
+def test_set_flake8_using_workspace_did_change_configuration(client_server_pair):
+ client, server = client_server_pair
+ send_initialize_request(client, None)
+ assert (
+ server.workspace._config.settings().get("plugins").get("flake8").get("enabled")
+ is False
+ )
+
+ with patch.object(server.workspace, "update_config") as mock_update_config:
+ client._endpoint.notify(
+ "workspace/didChangeConfiguration",
+ {"settings": INITIALIZATION_OPTIONS},
+ )
+ wait_for_condition(lambda: mock_update_config.call_count >= 1)
+
+ for key, value in INITIALIZATION_OPTIONS["pylsp"]["plugins"].items():
+ assert server.workspace._config.settings().get("plugins").get(key).get(
+ "enabled"
+ ) == value.get("enabled")
diff --git a/test/test_utils.py b/test/test_utils.py
index fb4a8b8..8b518d7 100644
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -6,7 +6,7 @@ import os
import sys
from threading import Thread
import time
-from typing import List
+from typing import Any, Dict, List
from unittest import mock
from flaky import flaky
@@ -62,12 +62,13 @@ def notebook_with_python_cells(cells: List[str]):
}
-def send_initialize_request(client):
+def send_initialize_request(client, initialization_options: Dict[str, Any] = None):
return client._endpoint.request(
"initialize",
{
"processId": 1234,
"rootPath": os.path.dirname(__file__),
+ "initializationOptions": initialization_options,
},
).result(timeout=CALL_TIMEOUT_IN_SECONDS)
|
Maybe use initializationOptions as additional source of settings
This came up in [this issue](https://github.com/kak-lsp/kak-lsp/issues/611) with the kak-lsp client.
Before the workaround for that issue, kak-lsp sent server configuration via the `initialize` request (in `initializationOptions`).
It only sent `workspace/didChangeConfiguration` when the configuration actually changed.
This caused problems because pylsp ignores `initializationOptions`. The workaround is to re-send options with `workspace/didChangeConfiguration`.
I wonder if it's a good idea to use `initializationOptions` as additional settings source.
I see two possible variants:
1. Always include `initializationOptions` but let `workspace/didChangeConfiguration` override its settings
2. As soon as `workspace/didChangeConfiguration` arrives, forget the `initializationOptions`
Annoyingly, option 2 would not have fixed the kak-lsp issue, because kak-lsp used to an empty
settings object in `workspace/didChangeConfiguration` (but that's an issue on our side).
It's probably also fine to leave it; LSP is quite underspecified about how these requests interact. I heard that both are deprecated in favor of `workspace/configuration`..
|
0.0
|
b864c4fccd1ad4bb4f125e321c5ac03c6c21f044
|
[
"test/test_configuration.py::test_set_flake8_using_init_opts"
] |
[
"test/test_configuration.py::test_set_flake8_using_workspace_did_change_configuration",
"test/test_utils.py::test_debounce",
"test/test_utils.py::test_debounce_keyed_by",
"test/test_utils.py::test_list_to_string",
"test/test_utils.py::test_find_parents",
"test/test_utils.py::test_merge_dicts",
"test/test_utils.py::test_clip_column",
"test/test_utils.py::test_format_docstring_valid_rst_signature",
"test/test_utils.py::test_format_docstring_invalid_rst_signature"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-12 20:11:17+00:00
|
mit
| 5,079 |
|
python-metar__python-metar-115
|
diff --git a/metar/Datatypes.py b/metar/Datatypes.py
index c1ba23f..201f624 100644
--- a/metar/Datatypes.py
+++ b/metar/Datatypes.py
@@ -480,8 +480,8 @@ class position(object):
long1 = self.longitude
lat2 = position2.latitude
long2 = position2.longitude
- a = sin(0.5(lat2 - lat1)) + cos(lat1) * cos(lat2) * sin(
- 0.5 * (long2 - long1) ** 2
+ a = (sin(0.5(lat2 - lat1))) ** 2 + cos(lat1) * cos(lat2) * (sin(
+ 0.5 * (long2 - long1)) ** 2
)
c = 2.0 * atan(sqrt(a) * sqrt(1.0 - a))
d = distance(earth_radius * c, "M")
diff --git a/metar/Metar.py b/metar/Metar.py
index 9ac23db..9dc08a7 100644
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -43,7 +43,7 @@ TIME_RE = re.compile(
(?P<min>\d\d)Z?\s+""",
re.VERBOSE,
)
-MODIFIER_RE = re.compile(r"^(?P<mod>AUTO|FINO|NIL|TEST|CORR?|RTD|CC[A-G])\s+")
+MODIFIER_RE = re.compile(r"^(?P<mod>AUTO|COR AUTO|FINO|NIL|TEST|CORR?|RTD|CC[A-G])\s+")
WIND_RE = re.compile(
r"""^(?P<dir>[\dO]{3}|[0O]|///|MMM|VRB)
(?P<speed>P?[\dO]{2,3}|[/M]{2,3})
@@ -1045,7 +1045,7 @@ class Metar(object):
(WINDSHEAR_RE, _handleWindShear, True),
(COLOR_RE, _handleColor, True),
(RUNWAYSTATE_RE, _handleRunwayState, True),
- (TREND_RE, _handleTrend, False),
+ (TREND_RE, _handleTrend, True),
(REMARK_RE, _startRemarks, False),
]
|
python-metar/python-metar
|
e572a37a8da465191316e5075059633b83100da4
|
diff --git a/test/test_metar.py b/test/test_metar.py
index 3770baf..92e9534 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -39,6 +39,20 @@ def test_module():
assert hasattr(metar, "__version__")
+def test_issue114_multiplebecominggroups():
+ """multiple BECMG (becoming) groups should be possible"""
+ code = (
+ "METAR WSSS 280900Z 26009KT 180V350 0600 R20R/1900D R20C/1600D +TSRA FEW008 SCT013CB FEW015TCU 24/23 Q1010 "
+ "BECMG FM0920 TL0930 3000 TSRA "
+ "BECMG FM1000 TL1020 6000 NSW"
+ )
+
+ metar = Metar.Metar(code)
+ assert metar.decode_completed
+ assert len(metar._trend_groups) == 10
+ assert metar.trend() == "BECMG FM0920 TL0930 3000 TSRA BECMG FM1000 TL1020 6000 NSW"
+
+
@pytest.mark.parametrize("trailstr", ["", "=", "= "])
def test_issue84_trimequals(trailstr):
"""A trailing = in METAR should not trip up the ingest."""
@@ -602,3 +616,14 @@ def test_not_strict_mode():
assert report.station_id == "K9L2"
assert report.vis.value() == 10
assert report.sky_conditions() == "clear"
+
+
+def test_cor_auto_mod():
+ """Test parsing of a COR AUTO Metar."""
+ code = (
+ "METAR KADW 252356Z COR AUTO 10008KT 10SM CLR 19/11 A2986 "
+ "RMK AO2 SLP117 T01880111 10230 20188 50004 $ COR 0007="
+ )
+ m = Metar.Metar(code, year=2019)
+
+ assert m.mod == 'COR AUTO'
|
Cannot parse multiple BECOMING groups
A `ParserError` is raised when trying to parse a report with multiple BECOMING (`BECMG`) groups:
> Unparsed groups in body 'BECMG FM1000 TL1020 6000 NSW' while processing 'METAR WSSS 280900Z 26009KT 180V350 0600 R20R/1900D R20C/1600D +TSRA FEW008 SCT013CB FEW015TCU 24/23 Q1010 BECMG FM0920 TL0930 3000 TSRA BECMG FM1000 TL1020 6000 NSW'
> Unparsed groups in body 'BECMG FM1920 TL1940 6000 NSW' while processing 'METAR WSSS 311900Z 28009KT 210V320 1800 +TSRA FEW010 FEW014CB BKN015TCU 25/24 Q1011 BECMG TL1920 4000 TSRA BECMG FM1920 TL1940 6000 NSW'
> Unparsed groups in body 'BECMG FM1955 TL2010 6000 NSW' while processing 'METAR WSSS 311930Z VRB05KT 1800 +TSRA FEW008 FEW014CB SCT015TCU 25/24 Q1011 BECMG FM1940 TL1955 4000 TSRA BECMG FM1955 TL2010 6000 NSW'
> Unparsed groups in body 'BECMG FM2020 TL2040 6000 NSW' while processing 'METAR WSSS 312000Z VRB04KT 2000 +TSRA FEW010 FEW014CB SCT040 BKN140 24/24 Q1011 BECMG TL2020 4000 -TSRA BECMG FM2020 TL2040 6000 NSW'
|
0.0
|
e572a37a8da465191316e5075059633b83100da4
|
[
"test/test_metar.py::test_issue114_multiplebecominggroups",
"test/test_metar.py::test_cor_auto_mod"
] |
[
"test/test_metar.py::test_xlate_loc",
"test/test_metar.py::test_module",
"test/test_metar.py::test_issue84_trimequals[]",
"test/test_metar.py::test_issue84_trimequals[=]",
"test/test_metar.py::test_issue84_trimequals[=",
"test/test_metar.py::test_issue77_ice_accretion[1]",
"test/test_metar.py::test_issue77_ice_accretion[3]",
"test/test_metar.py::test_issue77_ice_accretion[6]",
"test/test_metar.py::test_issue64_cloudkeyerror",
"test/test_metar.py::test_issue67_precip_text",
"test/test_metar.py::test_issue40_runwayunits",
"test/test_metar.py::test_010_parseType_default",
"test/test_metar.py::test_011_parseType_legal",
"test/test_metar.py::test_020_parseStation_legal",
"test/test_metar.py::test_021_parseStation_illegal",
"test/test_metar.py::test_030_parseTime_legal",
"test/test_metar.py::test_031_parseTime_specify_year",
"test/test_metar.py::test_032_parseTime_specify_month",
"test/test_metar.py::test_033_parseTime_auto_month",
"test/test_metar.py::test_034_parseTime_auto_year",
"test/test_metar.py::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::test_040_parseModifier_default",
"test/test_metar.py::test_041_parseModifier",
"test/test_metar.py::test_042_parseModifier_nonstd",
"test/test_metar.py::test_043_parseModifier_illegal",
"test/test_metar.py::test_140_parseWind",
"test/test_metar.py::test_141_parseWind_nonstd",
"test/test_metar.py::test_issue51_strict",
"test/test_metar.py::test_142_parseWind_illegal",
"test/test_metar.py::test_150_parseVisibility",
"test/test_metar.py::test_151_parseVisibility_direction",
"test/test_metar.py::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::test_290_ranway_state",
"test/test_metar.py::test_300_parseTrend",
"test/test_metar.py::test_snowdepth",
"test/test_metar.py::test_310_parse_sky_conditions",
"test/test_metar.py::test_not_strict_mode"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-05 19:39:17+00:00
|
bsd-2-clause
| 5,080 |
|
python-metar__python-metar-120
|
diff --git a/metar/Metar.py b/metar/Metar.py
index 5ef2d76..e5d113d 100644
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -109,12 +109,13 @@ COLOR_RE = re.compile(
re.VERBOSE,
)
RUNWAYSTATE_RE = re.compile(
- r"""((?P<name>\d\d) | R(?P<namenew>\d\d)(RR?|LL?|C)?/?)
+ r"""((?P<snoclo>R/SNOCLO) |
+ ((?P<name>\d\d) | R(?P<namenew>\d\d)(RR?|LL?|C)?/?)
((?P<special> SNOCLO|CLRD(\d\d|//)) |
(?P<deposit>(\d|/))
(?P<extent>(\d|/))
(?P<depth>(\d\d|//))
- (?P<friction>(\d\d|//)))\s+""",
+ (?P<friction>(\d\d|//))))\s+""",
re.VERBOSE,
)
TREND_RE = re.compile(r"^(?P<trend>TEMPO|BECMG|FCST|NOSIG)\s+")
|
python-metar/python-metar
|
f0af09e5685083cd3cabe4fb44a28777b95b118a
|
diff --git a/test/test_metar.py b/test/test_metar.py
index 00bd05f..d6818a1 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -556,6 +556,11 @@ def test_290_ranway_state():
assert report("09SNOCLO").remarks() == ""
assert report("09CLRD//").remarks() == ""
+ assert report("R/SNOCLO").remarks() == ""
+ assert report("R09/CLRD//").remarks() == ""
+
+ assert report("R01R/SNOCLO ").remarks() == ""
+
def test_300_parseTrend():
"""Check parsing of trend forecasts."""
|
Unparsed groups in body 'R/SNOCLO'
The [Manual on Codes](https://library.wmo.int/doc_num.php?explnum_id=10235) states
> The state of the runway group shall be replaced by the abbreviation R/SNOCLO when the aerodrome is closed due to extreme deposit of snow.
Note that there is no runway designator, just the letter "R". However, the runway state regex for parsing the record requires a runway number. This leads to the mentioned error.
Test record:
> METAR EDDC 032220Z 31005KT 5000 -SN BKN008 M01/M01 Q1020 R/SNOCLO
|
0.0
|
f0af09e5685083cd3cabe4fb44a28777b95b118a
|
[
"test/test_metar.py::test_290_ranway_state"
] |
[
"test/test_metar.py::test_xlate_loc",
"test/test_metar.py::test_module",
"test/test_metar.py::test_issue114_multiplebecominggroups",
"test/test_metar.py::test_issue84_trimequals[]",
"test/test_metar.py::test_issue84_trimequals[=]",
"test/test_metar.py::test_issue84_trimequals[=",
"test/test_metar.py::test_issue77_ice_accretion[1]",
"test/test_metar.py::test_issue77_ice_accretion[3]",
"test/test_metar.py::test_issue77_ice_accretion[6]",
"test/test_metar.py::test_issue64_cloudkeyerror",
"test/test_metar.py::test_issue67_precip_text",
"test/test_metar.py::test_issue40_runwayunits",
"test/test_metar.py::test_issue107_runwayunits",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////]",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////FT]",
"test/test_metar.py::test_issue26_runway_slashes[R28L//////]",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////N]",
"test/test_metar.py::test_010_parseType_default",
"test/test_metar.py::test_011_parseType_legal",
"test/test_metar.py::test_020_parseStation_legal",
"test/test_metar.py::test_021_parseStation_illegal",
"test/test_metar.py::test_030_parseTime_legal",
"test/test_metar.py::test_031_parseTime_specify_year",
"test/test_metar.py::test_032_parseTime_specify_month",
"test/test_metar.py::test_033_parseTime_auto_month",
"test/test_metar.py::test_034_parseTime_auto_year",
"test/test_metar.py::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::test_040_parseModifier_default",
"test/test_metar.py::test_041_parseModifier",
"test/test_metar.py::test_042_parseModifier_nonstd",
"test/test_metar.py::test_043_parseModifier_illegal",
"test/test_metar.py::test_140_parseWind",
"test/test_metar.py::test_141_parseWind_nonstd",
"test/test_metar.py::test_issue139_no_wind_unit",
"test/test_metar.py::test_issue51_strict",
"test/test_metar.py::test_142_parseWind_illegal",
"test/test_metar.py::test_150_parseVisibility",
"test/test_metar.py::test_151_parseVisibility_direction",
"test/test_metar.py::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::test_300_parseTrend",
"test/test_metar.py::test_snowdepth",
"test/test_metar.py::test_310_parse_sky_conditions",
"test/test_metar.py::test_not_strict_mode",
"test/test_metar.py::test_cor_auto_mod",
"test/test_metar.py::test_slp_outside_remarks",
"test/test_metar.py::test_wind_after_sky",
"test/test_metar.py::test_issue136_temperature",
"test/test_metar.py::test_windshear_runway_identifier"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-05 14:34:10+00:00
|
bsd-2-clause
| 5,081 |
|
python-metar__python-metar-125
|
diff --git a/metar/Datatypes.py b/metar/Datatypes.py
index c1ba23f..201f624 100644
--- a/metar/Datatypes.py
+++ b/metar/Datatypes.py
@@ -480,8 +480,8 @@ class position(object):
long1 = self.longitude
lat2 = position2.latitude
long2 = position2.longitude
- a = sin(0.5(lat2 - lat1)) + cos(lat1) * cos(lat2) * sin(
- 0.5 * (long2 - long1) ** 2
+ a = (sin(0.5(lat2 - lat1))) ** 2 + cos(lat1) * cos(lat2) * (sin(
+ 0.5 * (long2 - long1)) ** 2
)
c = 2.0 * atan(sqrt(a) * sqrt(1.0 - a))
d = distance(earth_radius * c, "M")
diff --git a/metar/Metar.py b/metar/Metar.py
index 9ac23db..bbe3e6e 100644
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -43,7 +43,7 @@ TIME_RE = re.compile(
(?P<min>\d\d)Z?\s+""",
re.VERBOSE,
)
-MODIFIER_RE = re.compile(r"^(?P<mod>AUTO|FINO|NIL|TEST|CORR?|RTD|CC[A-G])\s+")
+MODIFIER_RE = re.compile(r"^(?P<mod>AUTO|COR AUTO|FINO|NIL|TEST|CORR?|RTD|CC[A-G])\s+")
WIND_RE = re.compile(
r"""^(?P<dir>[\dO]{3}|[0O]|///|MMM|VRB)
(?P<speed>P?[\dO]{2,3}|[/M]{2,3})
|
python-metar/python-metar
|
e572a37a8da465191316e5075059633b83100da4
|
diff --git a/test/test_metar.py b/test/test_metar.py
index 3770baf..08824e6 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -602,3 +602,14 @@ def test_not_strict_mode():
assert report.station_id == "K9L2"
assert report.vis.value() == 10
assert report.sky_conditions() == "clear"
+
+
+def test_cor_auto_mod():
+ """Test parsing of a COR AUTO Metar."""
+ code = (
+ "METAR KADW 252356Z COR AUTO 10008KT 10SM CLR 19/11 A2986 "
+ "RMK AO2 SLP117 T01880111 10230 20188 50004 $ COR 0007="
+ )
+ m = Metar.Metar(code, year=2019)
+
+ assert m.mod == 'COR AUTO'
|
Unparsed groups in body 'AUTO'
I've found some METARS that cannot be parsed because they have 'COR AUTO' immediately following the report time. For instance:
```
>>> from metar.Metar import Metar
>>> Metar('''METAR KADW 252356Z COR AUTO 10008KT 10SM CLR 19/11 A2986
RMK AO2 SLP117 T01880111 10230 20188 50004 $ COR
0007=''')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jhaiduce/Development/python-metar/metar/Metar.py", line 499, in __init__
raise ParserError(message)
metar.Metar.ParserError: Unparsed groups in body 'AUTO' while processing 'METAR KADW 252356Z COR AUTO 10008KT 10SM CLR 19/11 A2986
RMK AO2 SLP117 T01880111 10230 20188 50004 $ COR
0007='
```
|
0.0
|
e572a37a8da465191316e5075059633b83100da4
|
[
"test/test_metar.py::test_cor_auto_mod"
] |
[
"test/test_metar.py::test_xlate_loc",
"test/test_metar.py::test_module",
"test/test_metar.py::test_issue84_trimequals[]",
"test/test_metar.py::test_issue84_trimequals[=]",
"test/test_metar.py::test_issue84_trimequals[=",
"test/test_metar.py::test_issue77_ice_accretion[1]",
"test/test_metar.py::test_issue77_ice_accretion[3]",
"test/test_metar.py::test_issue77_ice_accretion[6]",
"test/test_metar.py::test_issue64_cloudkeyerror",
"test/test_metar.py::test_issue67_precip_text",
"test/test_metar.py::test_issue40_runwayunits",
"test/test_metar.py::test_010_parseType_default",
"test/test_metar.py::test_011_parseType_legal",
"test/test_metar.py::test_020_parseStation_legal",
"test/test_metar.py::test_021_parseStation_illegal",
"test/test_metar.py::test_030_parseTime_legal",
"test/test_metar.py::test_031_parseTime_specify_year",
"test/test_metar.py::test_032_parseTime_specify_month",
"test/test_metar.py::test_033_parseTime_auto_month",
"test/test_metar.py::test_034_parseTime_auto_year",
"test/test_metar.py::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::test_040_parseModifier_default",
"test/test_metar.py::test_041_parseModifier",
"test/test_metar.py::test_042_parseModifier_nonstd",
"test/test_metar.py::test_043_parseModifier_illegal",
"test/test_metar.py::test_140_parseWind",
"test/test_metar.py::test_141_parseWind_nonstd",
"test/test_metar.py::test_issue51_strict",
"test/test_metar.py::test_142_parseWind_illegal",
"test/test_metar.py::test_150_parseVisibility",
"test/test_metar.py::test_151_parseVisibility_direction",
"test/test_metar.py::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::test_290_ranway_state",
"test/test_metar.py::test_300_parseTrend",
"test/test_metar.py::test_snowdepth",
"test/test_metar.py::test_310_parse_sky_conditions",
"test/test_metar.py::test_not_strict_mode"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-12-07 16:30:08+00:00
|
bsd-2-clause
| 5,082 |
|
python-metar__python-metar-149
|
diff --git a/metar/Metar.py b/metar/Metar.py
index 8da571d..e3cf432 100644
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -1050,6 +1050,8 @@ class Metar(object):
(RUNWAY_RE, _handleRunway, True),
(WEATHER_RE, _handleWeather, True),
(SKY_RE, _handleSky, True),
+ (WIND_RE, _handleWind, False),
+ (VISIBILITY_RE, _handleVisibility, True),
(TEMP_RE, _handleTemp, False),
(PRESS_RE, _handlePressure, True),
(RECENT_RE, _handleRecent, True),
|
python-metar/python-metar
|
a0768efb99eb849dc67d8b01ea74c56012eaeaaf
|
diff --git a/test/test_metar.py b/test/test_metar.py
index 9bafe17..19996a7 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -654,6 +654,19 @@ def test_cor_auto_mod():
assert m.mod == 'COR AUTO'
+def test_wind_after_sky():
+ """
+ Test parsing of a METAR that lists wind after the sky groups
+ """
+
+ code = (
+ "METAR KCOF 281855Z FEW029TCU FEW040 SCT250 09008KT 7SM 32/25 A3008 "
+ "RMK VIRGA E TCU NE AND DSNT ALQDS SLP186"
+ )
+ m = Metar.Metar(code, year=2007)
+
+ assert m.wind_dir.value() == 90
+ assert m.wind_speed.value() == 8
def test_issue136_temperature():
raisesParserError("METAR EDDM 022150Z 26006KT CAVOK 201/16")
|
Unparsed group '09008KT 7SM' when wind is listed after sky groups.
The following METAR produces a ParserError:
METAR KCOF 281855Z FEW029TCU FEW040 SCT250 09008KT 7SM 32/25 A3008 RMK VIRGA E TCU NE AND DSNT ALQDS SLP186
Backtrace:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jhaiduce/Development/python-metar/metar/Metar.py", line 499, in __init__
raise ParserError(message)
metar.Metar.ParserError: Unparsed groups in body '09008KT 7SM' while processing 'METAR KCOF 281855Z FEW029TCU FEW040 SCT250 09008KT 7SM 32/25 A3008 RMK VIRGA E TCU NE AND DSNT ALQDS SLP186'
```
|
0.0
|
a0768efb99eb849dc67d8b01ea74c56012eaeaaf
|
[
"test/test_metar.py::test_wind_after_sky"
] |
[
"test/test_metar.py::test_xlate_loc",
"test/test_metar.py::test_module",
"test/test_metar.py::test_issue114_multiplebecominggroups",
"test/test_metar.py::test_issue84_trimequals[]",
"test/test_metar.py::test_issue84_trimequals[=]",
"test/test_metar.py::test_issue84_trimequals[=",
"test/test_metar.py::test_issue77_ice_accretion[1]",
"test/test_metar.py::test_issue77_ice_accretion[3]",
"test/test_metar.py::test_issue77_ice_accretion[6]",
"test/test_metar.py::test_issue64_cloudkeyerror",
"test/test_metar.py::test_issue67_precip_text",
"test/test_metar.py::test_issue40_runwayunits",
"test/test_metar.py::test_issue107_runwayunits",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////]",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////FT]",
"test/test_metar.py::test_issue26_runway_slashes[R28L//////]",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////N]",
"test/test_metar.py::test_010_parseType_default",
"test/test_metar.py::test_011_parseType_legal",
"test/test_metar.py::test_020_parseStation_legal",
"test/test_metar.py::test_021_parseStation_illegal",
"test/test_metar.py::test_030_parseTime_legal",
"test/test_metar.py::test_031_parseTime_specify_year",
"test/test_metar.py::test_032_parseTime_specify_month",
"test/test_metar.py::test_033_parseTime_auto_month",
"test/test_metar.py::test_034_parseTime_auto_year",
"test/test_metar.py::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::test_040_parseModifier_default",
"test/test_metar.py::test_041_parseModifier",
"test/test_metar.py::test_042_parseModifier_nonstd",
"test/test_metar.py::test_043_parseModifier_illegal",
"test/test_metar.py::test_140_parseWind",
"test/test_metar.py::test_141_parseWind_nonstd",
"test/test_metar.py::test_issue139_no_wind_unit",
"test/test_metar.py::test_issue51_strict",
"test/test_metar.py::test_142_parseWind_illegal",
"test/test_metar.py::test_150_parseVisibility",
"test/test_metar.py::test_151_parseVisibility_direction",
"test/test_metar.py::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::test_290_ranway_state",
"test/test_metar.py::test_300_parseTrend",
"test/test_metar.py::test_snowdepth",
"test/test_metar.py::test_310_parse_sky_conditions",
"test/test_metar.py::test_not_strict_mode",
"test/test_metar.py::test_cor_auto_mod",
"test/test_metar.py::test_issue136_temperature"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-09-23 17:46:17+00:00
|
bsd-2-clause
| 5,083 |
|
python-metar__python-metar-150
|
diff --git a/metar/Metar.py b/metar/Metar.py
index e3cf432..e9d59ba 100644
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -1054,6 +1054,7 @@ class Metar(object):
(VISIBILITY_RE, _handleVisibility, True),
(TEMP_RE, _handleTemp, False),
(PRESS_RE, _handlePressure, True),
+ (SEALVL_PRESS_RE, _handleSealvlPressRemark, False),
(RECENT_RE, _handleRecent, True),
(WINDSHEAR_RE, _handleWindShear, True),
(COLOR_RE, _handleColor, True),
|
python-metar/python-metar
|
ff8bdc3b87d31271487491ffe07f83d55e7b42f0
|
diff --git a/test/test_metar.py b/test/test_metar.py
index 19996a7..1252f1c 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -654,6 +654,19 @@ def test_cor_auto_mod():
assert m.mod == 'COR AUTO'
+def test_slp_outside_remarks():
+ """
+ Test parsing of a METAR that lists sea level pressure after the altimeter
+ setting instead of in the remarks.
+ """
+
+ code = (
+ "METAR KCOF 191855Z 18015G22KT 7SM FEW049 SCT300 28/18 A3001 SLP162 "
+ "RMK WND DATA ESTMD"
+ )
+ m = Metar.Metar(code, year=2007)
+ m.press_sea_level.value() == 1016.2
+
def test_wind_after_sky():
"""
Test parsing of a METAR that lists wind after the sky groups
|
Unparsed group 'SLP162' when SLP group placed ahead of remarks group.
The following METAR produces a ParserError:
METAR KCOF 191855Z 18015G22KT 7SM FEW049 SCT300 28/18 A3001 SLP162 RMK WND DATA ESTMD
Traceback:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jhaiduce/Development/python-metar/metar/Metar.py", line 499, in __init__
raise ParserError(message)
metar.Metar.ParserError: Unparsed groups in body 'SLP162' while processing 'METAR KCOF 191855Z 18015G22KT 7SM FEW049 SCT300 28/18 A3001 SLP162 RMK WND DATA ESTMD'
```
|
0.0
|
ff8bdc3b87d31271487491ffe07f83d55e7b42f0
|
[
"test/test_metar.py::test_slp_outside_remarks"
] |
[
"test/test_metar.py::test_xlate_loc",
"test/test_metar.py::test_module",
"test/test_metar.py::test_issue114_multiplebecominggroups",
"test/test_metar.py::test_issue84_trimequals[]",
"test/test_metar.py::test_issue84_trimequals[=]",
"test/test_metar.py::test_issue84_trimequals[=",
"test/test_metar.py::test_issue77_ice_accretion[1]",
"test/test_metar.py::test_issue77_ice_accretion[3]",
"test/test_metar.py::test_issue77_ice_accretion[6]",
"test/test_metar.py::test_issue64_cloudkeyerror",
"test/test_metar.py::test_issue67_precip_text",
"test/test_metar.py::test_issue40_runwayunits",
"test/test_metar.py::test_issue107_runwayunits",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////]",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////FT]",
"test/test_metar.py::test_issue26_runway_slashes[R28L//////]",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////N]",
"test/test_metar.py::test_010_parseType_default",
"test/test_metar.py::test_011_parseType_legal",
"test/test_metar.py::test_020_parseStation_legal",
"test/test_metar.py::test_021_parseStation_illegal",
"test/test_metar.py::test_030_parseTime_legal",
"test/test_metar.py::test_031_parseTime_specify_year",
"test/test_metar.py::test_032_parseTime_specify_month",
"test/test_metar.py::test_033_parseTime_auto_month",
"test/test_metar.py::test_034_parseTime_auto_year",
"test/test_metar.py::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::test_040_parseModifier_default",
"test/test_metar.py::test_041_parseModifier",
"test/test_metar.py::test_042_parseModifier_nonstd",
"test/test_metar.py::test_043_parseModifier_illegal",
"test/test_metar.py::test_140_parseWind",
"test/test_metar.py::test_141_parseWind_nonstd",
"test/test_metar.py::test_issue139_no_wind_unit",
"test/test_metar.py::test_issue51_strict",
"test/test_metar.py::test_142_parseWind_illegal",
"test/test_metar.py::test_150_parseVisibility",
"test/test_metar.py::test_151_parseVisibility_direction",
"test/test_metar.py::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::test_290_ranway_state",
"test/test_metar.py::test_300_parseTrend",
"test/test_metar.py::test_snowdepth",
"test/test_metar.py::test_310_parse_sky_conditions",
"test/test_metar.py::test_not_strict_mode",
"test/test_metar.py::test_cor_auto_mod",
"test/test_metar.py::test_wind_after_sky",
"test/test_metar.py::test_issue136_temperature"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-09-23 18:01:22+00:00
|
bsd-2-clause
| 5,084 |
|
python-metar__python-metar-152
|
diff --git a/metar/Metar.py b/metar/Metar.py
index cf6026f..8da571d 100644
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -85,8 +85,8 @@ SKY_RE = re.compile(
re.VERBOSE,
)
TEMP_RE = re.compile(
- r"""^(?P<temp>(M|-)?\d+|//|XX|MM)/
- (?P<dewpt>(M|-)?\d+|//|XX|MM)?\s+""",
+ r"""^(?P<temp>(M|-)?\d{1,2}|//|XX|MM)/
+ (?P<dewpt>(M|-)?\d{1,2}|//|XX|MM)?\s+""",
re.VERBOSE,
)
PRESS_RE = re.compile(
|
python-metar/python-metar
|
2f1be43f23f407152b43a4c2e290dc2dc77029ec
|
diff --git a/test/test_metar.py b/test/test_metar.py
index ed43504..9bafe17 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -653,3 +653,7 @@ def test_cor_auto_mod():
m = Metar.Metar(code, year=2019)
assert m.mod == 'COR AUTO'
+
+
+def test_issue136_temperature():
+ raisesParserError("METAR EDDM 022150Z 26006KT CAVOK 201/16")
|
Parser allows invalid format of temperature group
The regex for the temperature group allows an arbitrary number (but at least 1) of digits, both for temperature and dewpoint:
https://github.com/python-metar/python-metar/blob/96f6b98ce685b37c7d5e438fa2d5e2648e56d0b0/metar/Metar.py#L87-L90
However, the [Manual on Codes](https://library.wmo.int/doc_num.php?explnum_id=10235) gives the format of the temperature group as T'T'/T'<sub>d</sub>T'<sub>d</sub> in 15.11, calling for exactly 2 digits.
Consequently, the following report should raise an error instead of parsing a temperature of 201°C (which clearly is a typo in this context considering the reports before/after this one).
> METAR EDDM 022150Z 26006KT CAVOK 201/16 Q1018 NOSIG
|
0.0
|
2f1be43f23f407152b43a4c2e290dc2dc77029ec
|
[
"test/test_metar.py::test_issue136_temperature"
] |
[
"test/test_metar.py::test_xlate_loc",
"test/test_metar.py::test_module",
"test/test_metar.py::test_issue114_multiplebecominggroups",
"test/test_metar.py::test_issue84_trimequals[]",
"test/test_metar.py::test_issue84_trimequals[=]",
"test/test_metar.py::test_issue84_trimequals[=",
"test/test_metar.py::test_issue77_ice_accretion[1]",
"test/test_metar.py::test_issue77_ice_accretion[3]",
"test/test_metar.py::test_issue77_ice_accretion[6]",
"test/test_metar.py::test_issue64_cloudkeyerror",
"test/test_metar.py::test_issue67_precip_text",
"test/test_metar.py::test_issue40_runwayunits",
"test/test_metar.py::test_issue107_runwayunits",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////]",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////FT]",
"test/test_metar.py::test_issue26_runway_slashes[R28L//////]",
"test/test_metar.py::test_issue26_runway_slashes[R28L/////N]",
"test/test_metar.py::test_010_parseType_default",
"test/test_metar.py::test_011_parseType_legal",
"test/test_metar.py::test_020_parseStation_legal",
"test/test_metar.py::test_021_parseStation_illegal",
"test/test_metar.py::test_030_parseTime_legal",
"test/test_metar.py::test_031_parseTime_specify_year",
"test/test_metar.py::test_032_parseTime_specify_month",
"test/test_metar.py::test_033_parseTime_auto_month",
"test/test_metar.py::test_034_parseTime_auto_year",
"test/test_metar.py::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::test_040_parseModifier_default",
"test/test_metar.py::test_041_parseModifier",
"test/test_metar.py::test_042_parseModifier_nonstd",
"test/test_metar.py::test_043_parseModifier_illegal",
"test/test_metar.py::test_140_parseWind",
"test/test_metar.py::test_141_parseWind_nonstd",
"test/test_metar.py::test_issue139_no_wind_unit",
"test/test_metar.py::test_issue51_strict",
"test/test_metar.py::test_142_parseWind_illegal",
"test/test_metar.py::test_150_parseVisibility",
"test/test_metar.py::test_151_parseVisibility_direction",
"test/test_metar.py::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::test_290_ranway_state",
"test/test_metar.py::test_300_parseTrend",
"test/test_metar.py::test_snowdepth",
"test/test_metar.py::test_310_parse_sky_conditions",
"test/test_metar.py::test_not_strict_mode",
"test/test_metar.py::test_cor_auto_mod"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-10-04 11:58:36+00:00
|
bsd-2-clause
| 5,085 |
|
python-metar__python-metar-43
|
diff --git a/MANIFEST b/MANIFEST
deleted file mode 100644
index 4de8082..0000000
--- a/MANIFEST
+++ /dev/null
@@ -1,19 +0,0 @@
-README
-CHANGES
-NOTES
-LICENSE
-get_report.py
-parse_metar.py
-sample.py
-setup.py
-metar/Datatypes.py
-metar/Metar.py
-metar/__init__.py
-test/all_tests.py
-test/test_direction.py
-test/test_distance.py
-test/test_metar.py
-test/test_precipitation.py
-test/test_pressure.py
-test/test_speed.py
-test/test_temperature.py
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..bbb2df3
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,5 @@
+include README.md
+include CHANGES
+include NOTES
+include LICENSE
+recursive-include test *.py
diff --git a/metar/Metar.py b/metar/Metar.py
index 0e773cb..338e172 100755
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -587,7 +587,7 @@ class Metar(object):
self.vis_dir = direction(vis_dir)
self.vis = distance(vis_dist, vis_units, vis_less)
- def _handleRunway( self, d ):
+ def _handleRunway(self, d):
"""
Parse a runway visual range group.
@@ -596,15 +596,17 @@ class Metar(object):
. name [string]
. low [distance]
. high [distance]
- """
- if d['name']:
- name = d['name']
- low = distance(d['low'])
- if d['high']:
- high = distance(d['high'])
- else:
- high = low
- self.runway.append((name,low,high))
+ . unit [string]
+ """
+ if d['name'] is None:
+ return
+ unit = d['unit'] if d['unit'] is not None else 'FT'
+ low = distance(d['low'], unit)
+ if d['high'] is None:
+ high = low
+ else:
+ high = distance(d['high'], unit)
+ self.runway.append([d['name'], low, high, unit])
def _handleWeather( self, d ):
"""
@@ -1119,16 +1121,23 @@ class Metar(object):
text += "; %s" % self.max_vis.string(units)
return text
- def runway_visual_range( self, units=None ):
+ def runway_visual_range(self, units=None):
"""
Return a textual description of the runway visual range.
"""
lines = []
- for name,low,high in self.runway:
+ for name, low, high, unit in self.runway:
+ reportunits = unit if units is None else units
if low != high:
- lines.append("on runway %s, from %d to %s" % (name, low.value(units), high.string(units)))
+ lines.append(
+ ("on runway %s, from %d to %s"
+ ) % (name, low.value(reportunits),
+ high.string(reportunits))
+ )
else:
- lines.append("on runway %s, %s" % (name, low.string(units)))
+ lines.append(
+ "on runway %s, %s" % (name, low.string(reportunits))
+ )
return "; ".join(lines)
def present_weather( self ):
diff --git a/setup.py b/setup.py
index af7cfab..2ce9dfd 100755
--- a/setup.py
+++ b/setup.py
@@ -36,6 +36,7 @@ setup(
long_description=LONG_DESCRIPTION,
license="MIT",
packages=["metar"],
+ package_data={'metar': ['nsd_cccc.txt', ]},
platforms="Python 2.5 and later.",
classifiers=[
"Development Status :: 5 - Production/Stable",
|
python-metar/python-metar
|
6b5dcc358c1a7b2c46679e83d7ef5f3af25e4f2e
|
diff --git a/test/test_metar.py b/test/test_metar.py
index 76147e1..e6c8fee 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -17,6 +17,17 @@ class MetarTest(unittest.TestCase):
def raisesParserError(self, code):
self.assertRaises(Metar.ParserError, Metar.Metar, code )
+ def test_issue40_runwayunits(self):
+ """Check reported units on runway visual range."""
+ report = Metar.Metar(
+ "METAR KPIT 091955Z COR 22015G25KT 3/4SM R28L/2600FT TSRA OVC010CB "
+ "18/16 A2992 RMK SLP045 T01820159"
+ )
+ res = report.runway_visual_range()
+ self.assertEquals(res, 'on runway 28L, 2600 feet')
+ res = report.runway_visual_range('M')
+ self.assertTrue(res, 'on runway 28L, 792 meters')
+
def test_010_parseType_default(self):
"""Check default value of the report type."""
self.assertEqual( Metar.Metar("KEWR").type, "METAR" )
|
Feet vs. Meters
This METAR has R28L/2600FT but reduction reads:
visual range: on runway 28L, 2600 meters
(should read: visual range: on runway 28L, 2600 feet)
Reference: METAR KPIT 091955Z COR 22015G25KT 3/4SM R28L/2600FT TSRA OVC010CB 18/16 A2992 RMK SLP045 T01820159
|
0.0
|
6b5dcc358c1a7b2c46679e83d7ef5f3af25e4f2e
|
[
"test/test_metar.py::MetarTest::test_issue40_runwayunits"
] |
[
"test/test_metar.py::MetarTest::test_010_parseType_default",
"test/test_metar.py::MetarTest::test_011_parseType_legal",
"test/test_metar.py::MetarTest::test_020_parseStation_legal",
"test/test_metar.py::MetarTest::test_021_parseStation_illegal",
"test/test_metar.py::MetarTest::test_030_parseTime_legal",
"test/test_metar.py::MetarTest::test_031_parseTime_specify_year",
"test/test_metar.py::MetarTest::test_032_parseTime_specify_month",
"test/test_metar.py::MetarTest::test_033_parseTime_auto_month",
"test/test_metar.py::MetarTest::test_034_parseTime_auto_year",
"test/test_metar.py::MetarTest::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::MetarTest::test_040_parseModifier_default",
"test/test_metar.py::MetarTest::test_041_parseModifier",
"test/test_metar.py::MetarTest::test_042_parseModifier_nonstd",
"test/test_metar.py::MetarTest::test_043_parseModifier_illegal",
"test/test_metar.py::MetarTest::test_140_parseWind",
"test/test_metar.py::MetarTest::test_141_parseWind_nonstd",
"test/test_metar.py::MetarTest::test_142_parseWind_illegal",
"test/test_metar.py::MetarTest::test_150_parseVisibility",
"test/test_metar.py::MetarTest::test_151_parseVisibility_direction",
"test/test_metar.py::MetarTest::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::MetarTest::test_290_ranway_state",
"test/test_metar.py::MetarTest::test_300_parseTrend",
"test/test_metar.py::MetarTest::test_310_parse_sky_conditions",
"test/test_metar.py::MetarTest::test_not_strict_mode",
"test/test_metar.py::MetarTest::test_snowdepth"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-03 02:30:55+00:00
|
bsd-2-clause
| 5,086 |
|
python-metar__python-metar-45
|
diff --git a/metar/Metar.py b/metar/Metar.py
index 338e172..c089afb 100755
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -1216,12 +1216,14 @@ class Metar(object):
what = "clouds"
else:
what = ""
+ label = "%s %s" % (SKY_COVER[cover], what)
+ # HACK here to account for 'empty' entries with above format
+ label = " ".join(label.strip().split())
if cover == "VV":
- text_list.append("%s%s, vertical visibility to %s" %
- (SKY_COVER[cover],what,str(height)))
+ label += ", vertical visibility to %s" % (str(height), )
else:
- text_list.append("%s%s at %s" %
- (SKY_COVER[cover],what,str(height)))
+ label += " at %s" % (str(height), )
+ text_list.append(label)
return sep.join(text_list)
def trend( self ):
|
python-metar/python-metar
|
b9e9aec2a429d2512ec931ce8cf6b281abacc5e5
|
diff --git a/test/test_metar.py b/test/test_metar.py
index e6c8fee..990b7b0 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -457,6 +457,9 @@ class MetarTest(unittest.TestCase):
self.assertEqual( report('SCT030').sky_conditions(), 'scattered clouds at 3000 feet' )
self.assertEqual( report('BKN001').sky_conditions(), 'broken clouds at 100 feet' )
self.assertEqual( report('OVC008').sky_conditions(), 'overcast at 800 feet' )
+ self.assertEqual(
+ report('OVC010CB').sky_conditions(), 'overcast cumulonimbus at 1000 feet'
+ )
self.assertEqual( report('SCT020TCU').sky_conditions(), 'scattered towering cumulus at 2000 feet' )
self.assertEqual( report('BKN015CB').sky_conditions(), 'broken cumulonimbus at 1500 feet' )
self.assertEqual( report('FEW030').sky_conditions(), 'a few clouds at 3000 feet' )
|
Spacing issue
sky: overcastcumulonimbus at 1000 feet
should read
sky: overcast^cumulonimbus at 1000 feet
|
0.0
|
b9e9aec2a429d2512ec931ce8cf6b281abacc5e5
|
[
"test/test_metar.py::MetarTest::test_310_parse_sky_conditions"
] |
[
"test/test_metar.py::MetarTest::test_010_parseType_default",
"test/test_metar.py::MetarTest::test_011_parseType_legal",
"test/test_metar.py::MetarTest::test_020_parseStation_legal",
"test/test_metar.py::MetarTest::test_021_parseStation_illegal",
"test/test_metar.py::MetarTest::test_030_parseTime_legal",
"test/test_metar.py::MetarTest::test_031_parseTime_specify_year",
"test/test_metar.py::MetarTest::test_032_parseTime_specify_month",
"test/test_metar.py::MetarTest::test_033_parseTime_auto_month",
"test/test_metar.py::MetarTest::test_034_parseTime_auto_year",
"test/test_metar.py::MetarTest::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::MetarTest::test_040_parseModifier_default",
"test/test_metar.py::MetarTest::test_041_parseModifier",
"test/test_metar.py::MetarTest::test_042_parseModifier_nonstd",
"test/test_metar.py::MetarTest::test_043_parseModifier_illegal",
"test/test_metar.py::MetarTest::test_140_parseWind",
"test/test_metar.py::MetarTest::test_141_parseWind_nonstd",
"test/test_metar.py::MetarTest::test_142_parseWind_illegal",
"test/test_metar.py::MetarTest::test_150_parseVisibility",
"test/test_metar.py::MetarTest::test_151_parseVisibility_direction",
"test/test_metar.py::MetarTest::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::MetarTest::test_290_ranway_state",
"test/test_metar.py::MetarTest::test_300_parseTrend",
"test/test_metar.py::MetarTest::test_issue40_runwayunits",
"test/test_metar.py::MetarTest::test_not_strict_mode",
"test/test_metar.py::MetarTest::test_snowdepth"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-06 14:29:56+00:00
|
bsd-2-clause
| 5,087 |
|
python-metar__python-metar-55
|
diff --git a/metar/Metar.py b/metar/Metar.py
index b682d2c..766c485 100755
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -324,13 +324,11 @@ class Metar(object):
provided, then the month and year are guessed from the current date.
utcdelta : int or datetime.timedelta, optional
An int of hours or a timedelta object used to specify the timezone.
- strict : bool (default is True) or str {'raise', 'warn', 'log'}
- When unparsed or unparseable groups exist in a METAR code, a
- ``ParserError`` will be raised. Setting this to False will suppress that
- behavior and will use the standard library's logging module to record
- all supressed errors. One can then detect if decoding is complete by
- checking the :attr:`decode_completed` attribute.
-
+ strict : bool (default is True)
+ This option determines if a ``ParserError`` is raised when
+ unparsable groups are found or an unexpected exception is encountered.
+ Setting this to `False` will prevent exceptions from being raised and
+ only generate warning messages.
"""
self.code = metarcode # original METAR code
@@ -439,9 +437,13 @@ class Metar(object):
except Exception as err:
message = (
- "%s failed while processing '%s'\n\t%s" % (handler.__name__, code, "\n\t".join(err.args))
+ ("%s failed while processing '%s'\n\t%s"
+ ) % (handler.__name__, code, "\n\t".join(err.args))
)
- raise ParserError(message)
+ if strict:
+ raise ParserError(message)
+ else:
+ warnings.warn(message, RuntimeWarning)
if self._unparsed_groups:
code = ' '.join(self._unparsed_groups)
|
python-metar/python-metar
|
94a48ea3b965ed1b38c5ab52553dd4cbcc23867c
|
diff --git a/test/test_metar.py b/test/test_metar.py
index d358061..269cf02 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -267,6 +267,13 @@ class MetarTest(unittest.TestCase):
self.assertEqual( report("MMMMMGMMKT").wind(), "missing" )
self.assertEqual( report("MMMMMG01KT").wind(), "missing" )
+ def test_issue51_strict(self):
+ """Check that setting strict=False prevents a ParserError"""
+ with warnings.catch_warnings(record=True) as w:
+ report = Metar.Metar(sta_time+"90010KT", strict=False)
+ assert len(w) == 1
+ assert report.wind_speed is None
+
def test_142_parseWind_illegal(self):
"""Check rejection of illegal wind groups."""
self.raisesParserError( sta_time+"90010KT" )
|
Allow `ParserErrors` to not raise
If you're like me and get most of your METAR codes from FAA's ASOS program, you get a *lot* of parser errors.
The `MetarParser` subclass in [cloudside](https://github.com/Geosyntec/cloudside/blob/master/cloudside/station.py#L149) gets around this by simply logging the error and moving on.
It'd be nice to have this as an *option* upstream.
|
0.0
|
94a48ea3b965ed1b38c5ab52553dd4cbcc23867c
|
[
"test/test_metar.py::MetarTest::test_issue51_strict"
] |
[
"test/test_metar.py::MetarTest::test_010_parseType_default",
"test/test_metar.py::MetarTest::test_011_parseType_legal",
"test/test_metar.py::MetarTest::test_020_parseStation_legal",
"test/test_metar.py::MetarTest::test_021_parseStation_illegal",
"test/test_metar.py::MetarTest::test_030_parseTime_legal",
"test/test_metar.py::MetarTest::test_031_parseTime_specify_year",
"test/test_metar.py::MetarTest::test_032_parseTime_specify_month",
"test/test_metar.py::MetarTest::test_033_parseTime_auto_month",
"test/test_metar.py::MetarTest::test_034_parseTime_auto_year",
"test/test_metar.py::MetarTest::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::MetarTest::test_040_parseModifier_default",
"test/test_metar.py::MetarTest::test_041_parseModifier",
"test/test_metar.py::MetarTest::test_042_parseModifier_nonstd",
"test/test_metar.py::MetarTest::test_043_parseModifier_illegal",
"test/test_metar.py::MetarTest::test_140_parseWind",
"test/test_metar.py::MetarTest::test_141_parseWind_nonstd",
"test/test_metar.py::MetarTest::test_142_parseWind_illegal",
"test/test_metar.py::MetarTest::test_150_parseVisibility",
"test/test_metar.py::MetarTest::test_151_parseVisibility_direction",
"test/test_metar.py::MetarTest::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::MetarTest::test_290_ranway_state",
"test/test_metar.py::MetarTest::test_300_parseTrend",
"test/test_metar.py::MetarTest::test_310_parse_sky_conditions",
"test/test_metar.py::MetarTest::test_issue40_runwayunits",
"test/test_metar.py::MetarTest::test_not_strict_mode",
"test/test_metar.py::MetarTest::test_snowdepth"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-17 13:20:34+00:00
|
bsd-2-clause
| 5,088 |
|
python-metar__python-metar-69
|
diff --git a/metar/Metar.py b/metar/Metar.py
index d5836e3..7cbcaac 100755
--- a/metar/Metar.py
+++ b/metar/Metar.py
@@ -209,15 +209,25 @@ SKY_COVER = { "SKC":"clear",
"///":"",
"VV":"indefinite ceiling" }
-CLOUD_TYPE = { "TCU":"towering cumulus",
- "CU":"cumulus",
- "CB":"cumulonimbus",
- "SC":"stratocumulus",
- "CBMAM":"cumulonimbus mammatus",
- "ACC":"altocumulus castellanus",
- "SCSL":"standing lenticular stratocumulus",
- "CCSL":"standing lenticular cirrocumulus",
- "ACSL":"standing lenticular altocumulus" }
+
+CLOUD_TYPE = {
+ "AC": "altocumulus",
+ "ACC": "altocumulus castellanus",
+ "ACSL": "standing lenticular altocumulus",
+ "AS": "altostratus",
+ "CB": "cumulonimbus",
+ "CBMAM": "cumulonimbus mammatus",
+ "CCSL": "standing lenticular cirrocumulus",
+ "CC": "cirrocumulus",
+ "CI": "cirrus",
+ "CS": "cirrostratus",
+ "CU": "cumulus",
+ "NS": "nimbostratus",
+ "SC": "stratocumulus",
+ "ST": "stratus",
+ "SCSL": "standing lenticular stratocumulus",
+ "TCU": "towering cumulus",
+}
## translation of the present-weather codes into english
@@ -1243,7 +1253,9 @@ class Metar(object):
text_list.append(SKY_COVER[cover])
else:
if cloud:
- what = CLOUD_TYPE[cloud]
+ what = CLOUD_TYPE.get(
+ cloud, "unknown CLOUD_TYPE of %s" % (cloud, )
+ )
elif SKY_COVER[cover].endswith(" "):
what = "clouds"
else:
|
python-metar/python-metar
|
f092a1bf3a8b35a0366b6c5f42fe8fea6bdba093
|
diff --git a/test/test_metar.py b/test/test_metar.py
index 5630e1b..5482a03 100644
--- a/test/test_metar.py
+++ b/test/test_metar.py
@@ -17,6 +17,19 @@ class MetarTest(unittest.TestCase):
def raisesParserError(self, code):
self.assertRaises(Metar.ParserError, Metar.Metar, code )
+ def test_issue64_cloudkeyerror(self):
+ """Lookup on CLOUD_TYPE should not keyerror."""
+ report = Metar.Metar(
+ "METAR LOXZ 141420Z 08006KT 20KM VCSH FEW025SC SCT040SC BKN090AC "
+ "21/14 Q1015 BECMG SCT090"
+ )
+ res = report.sky_conditions()
+ ans = (
+ "a few stratocumulus at 2500 feet; scattered stratocumulus at "
+ "4000 feet; broken altocumulus at 9000 feet"
+ )
+ self.assertEqual(res, ans)
+
def test_issue40_runwayunits(self):
"""Check reported units on runway visual range."""
report = Metar.Metar(
|
AC code should be added to CLOUD_TYPE
Hi,
in this METAR `METAR LOXZ 141420Z 08006KT 20KM VCSH FEW025SC SCT040SC BKN090AC 21/14 Q1015 BECMG SCT090` parsing is ok but when we want the string representation we got an error
```
line 1161, in sky_conditions
what = CLOUD_TYPE[cloud]
KeyError: 'AC'
```
AC for Alto Cumulus should be added.
|
0.0
|
f092a1bf3a8b35a0366b6c5f42fe8fea6bdba093
|
[
"test/test_metar.py::MetarTest::test_issue64_cloudkeyerror"
] |
[
"test/test_metar.py::MetarTest::test_010_parseType_default",
"test/test_metar.py::MetarTest::test_011_parseType_legal",
"test/test_metar.py::MetarTest::test_020_parseStation_legal",
"test/test_metar.py::MetarTest::test_021_parseStation_illegal",
"test/test_metar.py::MetarTest::test_030_parseTime_legal",
"test/test_metar.py::MetarTest::test_031_parseTime_specify_year",
"test/test_metar.py::MetarTest::test_032_parseTime_specify_month",
"test/test_metar.py::MetarTest::test_033_parseTime_auto_month",
"test/test_metar.py::MetarTest::test_034_parseTime_auto_year",
"test/test_metar.py::MetarTest::test_035_parseTime_suppress_auto_month",
"test/test_metar.py::MetarTest::test_040_parseModifier_default",
"test/test_metar.py::MetarTest::test_041_parseModifier",
"test/test_metar.py::MetarTest::test_042_parseModifier_nonstd",
"test/test_metar.py::MetarTest::test_043_parseModifier_illegal",
"test/test_metar.py::MetarTest::test_140_parseWind",
"test/test_metar.py::MetarTest::test_141_parseWind_nonstd",
"test/test_metar.py::MetarTest::test_142_parseWind_illegal",
"test/test_metar.py::MetarTest::test_150_parseVisibility",
"test/test_metar.py::MetarTest::test_151_parseVisibility_direction",
"test/test_metar.py::MetarTest::test_152_parseVisibility_with_following_temperature",
"test/test_metar.py::MetarTest::test_290_ranway_state",
"test/test_metar.py::MetarTest::test_300_parseTrend",
"test/test_metar.py::MetarTest::test_310_parse_sky_conditions",
"test/test_metar.py::MetarTest::test_issue40_runwayunits",
"test/test_metar.py::MetarTest::test_issue51_strict",
"test/test_metar.py::MetarTest::test_not_strict_mode",
"test/test_metar.py::MetarTest::test_snowdepth"
] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-09-25 21:13:06+00:00
|
bsd-2-clause
| 5,089 |
|
python-odin__odin-120
|
diff --git a/HISTORY b/HISTORY
index c37c1c2..f2fc06d 100644
--- a/HISTORY
+++ b/HISTORY
@@ -1,3 +1,9 @@
+1.7.2
+=====
+
+- Fix an edge case bug where validators are not executed against empty list/dict
+ fields.
+
1.7.1
=====
diff --git a/poetry.lock b/poetry.lock
index 352e8c2..e8a2532 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -81,7 +81,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
[[package]]
name = "charset-normalizer"
-version = "2.0.3"
+version = "2.0.4"
description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet."
category = "dev"
optional = false
@@ -267,7 +267,7 @@ six = ">=1.0.0,<2.0.0"
[[package]]
name = "more-itertools"
-version = "8.8.0"
+version = "8.9.0"
description = "More routines for operating on iterables, beyond itertools"
category = "dev"
optional = false
@@ -627,8 +627,8 @@ chardet = [
{file = "chardet-4.0.0.tar.gz", hash = "sha256:0d6f53a15db4120f2b08c94f11e7d93d2c911ee118b6b30a04ec3ee8310179fa"},
]
charset-normalizer = [
- {file = "charset-normalizer-2.0.3.tar.gz", hash = "sha256:c46c3ace2d744cfbdebceaa3c19ae691f53ae621b39fd7570f59d14fb7f2fd12"},
- {file = "charset_normalizer-2.0.3-py3-none-any.whl", hash = "sha256:88fce3fa5b1a84fdcb3f603d889f723d1dd89b26059d0123ca435570e848d5e1"},
+ {file = "charset-normalizer-2.0.4.tar.gz", hash = "sha256:f23667ebe1084be45f6ae0538e4a5a865206544097e4e8bbcacf42cd02a348f3"},
+ {file = "charset_normalizer-2.0.4-py3-none-any.whl", hash = "sha256:0c8911edd15d19223366a194a513099a302055a962bca2cec0f54b8b63175d8b"},
]
colorama = [
{file = "colorama-0.4.4-py2.py3-none-any.whl", hash = "sha256:9f47eda37229f68eee03b24b9748937c7dc3868f906e8ba69fbcbdd3bc5dc3e2"},
@@ -777,8 +777,8 @@ more-itertools = [
{file = "more-itertools-5.0.0.tar.gz", hash = "sha256:38a936c0a6d98a38bcc2d03fdaaedaba9f412879461dd2ceff8d37564d6522e4"},
{file = "more_itertools-5.0.0-py2-none-any.whl", hash = "sha256:c0a5785b1109a6bd7fac76d6837fd1feca158e54e521ccd2ae8bfe393cc9d4fc"},
{file = "more_itertools-5.0.0-py3-none-any.whl", hash = "sha256:fe7a7cae1ccb57d33952113ff4fa1bc5f879963600ed74918f1236e212ee50b9"},
- {file = "more-itertools-8.8.0.tar.gz", hash = "sha256:83f0308e05477c68f56ea3a888172c78ed5d5b3c282addb67508e7ba6c8f813a"},
- {file = "more_itertools-8.8.0-py3-none-any.whl", hash = "sha256:2cf89ec599962f2ddc4d568a05defc40e0a587fbc10d5989713638864c36be4d"},
+ {file = "more-itertools-8.9.0.tar.gz", hash = "sha256:8c746e0d09871661520da4f1241ba6b908dc903839733c8203b552cffaf173bd"},
+ {file = "more_itertools-8.9.0-py3-none-any.whl", hash = "sha256:70401259e46e216056367a0a6034ee3d3f95e0bf59d3aa6a4eb77837171ed996"},
]
msgpack = [
{file = "msgpack-1.0.2-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:b6d9e2dae081aa35c44af9c4298de4ee72991305503442a5c74656d82b581fe9"},
diff --git a/pyproject.toml b/pyproject.toml
index a32e56f..7b85791 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "odin"
-version = "1.7.1"
+version = "1.7.2"
description = "Data-structure definition/validation/traversal, mapping and serialisation toolkit for Python"
authors = ["Tim Savage <[email protected]>"]
license = "BSD-3-Clause"
diff --git a/src/odin/fields/__init__.py b/src/odin/fields/__init__.py
index 3703290..0da7e18 100644
--- a/src/odin/fields/__init__.py
+++ b/src/odin/fields/__init__.py
@@ -40,6 +40,7 @@ __all__ = (
"IPv4Field",
"IPv6Field",
"IPv46Field",
+ "ListField",
"UUIDField",
"DictField",
"ObjectField",
@@ -76,6 +77,7 @@ class Field(BaseField):
"required": "This field is required.",
}
data_type_name = None
+ empty_values = EMPTY_VALUES
def __init__(
self,
@@ -170,7 +172,7 @@ class Field(BaseField):
raise NotImplementedError()
def run_validators(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
errors = []
@@ -186,7 +188,7 @@ class Field(BaseField):
def validate(self, value):
if (
self.choice_values
- and (value not in EMPTY_VALUES)
+ and (value not in self.empty_values)
and (value not in self.choice_values)
):
msg = self.error_messages["invalid_choice"] % value
@@ -315,7 +317,7 @@ class ScalarField(Field):
self.validators.append(MaxValueValidator(max_value))
def to_python(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
try:
return self.scalar_type(value)
@@ -366,7 +368,7 @@ class DateField(_IsoFormatMixin, Field):
data_type_name = "ISO-8601 Date"
def to_python(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
if isinstance(value, datetime.datetime):
return value.date()
@@ -403,7 +405,7 @@ class TimeField(_IsoFormatMixin, Field):
self.assume_local = assume_local
def to_python(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
if isinstance(value, datetime.time):
return value
@@ -440,7 +442,7 @@ class NaiveTimeField(_IsoFormatMixin, Field):
self.ignore_timezone = ignore_timezone
def to_python(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
if isinstance(value, datetime.time):
if value.tzinfo and self.ignore_timezone:
@@ -491,7 +493,7 @@ class DateTimeField(_IsoFormatMixin, Field):
self.assume_local = assume_local
def to_python(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
if isinstance(value, datetime.datetime):
return value
@@ -528,7 +530,7 @@ class NaiveDateTimeField(_IsoFormatMixin, Field):
self.ignore_timezone = ignore_timezone
def to_python(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
if isinstance(value, datetime.datetime):
if value.tzinfo and self.ignore_timezone:
@@ -570,7 +572,7 @@ class HttpDateTimeField(Field):
data_type_name = "ISO-1123 DateTime"
def to_python(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
if isinstance(value, datetime.datetime):
return value
@@ -607,7 +609,7 @@ class TimeStampField(Field):
data_type_name = "Integer"
def to_python(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
if isinstance(value, datetime.datetime):
return value
@@ -619,7 +621,7 @@ class TimeStampField(Field):
raise exceptions.ValidationError(msg)
def prepare(self, value):
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
if isinstance(value, six.integer_types):
return long(value)
@@ -632,6 +634,7 @@ class DictField(Field):
"invalid": "Must be a dict.",
}
data_type_name = "Dict"
+ empty_values = (None, "", [], ())
def __init__(self, **options):
options.setdefault("default", dict)
@@ -656,6 +659,7 @@ class ListField(Field):
"invalid": "Must be an array.",
}
data_type_name = "List"
+ empty_values = (None, "", {}, ())
def __init__(self, **options):
options.setdefault("default", list)
@@ -783,7 +787,7 @@ class TypedDictField(DictField):
def validate(self, value):
super(TypedDictField, self).validate(value)
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
key_errors = []
@@ -811,7 +815,7 @@ class TypedDictField(DictField):
def run_validators(self, value):
super(TypedDictField, self).run_validators(value)
- if value in EMPTY_VALUES:
+ if value in self.empty_values:
return
key_errors = []
|
python-odin/odin
|
8b1ea7fd573dd80a67cc2d041e2d4da4ae6c4788
|
diff --git a/tests/test_fields.py b/tests/test_fields.py
index e53546e..456b53c 100644
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -12,6 +12,7 @@ from odin.validators import (
MaxValueValidator,
MaxLengthValidator,
RegexValidator,
+ MinLengthValidator,
)
from odin.exceptions import ValidationError
@@ -822,7 +823,7 @@ class TestFields(object):
# DictField ###############################################################
- def test_dictfield_1(self):
+ def test_dictfield__where_null_is_false(self):
f = DictField()
pytest.raises(ValidationError, f.clean, None)
pytest.raises(ValidationError, f.clean, "abc")
@@ -831,18 +832,25 @@ class TestFields(object):
assert {"foo": "bar"} == f.clean({"foo": "bar"})
assert f.default == dict
- def test_dictfield_2(self):
+ def test_dictfield__where_null_is_true(self):
f = DictField(null=True)
- assert None == f.clean(None)
+ assert None is f.clean(None)
assert {} == f.clean({})
pytest.raises(ValidationError, f.clean, "abc")
pytest.raises(ValidationError, f.clean, 123)
assert {"foo": "bar"} == f.clean({"foo": "bar"})
- # ArrayField ##############################################################
+ def test_dictfield__validators_are_executed_on_empty(self):
+ """
+ Ensure that validators are executed even if the field is empty
+ """
+ f = DictField(validators=[MinLengthValidator(1)])
+ pytest.raises(ValidationError, f.clean, {})
+
+ # ListField ##############################################################
- def test_arrayfield_1(self):
- f = ArrayField()
+ def test_listfield__where_null_is_false(self):
+ f = ListField()
pytest.raises(ValidationError, f.clean, None)
pytest.raises(ValidationError, f.clean, "abc")
pytest.raises(ValidationError, f.clean, 123)
@@ -851,8 +859,8 @@ class TestFields(object):
assert ["foo", "bar", "$", "eek"], f.clean(["foo", "bar", "$" == "eek"])
assert f.default == list
- def test_arrayfield_2(self):
- f = ArrayField(null=True)
+ def test_listfield__where_null_is_true(self):
+ f = ListField(null=True)
assert None == f.clean(None)
pytest.raises(ValidationError, f.clean, "abc")
pytest.raises(ValidationError, f.clean, 123)
@@ -860,9 +868,16 @@ class TestFields(object):
assert ["foo", "bar"], f.clean(["foo" == "bar"])
assert ["foo", "bar", "$", "eek"], f.clean(["foo", "bar", "$" == "eek"])
+ def test_listfield__validators_are_executed_on_empty(self):
+ """
+ Ensure that validators are executed even if the field is empty
+ """
+ f = ListField(validators=[MinLengthValidator(1)])
+ pytest.raises(ValidationError, f.clean, [])
+
# TypedListField #########################################################
- def test_typedlistfield_1(self):
+ def test_typedlistfield__where_null_is_false(self):
f = TypedListField(IntegerField())
assert "List<Integer>" == f.data_type_name(f)
pytest.raises(ValidationError, f.clean, None)
@@ -873,7 +888,7 @@ class TestFields(object):
assert [1, 2, 3], f.clean([1, 2 == 3])
assert f.default == list
- def test_typedlistfield_2(self):
+ def test_typedlistfield__where_null_is_true(self):
f = TypedListField(IntegerField(), null=True)
assert "List<Integer>" == f.data_type_name(f)
assert None == f.clean(None)
|
List and Dict fields don't apply validation rules if the array is empty
If a field array contains no items validation rules are not being applied and are treated as if they are None. This is an issue if a validation rule is to ensure there are at least n items in a list or dict.
|
0.0
|
8b1ea7fd573dd80a67cc2d041e2d4da4ae6c4788
|
[
"tests/test_fields.py::TestFields::test_dictfield__validators_are_executed_on_empty",
"tests/test_fields.py::TestFields::test_listfield__where_null_is_false",
"tests/test_fields.py::TestFields::test_listfield__where_null_is_true",
"tests/test_fields.py::TestFields::test_listfield__validators_are_executed_on_empty",
"tests/test_fields.py::TestFields::test_uuid_field_with_bytes[97d4bb2c-54d4-11ef-98f7-fa3cdcf14c24]",
"tests/test_fields.py::TestFields::test_uuid_field_with_bytes[74978c65-53be-3a46-956f-db423e378212]",
"tests/test_fields.py::TestFields::test_uuid_field_with_bytes[e38e0acd-5f2b-4c54-b6d4-1f861127f424]",
"tests/test_fields.py::TestFields::test_uuid_field_with_bytes[4d967b7e-94a5-5f3a-847b-f423558e2fee]",
"tests/test_fields.py::TestFields::test_uuid_field_with_string[97d4bd2a-54d4-11ef-98f7-fa3cdcf14c24]",
"tests/test_fields.py::TestFields::test_uuid_field_with_string[bd76eae7-eb63-3e50-86c7-819b378b5ca8]",
"tests/test_fields.py::TestFields::test_uuid_field_with_string[7fea0cfe-5725-45e0-8820-36c9769cbaf1]",
"tests/test_fields.py::TestFields::test_uuid_field_with_string[bcb641cf-88e2-5bbb-9503-33dc1aee7de9]"
] |
[
"tests/test_fields.py::TestField::test_error_messages_no_overrides",
"tests/test_fields.py::TestField::test_error_messages_override_add",
"tests/test_fields.py::TestField::test_set_attributes_from_name",
"tests/test_fields.py::TestField::test_set_attributes_from_name_with_name",
"tests/test_fields.py::TestField::test_set_attributes_from_name_with_verbose_name",
"tests/test_fields.py::TestField::test_as_string[None-None]",
"tests/test_fields.py::TestField::test_as_string[-]",
"tests/test_fields.py::TestField::test_as_string[abc-abc]",
"tests/test_fields.py::TestField::test_as_string[1-1]",
"tests/test_fields.py::TestField::test_as_string[True-True]",
"tests/test_fields.py::TestField::test_as_string[False-False]",
"tests/test_fields.py::TestField::test_choice_doc_test",
"tests/test_fields.py::TestField::test_has_default",
"tests/test_fields.py::TestField::test_has_default_supplied",
"tests/test_fields.py::TestField::test_get_default",
"tests/test_fields.py::TestField::test_get_default_supplied",
"tests/test_fields.py::TestField::test_get_default_callable",
"tests/test_fields.py::TestField::test_value_from_object",
"tests/test_fields.py::TestField::test__repr",
"tests/test_fields.py::TestField::test__deep_copy",
"tests/test_fields.py::TestField::test_run_validators_and_override_validator_message",
"tests/test_fields.py::TestField::test_run_validators_and_override_validator_message_with_params",
"tests/test_fields.py::TestField::test_default_to_python_raises_not_implemented",
"tests/test_fields.py::TestField::test_clean_uses_default_if_value_is_not_provided_is_true",
"tests/test_fields.py::TestField::test_clean_uses_default_if_value_is_not_provided_is_false",
"tests/test_fields.py::TestVirtualField::test_creation_counter",
"tests/test_fields.py::TestVirtualField::test_repr",
"tests/test_fields.py::TestVirtualField::test_default_descriptor_behaviour",
"tests/test_fields.py::TestFields::test_booleanfield_success[field0-True-True]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field1-1-True]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field2-Yes-True]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field3-true-True]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field4-T-True]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field5-1-True]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field6-TRUE-True]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field7-False-False]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field8-0-False]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field9-No-False]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field10-false-False]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field11-FALSE-False]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field12-F-False]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field13-0-False]",
"tests/test_fields.py::TestFields::test_booleanfield_success[field14-None-None]",
"tests/test_fields.py::TestFields::test_booleanfield_failure[field0-None]",
"tests/test_fields.py::TestFields::test_booleanfield_failure[field1-]",
"tests/test_fields.py::TestFields::test_booleanfield_failure[field2-Awesome!]",
"tests/test_fields.py::TestFields::test_stringfield_success[field0-1-1]",
"tests/test_fields.py::TestFields::test_stringfield_success[field1-eek-eek]",
"tests/test_fields.py::TestFields::test_stringfield_success[field2-1-1]",
"tests/test_fields.py::TestFields::test_stringfield_success[field3-None-None]",
"tests/test_fields.py::TestFields::test_stringfield_success[field4--]",
"tests/test_fields.py::TestFields::test_stringfield_success[field5--]",
"tests/test_fields.py::TestFields::test_stringfield_success[field6--]",
"tests/test_fields.py::TestFields::test_stringfield_success[field7-123456-123456]",
"tests/test_fields.py::TestFields::test_stringfield_failure[field0-None]",
"tests/test_fields.py::TestFields::test_stringfield_failure[field1-]",
"tests/test_fields.py::TestFields::test_stringfield_failure[field2-]",
"tests/test_fields.py::TestFields::test_stringfield_failure[field3-]",
"tests/test_fields.py::TestFields::test_stringfield_failure[field4-1234567890a]",
"tests/test_fields.py::TestFields::test_stringfield",
"tests/test_fields.py::TestFields::test_stringfield__handling_of_null_empty[field0-False]",
"tests/test_fields.py::TestFields::test_stringfield__handling_of_null_empty[field1-True]",
"tests/test_fields.py::TestFields::test_stringfield__handling_of_null_empty[field2-False]",
"tests/test_fields.py::TestFields::test_stringfield__handling_of_null_empty[field3-True]",
"tests/test_fields.py::TestFields::test_stringfield__handling_of_null_empty[field4-True]",
"tests/test_fields.py::TestFields::test_stringfield__handling_of_null_empty[field5-False]",
"tests/test_fields.py::TestFields::test_stringfield__handling_of_null_empty[field6-False]",
"tests/test_fields.py::TestFields::test_urlfield_1",
"tests/test_fields.py::TestFields::test_integerfield_1",
"tests/test_fields.py::TestFields::test_integerfield_2",
"tests/test_fields.py::TestFields::test_integerfield_3",
"tests/test_fields.py::TestFields::test_floatfield_1",
"tests/test_fields.py::TestFields::test_floatfield_2",
"tests/test_fields.py::TestFields::test_floatfield_3",
"tests/test_fields.py::TestFields::test_datefield_clean_success[field0-2013-11-24-expected0]",
"tests/test_fields.py::TestFields::test_datefield_clean_success[field1-value1-expected1]",
"tests/test_fields.py::TestFields::test_datefield_clean_success[field2-value2-expected2]",
"tests/test_fields.py::TestFields::test_datefield_clean_success[field3-None-None]",
"tests/test_fields.py::TestFields::test_datefield_clean_failure[field0-None]",
"tests/test_fields.py::TestFields::test_datefield_clean_failure[field1-abc]",
"tests/test_fields.py::TestFields::test_datefield_clean_failure[field2-123]",
"tests/test_fields.py::TestFields::test_datefield_as_string[field0-value0-2013-11-24]",
"tests/test_fields.py::TestFields::test_timefield_1",
"tests/test_fields.py::TestFields::test_timefield_2",
"tests/test_fields.py::TestFields::test_timefield_as_string[field0-value0-12:44:12.000012]",
"tests/test_fields.py::TestFields::test_timefield_as_string[field1-value1-12:44:12.000012+00:00]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target0-18:43:00.000Z-expected0]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target1-18:43:00.000Z-expected1]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target2-value2-expected2]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target3-None-None]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target4-18:43:00.000Z-expected4]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target5-18:43:00.000Z-expected5]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target6-value6-expected6]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target7-18:43:00.000Z-expected7]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target8-18:43:00.000Z-expected8]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_valid_values[target9-value9-expected9]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_invalid_values[target0-None]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_invalid_values[target1-abc]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_invalid_values[target2-123]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_invalid_values[target3-abc]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_invalid_values[target4-123]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_invalid_values[target5-None]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_invalid_values[target6-abc]",
"tests/test_fields.py::TestFields::test_naivetimefield__clean_invalid_values[target7-123]",
"tests/test_fields.py::TestFields::test_naivetimefield__prepare[target0-value0-expected0]",
"tests/test_fields.py::TestFields::test_naivetimefield__prepare[target1-value1-expected1]",
"tests/test_fields.py::TestFields::test_datetimefield_1",
"tests/test_fields.py::TestFields::test_datetimefield_2",
"tests/test_fields.py::TestFields::test_datetimefield_as_string[field0-value0-2013-11-24T18:43:00+10:00]",
"tests/test_fields.py::TestFields::test_datetimefield_as_string[field1-value1-2013-11-24T18:43:00+00:00]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target0-2013-11-24T18:43:00.000Z-expected0]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target1-2013-11-24",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target2-value2-expected2]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target3-None-None]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target4-2013-11-24T18:43:00.000Z-expected4]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target5-2013-11-24",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target6-value6-expected6]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target7-2013-11-24T18:43:00.000Z-expected7]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target8-2013-11-24",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_valid_values[target9-value9-expected9]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_invalid_values[target0-None]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_invalid_values[target1-abc]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_invalid_values[target2-123]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_invalid_values[target3-abc]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_invalid_values[target4-123]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_invalid_values[target5-None]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_invalid_values[target6-abc]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__clean_invalid_values[target7-123]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__prepare[target0-value0-expected0]",
"tests/test_fields.py::TestFields::test_naivedatetimefield__prepare[target1-value1-expected1]",
"tests/test_fields.py::TestFields::test_httpdatetimefield_1",
"tests/test_fields.py::TestFields::test_httpdatetimefield_2",
"tests/test_fields.py::TestFields::test_httpdate_time_field__as_string",
"tests/test_fields.py::TestFields::test_timestampfield_1",
"tests/test_fields.py::TestFields::test_timestampfield_2",
"tests/test_fields.py::TestFields::test_timestampfield_3",
"tests/test_fields.py::TestFields::test_dictfield__where_null_is_false",
"tests/test_fields.py::TestFields::test_dictfield__where_null_is_true",
"tests/test_fields.py::TestFields::test_typedlistfield__where_null_is_false",
"tests/test_fields.py::TestFields::test_typedlistfield__where_null_is_true",
"tests/test_fields.py::TestFields::test_typed_list_field_dynamic_type_name",
"tests/test_fields.py::TestFields::test_typed_list_field__with_choices[target0-None]",
"tests/test_fields.py::TestFields::test_typed_list_field__with_choices[target1-expected1]",
"tests/test_fields.py::TestFields::test_typed_list_field__with_choices[target2-expected2]",
"tests/test_fields.py::TestFields::test_typeddictfield_1",
"tests/test_fields.py::TestFields::test_typeddictfield_2",
"tests/test_fields.py::TestFields::test_typeddictfield_3",
"tests/test_fields.py::TestFields::test_typeddictfield_nested_typed_array",
"tests/test_fields.py::TestFields::test_typeddictfield_validate",
"tests/test_fields.py::TestFields::test_typed_dict_field_dynamic_type_name",
"tests/test_fields.py::TestFields::test_valid_values[[email protected]@example.company]",
"tests/test_fields.py::TestFields::test_valid_values[field1-127.0.0.1-127.0.0.1]",
"tests/test_fields.py::TestFields::test_valid_values[field2-::1-::1]",
"tests/test_fields.py::TestFields::test_valid_values[field3-1:2:3:4:5:6:7:8-1:2:3:4:5:6:7:8]",
"tests/test_fields.py::TestFields::test_valid_values[field4-127.0.0.1-127.0.0.1]",
"tests/test_fields.py::TestFields::test_valid_values[field5-::1-::1]",
"tests/test_fields.py::TestFields::test_valid_values[field6-1:2:3:4:5:6:7:8-1:2:3:4:5:6:7:8]",
"tests/test_fields.py::TestFields::test_uuid_field_with_uuid_objects[value0]",
"tests/test_fields.py::TestFields::test_uuid_field_with_uuid_objects[value1]",
"tests/test_fields.py::TestFields::test_uuid_field_with_uuid_objects[value2]",
"tests/test_fields.py::TestFields::test_uuid_field_with_uuid_objects[value3]",
"tests/test_fields.py::TestFields::test_uuid_field_with_16_bytes_sequence[bytes-uuid1]",
"tests/test_fields.py::TestFields::test_uuid_field_with_16_bytes_sequence[bytes-uuid3]",
"tests/test_fields.py::TestFields::test_uuid_field_with_16_bytes_sequence[bytes-uuid4]",
"tests/test_fields.py::TestFields::test_uuid_field_with_16_bytes_sequence[bytes-uuid5]",
"tests/test_fields.py::TestFields::test_uuid_field_with_int[0]",
"tests/test_fields.py::TestFields::test_uuid_field_with_int[1]",
"tests/test_fields.py::TestFields::test_uuid_field_with_int[2]",
"tests/test_fields.py::TestFields::test_uuid_field_with_int[3]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_int[-1]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_int[-2]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_bytes[\\xac]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_bytes[\\xad]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_fields[value0]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_fields[value1]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_fields[value2]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_fields[value3]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_fields[value4]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_fields[value5]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_hex[sometext]",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_hex[01010101-0101-0101-0101-01010101010]",
"tests/test_fields.py::TestFields::test_uuid_field_non_str_value",
"tests/test_fields.py::TestFields::test_uuid_field_invalid_non_str_value",
"tests/test_fields.py::TestFields::test_uuid_field__none",
"tests/test_fields.py::TestFields::test_uuid_field__not_none"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-06 00:50:28+00:00
|
bsd-3-clause
| 5,090 |
|
python-odin__odinweb-11
|
diff --git a/odinweb/containers.py b/odinweb/containers.py
index 43622c4..975da81 100644
--- a/odinweb/containers.py
+++ b/odinweb/containers.py
@@ -274,6 +274,17 @@ class ApiInterfaceBase(ApiContainer):
"""
Handle an *un-handled* exception.
"""
+ # Let middleware attempt to handle exception
+ try:
+ for middleware in self.middleware.handle_500:
+ resource = middleware(request, exception)
+ if resource:
+ return resource
+
+ except Exception as ex: # noqa - This is a top level handler
+ exception = ex
+
+ # Fallback to generic error
logger.exception('Internal Server Error: %s', exception, extra={
'status_code': 500,
'request': request
@@ -343,7 +354,12 @@ class ApiInterfaceBase(ApiContainer):
# error processing, this often provides convenience features
# to aid in the debugging process.
raise
- resource = self.handle_500(request, e)
+
+ resource = None
+ # Fallback to the default handler
+ if resource is None:
+ resource = self.handle_500(request, e)
+
status = resource.status
if isinstance(status, HTTPStatus):
diff --git a/odinweb/data_structures.py b/odinweb/data_structures.py
index cd79032..3ec6db0 100644
--- a/odinweb/data_structures.py
+++ b/odinweb/data_structures.py
@@ -439,6 +439,14 @@ class MiddlewareList(list):
middleware = sort_by_priority(self, reverse=True)
return tuple(m.post_dispatch for m in middleware if hasattr(m, 'post_dispatch'))
+ @lazy_property
+ def handle_500(self):
+ """
+ List of handle-error methods from registered middleware.
+ """
+ middleware = sort_by_priority(self, reverse=True)
+ return tuple(m.handle_500 for m in middleware if hasattr(m, 'handle_500'))
+
@lazy_property
def post_swagger(self):
"""
|
python-odin/odinweb
|
cc4650b45a90fa41346ed53cf970cf0da414a44a
|
diff --git a/tests/test_containers.py b/tests/test_containers.py
index 475acd4..0be6c61 100644
--- a/tests/test_containers.py
+++ b/tests/test_containers.py
@@ -1,6 +1,7 @@
from __future__ import absolute_import
import pytest
+from odinweb.resources import Error
from odin.exceptions import ValidationError
from odinweb import api
@@ -302,6 +303,37 @@ class TestApiInterfaceBase(object):
with pytest.raises(ValueError):
target.dispatch(operation, MockRequest())
+ def test_dispatch__error_handled_by_middleware(self):
+ class ErrorMiddleware(object):
+ def handle_500(self, request, exception):
+ assert isinstance(exception, ValueError)
+ return Error.from_status(HTTPStatus.SEE_OTHER, 0,
+ "Quick over there...")
+
+ def callback(request):
+ raise ValueError()
+
+ target = containers.ApiInterfaceBase(middleware=[ErrorMiddleware()])
+ operation = Operation(callback)
+
+ actual = target.dispatch(operation, MockRequest())
+ assert actual.status == 303
+
+ def test_dispatch__error_handled_by_middleware_raises_exception(self):
+ class ErrorMiddleware(object):
+ def handle_500(self, request, exception):
+ assert isinstance(exception, ValueError)
+ raise ValueError
+
+ def callback(request):
+ raise ValueError()
+
+ target = containers.ApiInterfaceBase(middleware=[ErrorMiddleware()])
+ operation = Operation(callback)
+
+ actual = target.dispatch(operation, MockRequest())
+ assert actual.status == 500
+
def test_dispatch__encode_error_with_debug_enabled(self):
def callback(request):
raise api.ImmediateHttpResponse(ValueError, HTTPStatus.NOT_MODIFIED, {})
|
Added error hook for middleware
Allow middleware to catch errors.
Returning an explicit `True` indicates that the exception has been handled
|
0.0
|
cc4650b45a90fa41346ed53cf970cf0da414a44a
|
[
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__error_handled_by_middleware"
] |
[
"tests/test_containers.py::TestResourceApiMeta::test_empty_api",
"tests/test_containers.py::TestResourceApiMeta::test_normal_api",
"tests/test_containers.py::TestResourceApiMeta::test_sub_classed_api",
"tests/test_containers.py::TestResourceApi::test_api_name__default",
"tests/test_containers.py::TestResourceApi::test_api_name__custom",
"tests/test_containers.py::TestResourceApi::test_op_paths",
"tests/test_containers.py::TestApiContainer::test_options[options0-name-None]",
"tests/test_containers.py::TestApiContainer::test_options[options1-name-foo]",
"tests/test_containers.py::TestApiContainer::test_options[options2-path_prefix-value2]",
"tests/test_containers.py::TestApiContainer::test_options[options3-path_prefix-value3]",
"tests/test_containers.py::TestApiContainer::test_options[options4-path_prefix-value4]",
"tests/test_containers.py::TestApiContainer::test_op_paths",
"tests/test_containers.py::TestApiContainer::test_op_paths__no_sub_path",
"tests/test_containers.py::TestApiCollection::test_version_options[options0-1-v1-path_prefix0]",
"tests/test_containers.py::TestApiCollection::test_version_options[options1-2-v2-path_prefix1]",
"tests/test_containers.py::TestApiCollection::test_version_options[options2-3-version-3-path_prefix2]",
"tests/test_containers.py::TestApiCollection::test_register_operation",
"tests/test_containers.py::TestApiInterfaceBase::test_options[options0-api-False-path_prefix0]",
"tests/test_containers.py::TestApiInterfaceBase::test_options[options1-!api-False-path_prefix1]",
"tests/test_containers.py::TestApiInterfaceBase::test_options[options2-api-False-path_prefix2]",
"tests/test_containers.py::TestApiInterfaceBase::test_options[options3-api-True-path_prefix3]",
"tests/test_containers.py::TestApiInterfaceBase::test_init_non_absolute",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__invalid_headers[r0-422-Unprocessable",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__invalid_headers[r1-406-URI",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__invalid_headers[r2-405-Specified",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[error0-HTTPStatus.NOT_MODIFIED]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[error1-400]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[error2-400]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[NotImplementedError-501]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[ValueError-500]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[error5-500]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__with_middleware",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__error_with_debug_enabled",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__error_handled_by_middleware_raises_exception",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__encode_error_with_debug_enabled",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__http_response",
"tests/test_containers.py::TestApiInterfaceBase::test_op_paths",
"tests/test_containers.py::TestApiInterfaceBase::test_op_paths__collate_methods"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-08-21 14:23:31+00:00
|
bsd-3-clause
| 5,091 |
|
python-tap__tappy-112
|
diff --git a/AUTHORS b/AUTHORS
index e87e3b8..3735496 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -3,6 +3,7 @@ tappy was originally created by Matt Layman.
Contributors
------------
+* Adeodato Simó
* Andrew McNamara
* Chris Clarke
* Erik Cederstrand
diff --git a/docs/releases.rst b/docs/releases.rst
index dd80f97..7f708c7 100644
--- a/docs/releases.rst
+++ b/docs/releases.rst
@@ -5,6 +5,7 @@ Version 3.1, To Be Released
---------------------------
* Add support for Python 3.8.
+* Fix parsing of multi-line strings in YAML blocks (#111)
Version 3.0, Released January 10, 2020
--------------------------------------
diff --git a/tap/parser.py b/tap/parser.py
index 637436b..2f28bd8 100644
--- a/tap/parser.py
+++ b/tap/parser.py
@@ -181,7 +181,8 @@ WARNING: Optional imports not found, TAP 13 output will be
try:
next(fh)
while indent_match.match(fh.peek()):
- raw_yaml.append(next(fh).replace(indent, "", 1))
+ yaml_line = next(fh).replace(indent, "", 1)
+ raw_yaml.append(yaml_line.rstrip("\n"))
# check for the end and stop adding yaml if encountered
if self.yaml_block_end.match(fh.peek()):
next(fh)
|
python-tap/tappy
|
015c21c1a98b88f23844a44e346604f2398b11d5
|
diff --git a/tap/tests/test_parser.py b/tap/tests/test_parser.py
index 431297a..ac8f3d3 100644
--- a/tap/tests/test_parser.py
+++ b/tap/tests/test_parser.py
@@ -348,7 +348,12 @@ class TestParser(unittest.TestCase):
got:
- foo
expect:
- - bar"""
+ - bar
+ output: |-
+ a multiline string
+ must be handled properly
+ even with | pipes
+ | here > and: there"""
)
parser = Parser()
lines = []
@@ -358,20 +363,21 @@ class TestParser(unittest.TestCase):
if have_yaml:
converted_yaml = yaml.safe_load(
- u"""
+ u'''
message: test
severity: fail
data:
got:
- foo
expect:
- - bar"""
+ - bar
+ output: "a multiline string\\nmust be handled properly\\neven with | pipes\\n| here > and: there"'''
)
self.assertEqual(3, len(lines))
self.assertEqual(13, lines[0].version)
self.assertEqual(converted_yaml, lines[2].yaml_block)
else:
- self.assertEqual(11, len(lines))
+ self.assertEqual(16, len(lines))
self.assertEqual(13, lines[0].version)
for l in list(range(3, 11)):
self.assertEqual("unknown", lines[l].category)
|
Additional newlines added in YAML blocks for multi-line strings
Hello!
I've observed that `_extract_yaml_block()` performs `"\n".join(raw_yaml)` without having stripped the newline character in each possible line, resulting in unwanted empty lines when parsing multi-line strings in YAML blocks.
I'll give an example. With this file:
```python
#!/usr/bin/python3
import tap.parser
tap_input = """TAP version 13
1..2
ok 1 A passing test
---
message: test
severity: fail
output: |+
this is a multiline
string but with tap
somehow blank lines
are added to it.
"""
parser = tap.parser.Parser()
for i, l in enumerate(parser.parse_text(tap_input)):
if i == 2:
print("{!r}".format(l.yaml_block["output"].splitlines()))
```
The output is:
```
['', 'this is a multiline', '', 'string but with tap', '', 'somehow blank lines', '', 'are added to it.']
```
Where as I expected:
```
['this is a multiline', 'string but with tap', 'somehow blank lines', 'are added to it.']
```
I will submit a PR shortly.
|
0.0
|
015c21c1a98b88f23844a44e346604f2398b11d5
|
[
"tap/tests/test_parser.py::TestParser::test_parses_yaml_more_complex"
] |
[
"tap/tests/test_parser.py::TestParser::test_parses_yaml",
"tap/tests/test_parser.py::TestParser::test_finds_plan",
"tap/tests/test_parser.py::TestParser::test_parses_mixed",
"tap/tests/test_parser.py::TestParser::test_parses_text",
"tap/tests/test_parser.py::TestParser::test_malformed_yaml",
"tap/tests/test_parser.py::TestParser::test_diagnostic_line",
"tap/tests/test_parser.py::TestParser::test_finds_ok",
"tap/tests/test_parser.py::TestParser::test_parse_empty_file",
"tap/tests/test_parser.py::TestParser::test_finds_plan_with_skip",
"tap/tests/test_parser.py::TestParser::test_finds_version",
"tap/tests/test_parser.py::TestParser::test_after_hash_is_not_description",
"tap/tests/test_parser.py::TestParser::test_parses_yaml_no_end",
"tap/tests/test_parser.py::TestParser::test_finds_directive",
"tap/tests/test_parser.py::TestParser::test_parses_file",
"tap/tests/test_parser.py::TestParser::test_finds_description",
"tap/tests/test_parser.py::TestParser::test_finds_not_ok",
"tap/tests/test_parser.py::TestParser::test_finds_skip",
"tap/tests/test_parser.py::TestParser::test_parses_stdin",
"tap/tests/test_parser.py::TestParser::test_ignores_plan_with_any_non_skip_directive",
"tap/tests/test_parser.py::TestParser::test_finds_number",
"tap/tests/test_parser.py::TestParser::test_parses_yaml_no_start",
"tap/tests/test_parser.py::TestParser::test_parses_yaml_no_association",
"tap/tests/test_parser.py::TestParser::test_errors_on_old_version",
"tap/tests/test_parser.py::TestParser::test_finds_todo",
"tap/tests/test_parser.py::TestParser::test_bail_out_line",
"tap/tests/test_parser.py::TestParser::test_unrecognizable_line"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-09 16:50:51+00:00
|
bsd-2-clause
| 5,092 |
|
python-tap__tappy-92
|
diff --git a/AUTHORS b/AUTHORS
index 566404e..06d46c5 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -5,6 +5,7 @@ Contributors
* Andrew McNamara
* Chris Clarke
+* Erik Cederstrand
* Marc Abramowitz
* Mark E. Hamilton
* Matt Layman
diff --git a/docs/releases.rst b/docs/releases.rst
index b04ab19..ee84c7e 100644
--- a/docs/releases.rst
+++ b/docs/releases.rst
@@ -5,6 +5,7 @@ Version 3.0, To Be Released
---------------------------
* Drop support for Python 2 (it is end-of-life).
+* Add support for subtests.
Version 2.6.2, Released October 20, 2019
----------------------------------------
diff --git a/tap/runner.py b/tap/runner.py
index 94134e1..10e8510 100644
--- a/tap/runner.py
+++ b/tap/runner.py
@@ -17,6 +17,18 @@ class TAPTestResult(TextTestResult):
def __init__(self, stream, descriptions, verbosity):
super(TAPTestResult, self).__init__(stream, descriptions, verbosity)
+ def addSubTest(self, test, subtest, err):
+ super(TAPTestResult, self).addSubTest(test, subtest, err)
+ if err is not None:
+ diagnostics = formatter.format_exception(err)
+ self.tracker.add_not_ok(
+ self._cls_name(test),
+ self._description(subtest),
+ diagnostics=diagnostics,
+ )
+ else:
+ self.tracker.add_ok(self._cls_name(test), self._description(subtest))
+
def stopTestRun(self):
"""Once the test run is complete, generate each of the TAP files."""
super(TAPTestResult, self).stopTestRun()
|
python-tap/tappy
|
1c079e9ad6aaecaefcfc65d306417b28bce2ce06
|
diff --git a/tap/tests/test_result.py b/tap/tests/test_result.py
index 06fb7e1..b5c1c9a 100644
--- a/tap/tests/test_result.py
+++ b/tap/tests/test_result.py
@@ -1,7 +1,9 @@
# Copyright (c) 2019, Matt Layman and contributors
+import contextlib
import os
import unittest
+import unittest.case
from tap.i18n import _
from tap.runner import TAPTestResult
@@ -13,6 +15,14 @@ class FakeTestCase(unittest.TestCase):
def runTest(self):
pass
+ @contextlib.contextmanager
+ def subTest(self, *args, **kwargs):
+ try:
+ self._subtest = unittest.case._SubTest(self, object(), {})
+ yield
+ finally:
+ self._subtest = None
+
def __call__(self, result):
pass
@@ -70,3 +80,25 @@ class TestTAPTestResult(TestCase):
self.assertEqual(
line.directive.text, "TODO {}".format(_("(unexpected success)"))
)
+
+ def test_adds_subtest_success(self):
+ """Test that the runner handles subtest success results."""
+ result = self._make_one()
+ test = FakeTestCase()
+ with test.subTest():
+ result.addSubTest(test, test._subtest, None)
+ line = result.tracker._test_cases["FakeTestCase"][0]
+ self.assertTrue(line.ok)
+
+ def test_adds_subtest_failure(self):
+ """Test that the runner handles subtest failure results."""
+ result = self._make_one()
+ # Python 3 does some extra testing in unittest on exceptions so fake
+ # the cause as if it were raised.
+ ex = Exception()
+ ex.__cause__ = None
+ test = FakeTestCase()
+ with test.subTest():
+ result.addSubTest(test, test._subtest, (ex.__class__, ex, None))
+ line = result.tracker._test_cases["FakeTestCase"][0]
+ self.assertFalse(line.ok)
|
Sub tests are not included
If the unittests include [subtests](https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests) the results of these subtests are not picked up.
Also, if the test class contains only failing subtests, the tap file may not be generated at all.
|
0.0
|
1c079e9ad6aaecaefcfc65d306417b28bce2ce06
|
[
"tap/tests/test_result.py::TestTAPTestResult::test_adds_subtest_failure",
"tap/tests/test_result.py::TestTAPTestResult::test_adds_subtest_success"
] |
[
"tap/tests/test_result.py::FakeTestCase::runTest",
"tap/tests/test_result.py::TestTAPTestResult::test_adds_error",
"tap/tests/test_result.py::TestTAPTestResult::test_adds_expected_failure",
"tap/tests/test_result.py::TestTAPTestResult::test_adds_failure",
"tap/tests/test_result.py::TestTAPTestResult::test_adds_skip",
"tap/tests/test_result.py::TestTAPTestResult::test_adds_success",
"tap/tests/test_result.py::TestTAPTestResult::test_adds_unexpected_success"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-12-09 10:52:54+00:00
|
bsd-2-clause
| 5,093 |
|
python-trio__trio-1129
|
diff --git a/docs-requirements.txt b/docs-requirements.txt
index 02ecb74a..d1466815 100644
--- a/docs-requirements.txt
+++ b/docs-requirements.txt
@@ -11,7 +11,7 @@ babel==2.7.0 # via sphinx
certifi==2019.6.16 # via requests
chardet==3.0.4 # via requests
click==7.0 # via towncrier
-docutils==0.14 # via sphinx
+docutils==0.15 # via sphinx
idna==2.8
imagesize==1.1.0 # via sphinx
immutables==0.9
@@ -21,7 +21,7 @@ markupsafe==1.1.1 # via jinja2
outcome==1.0.0
packaging==19.0 # via sphinx
pygments==2.4.2 # via sphinx
-pyparsing==2.4.0 # via packaging
+pyparsing==2.4.1 # via packaging
pytz==2019.1 # via babel
requests==2.22.0 # via sphinx
six==1.12.0 # via packaging
diff --git a/docs/source/reference-hazmat.rst b/docs/source/reference-hazmat.rst
index 6cad8476..e12d3601 100644
--- a/docs/source/reference-hazmat.rst
+++ b/docs/source/reference-hazmat.rst
@@ -174,6 +174,26 @@ All environments provide the following functions:
yourself afterwards.
+Unix-specific API
+-----------------
+
+`FdStream` supports wrapping Unix files (such as a pipe or TTY) as
+a stream.
+
+If you have two different file descriptors for sending and receiving,
+and want to bundle them together into a single bidirectional
+`~trio.abc.Stream`, then use `trio.StapledStream`::
+
+ bidirectional_stream = trio.StapledStream(
+ trio.hazmat.FdStream(write_fd),
+ trio.hazmat.FdStream(read_fd)
+ )
+
+.. autoclass:: FdStream
+ :show-inheritance:
+ :members:
+
+
Kqueue-specific API
-------------------
diff --git a/newsfragments/829.feature.rst b/newsfragments/829.feature.rst
new file mode 100644
index 00000000..34090857
--- /dev/null
+++ b/newsfragments/829.feature.rst
@@ -0,0 +1,1 @@
+Add `trio.hazmat.FdStream` for wrapping a Unix file descriptor as a `~trio.abc.Stream`.
diff --git a/trio/_subprocess.py b/trio/_subprocess.py
index ae530e3a..f9bc0647 100644
--- a/trio/_subprocess.py
+++ b/trio/_subprocess.py
@@ -1,9 +1,8 @@
import os
-import select
import subprocess
-from functools import partial
+from typing import Optional
-from ._abc import AsyncResource
+from ._abc import AsyncResource, SendStream, ReceiveStream
from ._highlevel_generic import StapledStream
from ._sync import Lock
from ._subprocess_platform import (
@@ -101,9 +100,10 @@ class Process(AsyncResource):
.format(key)
)
- self.stdin = None
- self.stdout = None
- self.stderr = None
+ self.stdin = None # type: Optional[SendStream]
+ self.stdout = None # type: Optional[ReceiveStream]
+ self.stderr = None # type: Optional[ReceiveStream]
+ self.stdio = None # type: Optional[StapledStream]
if os.name == "posix":
if isinstance(command, str) and not options.get("shell"):
@@ -153,8 +153,6 @@ class Process(AsyncResource):
if self.stdin is not None and self.stdout is not None:
self.stdio = StapledStream(self.stdin, self.stdout)
- else:
- self.stdio = None
self.args = self._proc.args
self.pid = self._proc.pid
diff --git a/trio/_subprocess_platform/__init__.py b/trio/_subprocess_platform/__init__.py
index 1507ec12..b1db8499 100644
--- a/trio/_subprocess_platform/__init__.py
+++ b/trio/_subprocess_platform/__init__.py
@@ -67,15 +67,15 @@ except ImportError as ex: # pragma: no cover
try:
if os.name == "posix":
- from .._unix_pipes import PipeSendStream, PipeReceiveStream
+ from ..hazmat import FdStream
def create_pipe_to_child_stdin(): # noqa: F811
rfd, wfd = os.pipe()
- return PipeSendStream(wfd), rfd
+ return FdStream(wfd), rfd
def create_pipe_from_child_output(): # noqa: F811
rfd, wfd = os.pipe()
- return PipeReceiveStream(rfd), wfd
+ return FdStream(rfd), wfd
elif os.name == "nt":
from .._windows_pipes import PipeSendStream, PipeReceiveStream
diff --git a/trio/_unix_pipes.py b/trio/_unix_pipes.py
index 7cd205e9..b212b2a9 100644
--- a/trio/_unix_pipes.py
+++ b/trio/_unix_pipes.py
@@ -1,12 +1,16 @@
-import fcntl
import os
import errno
-from ._abc import SendStream, ReceiveStream
+from ._abc import Stream
from ._util import ConflictDetector
import trio
+if os.name != "posix":
+ # We raise an error here rather than gating the import in hazmat.py
+ # in order to keep jedi static analysis happy.
+ raise ImportError
+
class _FdHolder:
# This class holds onto a raw file descriptor, in non-blocking mode, and
@@ -33,9 +37,9 @@ class _FdHolder:
if not isinstance(fd, int):
raise TypeError("file descriptor must be an int")
self.fd = fd
- # Flip the fd to non-blocking mode
- flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
- fcntl.fcntl(self.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
+ # Store original state, and ensure non-blocking mode is enabled
+ self._original_is_blocking = os.get_blocking(fd)
+ os.set_blocking(fd, False)
@property
def closed(self):
@@ -53,6 +57,7 @@ class _FdHolder:
return
fd = self.fd
self.fd = -1
+ os.set_blocking(fd, self._original_is_blocking)
os.close(fd)
def __del__(self):
@@ -65,21 +70,53 @@ class _FdHolder:
await trio.hazmat.checkpoint()
-class PipeSendStream(SendStream):
- """Represents a send stream over an os.pipe object."""
+class FdStream(Stream):
+ """
+ Represents a stream given the file descriptor to a pipe, TTY, etc.
+
+ *fd* must refer to a file that is open for reading and/or writing and
+ supports non-blocking I/O (pipes and TTYs will work, on-disk files probably
+ not). The returned stream takes ownership of the fd, so closing the stream
+ will close the fd too. As with `os.fdopen`, you should not directly use
+ an fd after you have wrapped it in a stream using this function.
+
+ To be used as a Trio stream, an open file must be placed in non-blocking
+ mode. Unfortunately, this impacts all I/O that goes through the
+ underlying open file, including I/O that uses a different
+ file descriptor than the one that was passed to Trio. If other threads
+ or processes are using file descriptors that are related through `os.dup`
+ or inheritance across `os.fork` to the one that Trio is using, they are
+ unlikely to be prepared to have non-blocking I/O semantics suddenly
+ thrust upon them. For example, you can use ``FdStream(os.dup(0))`` to
+ obtain a stream for reading from standard input, but it is only safe to
+ do so with heavy caveats: your stdin must not be shared by any other
+ processes and you must not make any calls to synchronous methods of
+ `sys.stdin` until the stream returned by `FdStream` is closed. See
+ `issue #174 <https://github.com/python-trio/trio/issues/174>`__ for a
+ discussion of the challenges involved in relaxing this restriction.
+
+ Args:
+ fd (int): The fd to be wrapped.
+
+ Returns:
+ A new `FdStream` object.
+ """
def __init__(self, fd: int):
self._fd_holder = _FdHolder(fd)
- self._conflict_detector = ConflictDetector(
- "another task is using this pipe"
+ self._send_conflict_detector = ConflictDetector(
+ "another task is using this stream for send"
+ )
+ self._receive_conflict_detector = ConflictDetector(
+ "another task is using this stream for receive"
)
async def send_all(self, data: bytes):
- with self._conflict_detector:
+ with self._send_conflict_detector:
# have to check up front, because send_all(b"") on a closed pipe
# should raise
if self._fd_holder.closed:
- raise trio.ClosedResourceError("this pipe was already closed")
+ raise trio.ClosedResourceError("file was already closed")
await trio.hazmat.checkpoint()
length = len(data)
# adapted from the SocketStream code
@@ -94,15 +131,15 @@ class PipeSendStream(SendStream):
except OSError as e:
if e.errno == errno.EBADF:
raise trio.ClosedResourceError(
- "this pipe was closed"
+ "file was already closed"
) from None
else:
raise trio.BrokenResourceError from e
async def wait_send_all_might_not_block(self) -> None:
- with self._conflict_detector:
+ with self._send_conflict_detector:
if self._fd_holder.closed:
- raise trio.ClosedResourceError("this pipe was already closed")
+ raise trio.ClosedResourceError("file was already closed")
try:
await trio.hazmat.wait_writable(self._fd_holder.fd)
except BrokenPipeError as e:
@@ -110,24 +147,8 @@ class PipeSendStream(SendStream):
# of sending, which is annoying
raise trio.BrokenResourceError from e
- async def aclose(self):
- await self._fd_holder.aclose()
-
- def fileno(self):
- return self._fd_holder.fd
-
-
-class PipeReceiveStream(ReceiveStream):
- """Represents a receive stream over an os.pipe object."""
-
- def __init__(self, fd: int):
- self._fd_holder = _FdHolder(fd)
- self._conflict_detector = ConflictDetector(
- "another task is using this pipe"
- )
-
async def receive_some(self, max_bytes: int) -> bytes:
- with self._conflict_detector:
+ with self._receive_conflict_detector:
if not isinstance(max_bytes, int):
raise TypeError("max_bytes must be integer >= 1")
@@ -143,7 +164,7 @@ class PipeReceiveStream(ReceiveStream):
except OSError as e:
if e.errno == errno.EBADF:
raise trio.ClosedResourceError(
- "this pipe was closed"
+ "file was already closed"
) from None
else:
raise trio.BrokenResourceError from e
diff --git a/trio/hazmat.py b/trio/hazmat.py
index 69070a79..5fe32c03 100644
--- a/trio/hazmat.py
+++ b/trio/hazmat.py
@@ -3,6 +3,7 @@ This namespace represents low-level functionality not intended for daily use,
but useful for extending Trio's functionality.
"""
+import os
import sys
# This is the union of a subset of trio/_core/ and some things from trio/*.py.
@@ -22,6 +23,12 @@ from ._core import (
spawn_system_task, wait_readable, wait_writable, notify_closing
)
+# Unix-specific symbols
+try:
+ from ._unix_pipes import FdStream
+except ImportError:
+ pass
+
# Kqueue-specific symbols
try:
from ._core import (
|
python-trio/trio
|
906456b29b40a571964b4b32d0f59cebc64b651e
|
diff --git a/test-requirements.txt b/test-requirements.txt
index 5aab7fc4..3237f14f 100644
--- a/test-requirements.txt
+++ b/test-requirements.txt
@@ -26,7 +26,7 @@ isort==4.3.21 # via pylint
jedi==0.14.1
lazy-object-proxy==1.4.1 # via astroid
mccabe==0.6.1 # via flake8, pylint
-more-itertools==7.1.0 # via pytest
+more-itertools==7.2.0 # via pytest
outcome==1.0.0
packaging==19.0 # via pytest
parso==0.5.1 # via jedi
@@ -42,7 +42,7 @@ pyflakes==2.1.1 # via flake8
pygments==2.4.2 # via ipython
pylint==2.3.1
pyopenssl==19.0.0
-pyparsing==2.4.0 # via packaging
+pyparsing==2.4.1 # via packaging
pytest-cov==2.7.1
pytest==5.0.1
six==1.12.0 # via astroid, cryptography, packaging, prompt-toolkit, pyopenssl, traitlets
diff --git a/trio/tests/test_unix_pipes.py b/trio/tests/test_unix_pipes.py
index 7728a57f..46f28d54 100644
--- a/trio/tests/test_unix_pipes.py
+++ b/trio/tests/test_unix_pipes.py
@@ -11,14 +11,17 @@ from ..testing import wait_all_tasks_blocked, check_one_way_stream
posix = os.name == "posix"
pytestmark = pytest.mark.skipif(not posix, reason="posix only")
if posix:
- from .._unix_pipes import PipeSendStream, PipeReceiveStream
+ from .._unix_pipes import FdStream
+else:
+ with pytest.raises(ImportError):
+ from .._unix_pipes import FdStream
# Have to use quoted types so import doesn't crash on windows
-async def make_pipe() -> "Tuple[PipeSendStream, PipeReceiveStream]":
+async def make_pipe() -> "Tuple[FdStream, FdStream]":
"""Makes a new pair of pipes."""
(r, w) = os.pipe()
- return PipeSendStream(w), PipeReceiveStream(r)
+ return FdStream(w), FdStream(r)
async def make_clogged_pipe():
@@ -49,7 +52,7 @@ async def make_clogged_pipe():
async def test_send_pipe():
r, w = os.pipe()
- async with PipeSendStream(w) as send:
+ async with FdStream(w) as send:
assert send.fileno() == w
await send.send_all(b"123")
assert (os.read(r, 8)) == b"123"
@@ -59,7 +62,7 @@ async def test_send_pipe():
async def test_receive_pipe():
r, w = os.pipe()
- async with PipeReceiveStream(r) as recv:
+ async with FdStream(r) as recv:
assert (recv.fileno()) == r
os.write(w, b"123")
assert (await recv.receive_some(8)) == b"123"
@@ -93,10 +96,10 @@ async def test_pipes_combined():
async def test_pipe_errors():
with pytest.raises(TypeError):
- PipeReceiveStream(None)
+ FdStream(None)
with pytest.raises(ValueError):
- await PipeReceiveStream(0).receive_some(0)
+ await FdStream(0).receive_some(0)
async def test_del():
@@ -146,7 +149,7 @@ async def test_misdirected_aclose_regression():
if r2_fd != old_r_fd: # pragma: no cover
os.dup2(r2_fd, old_r_fd)
os.close(r2_fd)
- async with PipeReceiveStream(old_r_fd) as r2:
+ async with FdStream(old_r_fd) as r2:
assert r2.fileno() == old_r_fd
# And now set up a background task that's working on the new receive
|
Should we somehow expose Pipe*Stream on Unix, and if so, how?
We have `PipeReceiveStream` and `PipeSendStream` classes on Unix, that are currently not exposed publicly; they're only used internally for subprocesses.
The actual code is a pretty generic building block: they can wrap around any Unix file-descriptor that supports non-blocking mode. So they could potentially be useful for talking to [FIFOs](http://man7.org/linux/man-pages/man7/fifo.7.html), TTYs, stdio streams (#174), etc.
Should we expose them more directly? If so, how? In `trio.hazmat`, with some sort of [`os.fdopen`](https://docs.python.org/3/library/os.html#os.fdopen) equivalent?
If we do we'll want to think through the ownership semantics: should they take ownership of a passed in fd, or should they dup it?
Also, they should restore the fd's blocking/non-blocking state before closing it.
|
0.0
|
906456b29b40a571964b4b32d0f59cebc64b651e
|
[
"trio/tests/test_unix_pipes.py::test_send_pipe",
"trio/tests/test_unix_pipes.py::test_receive_pipe",
"trio/tests/test_unix_pipes.py::test_pipes_combined",
"trio/tests/test_unix_pipes.py::test_pipe_errors",
"trio/tests/test_unix_pipes.py::test_del",
"trio/tests/test_unix_pipes.py::test_async_with",
"trio/tests/test_unix_pipes.py::test_misdirected_aclose_regression",
"trio/tests/test_unix_pipes.py::test_close_at_bad_time_for_receive_some",
"trio/tests/test_unix_pipes.py::test_close_at_bad_time_for_send_all",
"trio/tests/test_unix_pipes.py::test_bizarro_OSError_from_receive",
"trio/tests/test_unix_pipes.py::test_pipe_fully"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-06-27 12:28:09+00:00
|
mit
| 5,094 |
|
python-trio__trio-1527
|
diff --git a/newsfragments/1526.bugfix.rst b/newsfragments/1526.bugfix.rst
new file mode 100644
index 00000000..02e1d37c
--- /dev/null
+++ b/newsfragments/1526.bugfix.rst
@@ -0,0 +1,1 @@
+Calling `open_signal_receiver` with no arguments used to succeed without listening for any signals. This was confusing, so now it raises TypeError instead.
diff --git a/trio/_signals.py b/trio/_signals.py
index aca23dda..cee3b7db 100644
--- a/trio/_signals.py
+++ b/trio/_signals.py
@@ -129,6 +129,8 @@ def open_signal_receiver(*signals):
signals: the signals to listen for.
Raises:
+ TypeError: if no signals were provided.
+
RuntimeError: if you try to use this anywhere except Python's main
thread. (This is a Python limitation.)
@@ -144,6 +146,9 @@ def open_signal_receiver(*signals):
reload_configuration()
"""
+ if not signals:
+ raise TypeError("No signals were provided")
+
if not is_main_thread():
raise RuntimeError(
"Sorry, open_signal_receiver is only possible when running in "
|
python-trio/trio
|
fa4ded772e3bc0b26e85c4e5deffabad1b257c01
|
diff --git a/trio/tests/test_signals.py b/trio/tests/test_signals.py
index 7ae93040..20821b40 100644
--- a/trio/tests/test_signals.py
+++ b/trio/tests/test_signals.py
@@ -41,6 +41,12 @@ async def test_open_signal_receiver_restore_handler_after_one_bad_signal():
assert signal.getsignal(signal.SIGILL) is orig
+async def test_open_signal_receiver_empty_fail():
+ with pytest.raises(TypeError, match="No signals were provided"):
+ with open_signal_receiver():
+ pass
+
+
async def test_open_signal_receiver_restore_handler_after_duplicate_signal():
orig = signal.getsignal(signal.SIGILL)
with open_signal_receiver(signal.SIGILL, signal.SIGILL):
|
trio.open_signal_receiver should give an error if no arguments are passed
User confusion spotted in the wild: https://gitter.im/python-trio/general?at=5ebfa9d613878c30b581b9fe
|
0.0
|
fa4ded772e3bc0b26e85c4e5deffabad1b257c01
|
[
"trio/tests/test_signals.py::test_open_signal_receiver_empty_fail"
] |
[
"trio/tests/test_signals.py::test_open_signal_receiver",
"trio/tests/test_signals.py::test_open_signal_receiver_restore_handler_after_one_bad_signal",
"trio/tests/test_signals.py::test_open_signal_receiver_restore_handler_after_duplicate_signal",
"trio/tests/test_signals.py::test_catch_signals_wrong_thread",
"trio/tests/test_signals.py::test_open_signal_receiver_conflict",
"trio/tests/test_signals.py::test_open_signal_receiver_no_starvation",
"trio/tests/test_signals.py::test_catch_signals_race_condition_on_exit"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_added_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-16 09:27:51+00:00
|
mit
| 5,095 |
|
python-trio__trio-1639
|
diff --git a/newsfragments/1638.fix.rst b/newsfragments/1638.fix.rst
new file mode 100644
index 00000000..6c6a9a6a
--- /dev/null
+++ b/newsfragments/1638.fix.rst
@@ -0,0 +1,1 @@
+The thread cache didn't release its reference to the previous job.
diff --git a/trio/_core/_thread_cache.py b/trio/_core/_thread_cache.py
index 8faf5543..ae5e8450 100644
--- a/trio/_core/_thread_cache.py
+++ b/trio/_core/_thread_cache.py
@@ -69,6 +69,8 @@ class WorkerThread:
# instead of spawning a new thread.
self._thread_cache._idle_workers[self] = None
deliver(result)
+ del fn
+ del deliver
else:
# Timeout acquiring lock, so we can probably exit. But,
# there's a race condition: we might be assigned a job *just*
|
python-trio/trio
|
e444094a262f69af6a16b60fa59a2ab53316e5ce
|
diff --git a/trio/_core/tests/test_thread_cache.py b/trio/_core/tests/test_thread_cache.py
index f19ac1d4..0f6e0a07 100644
--- a/trio/_core/tests/test_thread_cache.py
+++ b/trio/_core/tests/test_thread_cache.py
@@ -4,7 +4,7 @@ from queue import Queue
import time
import sys
-from .tutil import slow
+from .tutil import slow, gc_collect_harder
from .. import _thread_cache
from .._thread_cache import start_thread_soon, ThreadCache
@@ -25,6 +25,29 @@ def test_thread_cache_basics():
outcome.unwrap()
+def test_thread_cache_deref():
+ res = [False]
+
+ class del_me:
+ def __call__(self):
+ return 42
+
+ def __del__(self):
+ res[0] = True
+
+ q = Queue()
+
+ def deliver(outcome):
+ q.put(outcome)
+
+ start_thread_soon(del_me(), deliver)
+ outcome = q.get()
+ assert outcome.unwrap() == 42
+
+ gc_collect_harder()
+ assert res[0]
+
+
@slow
def test_spawning_new_thread_from_deliver_reuses_starting_thread():
# We know that no-one else is using the thread cache, so if we keep
|
to_thread.run_sync() foils meta-class destructors
Invoking `to_thread.run_sync()` seems to prevent meta-class destructors of completely unrelated classes from being called on shutdown.
```python
import trio
class deltype(type):
def __del__(self):
print(f"{self.__name__} class deleted")
Test = deltype("Test", (object,), {})
async def async_main():
await trio.to_thread.run_sync(lambda: print('hi'))
await trio.sleep(0)
trio.run(async_main)
```
expected output:
```
hi
Test class deleted
```
actual output:
```
hi
```
if the `run_sync()` is commented out, the meta-class destructor is called as expected:
```
Test class deleted
```
|
0.0
|
e444094a262f69af6a16b60fa59a2ab53316e5ce
|
[
"trio/_core/tests/test_thread_cache.py::test_thread_cache_deref"
] |
[
"trio/_core/tests/test_thread_cache.py::test_thread_cache_basics",
"trio/_core/tests/test_thread_cache.py::test_spawning_new_thread_from_deliver_reuses_starting_thread",
"trio/_core/tests/test_thread_cache.py::test_idle_threads_exit"
] |
{
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-06-22 12:51:53+00:00
|
mit
| 5,096 |
|
python-trio__trio-2475
|
diff --git a/newsfragments/1810.feature.rst b/newsfragments/1810.feature.rst
new file mode 100644
index 00000000..a2599d32
--- /dev/null
+++ b/newsfragments/1810.feature.rst
@@ -0,0 +1,1 @@
+`trio.socket.socket` now prints the address it tried to connect to upon failure.
diff --git a/trio/_socket.py b/trio/_socket.py
index bcff1ee9..8bfa6d26 100644
--- a/trio/_socket.py
+++ b/trio/_socket.py
@@ -688,7 +688,7 @@ class _SocketType(SocketType):
# Okay, the connect finished, but it might have failed:
err = self._sock.getsockopt(_stdlib_socket.SOL_SOCKET, _stdlib_socket.SO_ERROR)
if err != 0:
- raise OSError(err, "Error in connect: " + os.strerror(err))
+ raise OSError(err, f"Error connecting to {address}: {os.strerror(err)}")
################################################################
# recv
|
python-trio/trio
|
ce4c99e696a516db40b55fb076deca2e586626cf
|
diff --git a/trio/tests/test_socket.py b/trio/tests/test_socket.py
index 1fa3721f..ea5e48fe 100644
--- a/trio/tests/test_socket.py
+++ b/trio/tests/test_socket.py
@@ -723,6 +723,16 @@ async def test_SocketType_connect_paths():
await sock.connect(("127.0.0.1", 2))
+# Fix issue #1810
+async def test_address_in_socket_error():
+ address = "127.0.0.1"
+ with tsocket.socket() as sock:
+ try:
+ await sock.connect((address, 2))
+ except OSError as e:
+ assert any(address in str(arg) for arg in e.args)
+
+
async def test_resolve_address_exception_in_connect_closes_socket():
# Here we are testing issue 247, any cancellation will leave the socket closed
with _core.CancelScope() as cancel_scope:
|
Improve `start_soon` and `connection failed` error messages
Given …
```
Traceback (most recent call last):
File "./test", line 210, in main
tg.start_soon(s.run)
File "/home/smurf/src/Mudlet/test/e2e/venv/lib/python3.8/site-packages/trio/_core/_run.py", line 983, in start_soon
GLOBAL_RUN_CONTEXT.runner.spawn_impl(async_fn, args, self, name)
File "/home/smurf/src/Mudlet/test/e2e/venv/lib/python3.8/site-packages/trio/_core/_run.py", line 1432, in spawn_impl
coro = coroutine_or_error(async_fn, *args)
File "/home/smurf/src/Mudlet/test/e2e/venv/lib/python3.8/site-packages/trio/_util.py", line 108, in coroutine_or_error
coro = async_fn(*args)
TypeError: run() missing 1 required positional argument: 'evt'
```
… and the fact that I have approx 1337 classes (I exaggerate but slightly) whose `run` methods want an `evt` parameter, it'd be nice to see the qualified name of the thing. It'd be even nicer to see who tried to call it, but oh well.
Given the fact that my server connects to 4781 different remote systems (this however is an understatement),
```
Traceback (most recent call last):
File "/home/smurf/src/Mudlet/test/e2e/venv/lib/python3.8/site-packages/trio/_highlevel_open_tcp_stream.py", line 332, in attempt_connect
await sock.connect(sockaddr)
File "/home/smurf/src/Mudlet/test/e2e/venv/lib/python3.8/site-packages/trio/_socket.py", line 682, in connect
raise OSError(err, "Error in connect: " + os.strerror(err))
ConnectionRefusedError: [Errno 111] Error in connect: Connection refused
```
really should print the actual address it tried to talk to – instead of repeating itself.
|
0.0
|
ce4c99e696a516db40b55fb076deca2e586626cf
|
[
"trio/tests/test_socket.py::test_address_in_socket_error"
] |
[
"trio/tests/test_socket.py::test__try_sync",
"trio/tests/test_socket.py::test_socket_has_some_reexports",
"trio/tests/test_socket.py::test_getaddrinfo",
"trio/tests/test_socket.py::test_getnameinfo",
"trio/tests/test_socket.py::test_from_stdlib_socket",
"trio/tests/test_socket.py::test_from_fd",
"trio/tests/test_socket.py::test_socketpair_simple",
"trio/tests/test_socket.py::test_socket",
"trio/tests/test_socket.py::test_socket_v6",
"trio/tests/test_socket.py::test_sniff_sockopts",
"trio/tests/test_socket.py::test_SocketType_basics",
"trio/tests/test_socket.py::test_SocketType_dup",
"trio/tests/test_socket.py::test_SocketType_shutdown",
"trio/tests/test_socket.py::test_SocketType_simple_server[127.0.0.1-AddressFamily.AF_INET]",
"trio/tests/test_socket.py::test_SocketType_simple_server[::1-AddressFamily.AF_INET6]",
"trio/tests/test_socket.py::test_SocketType_is_readable",
"trio/tests/test_socket.py::test_SocketType_unresolved_names",
"trio/tests/test_socket.py::test_SocketType_non_blocking_paths",
"trio/tests/test_socket.py::test_SocketType_connect_paths",
"trio/tests/test_socket.py::test_resolve_address_exception_in_connect_closes_socket",
"trio/tests/test_socket.py::test_send_recv_variants",
"trio/tests/test_socket.py::test_idna",
"trio/tests/test_socket.py::test_custom_hostname_resolver",
"trio/tests/test_socket.py::test_custom_socket_factory",
"trio/tests/test_socket.py::test_SocketType_is_abstract",
"trio/tests/test_socket.py::test_unix_domain_socket",
"trio/tests/test_socket.py::test_interrupted_by_close",
"trio/tests/test_socket.py::test_many_sockets"
] |
{
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-14 12:07:43+00:00
|
mit
| 5,097 |
|
python-trio__trio-502
|
diff --git a/trio/_path.py b/trio/_path.py
index 4b1bee16..7f777936 100644
--- a/trio/_path.py
+++ b/trio/_path.py
@@ -128,6 +128,28 @@ class Path(metaclass=AsyncAutoWrapperType):
self._wrapped = pathlib.Path(*args)
+ async def iterdir(self):
+ """
+ Like :meth:`pathlib.Path.iterdir`, but async.
+
+ This is an async method that returns a synchronous iterator, so you
+ use it like::
+
+ for subpath in await mypath.iterdir():
+ ...
+
+ Note that it actually loads the whole directory list into memory
+ immediately, during the initial call. (See `issue #501
+ <https://github.com/python-trio/trio/issues/501>`__ for discussion.)
+
+ """
+
+ def _load_items():
+ return list(self._wrapped.iterdir())
+
+ items = await trio.run_sync_in_worker_thread(_load_items)
+ return (Path(item) for item in items)
+
def __getattr__(self, name):
if name in self._forward:
value = getattr(self._wrapped, name)
|
python-trio/trio
|
94d49f95ffba3634197c173b771dca80ebc70b08
|
diff --git a/trio/tests/test_path.py b/trio/tests/test_path.py
index 6b9d1c15..1289cfa2 100644
--- a/trio/tests/test_path.py
+++ b/trio/tests/test_path.py
@@ -198,3 +198,17 @@ async def test_path_nonpath():
async def test_open_file_can_open_path(path):
async with await trio.open_file(path, 'w') as f:
assert f.name == fspath(path)
+
+
+async def test_iterdir(path):
+ # Populate a directory
+ await path.mkdir()
+ await (path / 'foo').mkdir()
+ await (path / 'bar.txt').write_bytes(b'')
+
+ entries = set()
+ for entry in await path.iterdir():
+ assert isinstance(entry, trio.Path)
+ entries.add(entry.name)
+
+ assert entries == {'bar.txt', 'foo'}
|
trio.Path.iterdir wrapping is broken
Given `pathlib.Path.iterdir` returns a generator that does IO access on each iteration, `trio.Path.iterdir` is currently broken given it currently only generates the generator asynchronously (which I suppose is pointless given there is no need for IO at generator creation)
The solution would be to modify `trio.Path.iterdir` to return an async generator, however this means creating a special case given the current implementation is only an async wrapper on `pathlib.Path.iterdir`.
|
0.0
|
94d49f95ffba3634197c173b771dca80ebc70b08
|
[
"trio/tests/test_path.py::test_iterdir"
] |
[
"trio/tests/test_path.py::test_open_is_async_context_manager",
"trio/tests/test_path.py::test_magic",
"trio/tests/test_path.py::test_cmp_magic[Path-Path0]",
"trio/tests/test_path.py::test_cmp_magic[Path-Path1]",
"trio/tests/test_path.py::test_cmp_magic[Path-Path2]",
"trio/tests/test_path.py::test_div_magic[Path-Path0]",
"trio/tests/test_path.py::test_div_magic[Path-Path1]",
"trio/tests/test_path.py::test_div_magic[Path-str]",
"trio/tests/test_path.py::test_div_magic[str-Path]",
"trio/tests/test_path.py::test_forwarded_properties",
"trio/tests/test_path.py::test_async_method_signature",
"trio/tests/test_path.py::test_compare_async_stat_methods[is_dir]",
"trio/tests/test_path.py::test_compare_async_stat_methods[is_file]",
"trio/tests/test_path.py::test_invalid_name_not_wrapped",
"trio/tests/test_path.py::test_async_methods_rewrap[absolute]",
"trio/tests/test_path.py::test_async_methods_rewrap[resolve]",
"trio/tests/test_path.py::test_forward_methods_rewrap",
"trio/tests/test_path.py::test_forward_properties_rewrap",
"trio/tests/test_path.py::test_forward_methods_without_rewrap",
"trio/tests/test_path.py::test_repr",
"trio/tests/test_path.py::test_type_forwards_unsupported",
"trio/tests/test_path.py::test_type_wraps_unsupported",
"trio/tests/test_path.py::test_type_forwards_private",
"trio/tests/test_path.py::test_type_wraps_private",
"trio/tests/test_path.py::test_path_wraps_path[__init__]",
"trio/tests/test_path.py::test_path_wraps_path[joinpath]",
"trio/tests/test_path.py::test_path_nonpath",
"trio/tests/test_path.py::test_open_file_can_open_path"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2018-04-17 09:40:50+00:00
|
mit
| 5,098 |
|
python-trio__trio-576
|
diff --git a/.travis.yml b/.travis.yml
index 33c0f098..e571c41e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -26,6 +26,15 @@ matrix:
- python: 3.8-dev
dist: xenial
sudo: required
+ - os: osx
+ language: generic
+ env: MACPYTHON=3.5.4
+ - os: osx
+ language: generic
+ env: MACPYTHON=3.6.6
+ - os: osx
+ language: generic
+ env: MACPYTHON=3.7.0
script:
- ci/travis.sh
diff --git a/Jenkinsfile b/Jenkinsfile
index d94d4df1..50acf14b 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -1,7 +1,8 @@
def configs = [
[
label: 'sierra',
- pyversions: ['python3.5', 'python3.6'],
+ // pyversions: ['python3.5', 'python3.6'],
+ pyversions: ['python3.5'],
],
]
diff --git a/ci/travis.sh b/ci/travis.sh
index 3e0fde36..c856b9ab 100755
--- a/ci/travis.sh
+++ b/ci/travis.sh
@@ -6,6 +6,18 @@ YAPF_VERSION=0.20.1
git rev-parse HEAD
+if [ "$TRAVIS_OS_NAME" = "osx" ]; then
+ curl -Lo macpython.pkg https://www.python.org/ftp/python/${MACPYTHON}/python-${MACPYTHON}-macosx10.6.pkg
+ sudo installer -pkg macpython.pkg -target /
+ ls /Library/Frameworks/Python.framework/Versions/*/bin/
+ PYTHON_EXE=/Library/Frameworks/Python.framework/Versions/*/bin/python3
+ # The pip in older MacPython releases doesn't support a new enough TLS
+ curl https://bootstrap.pypa.io/get-pip.py | sudo $PYTHON_EXE
+ sudo $PYTHON_EXE -m pip install virtualenv
+ $PYTHON_EXE -m virtualenv testenv
+ source testenv/bin/activate
+fi
+
if [ "$USE_PYPY_NIGHTLY" = "1" ]; then
curl -fLo pypy.tar.bz2 http://buildbot.pypy.org/nightly/py3.5/pypy-c-jit-latest-linux64.tar.bz2
if [ ! -s pypy.tar.bz2 ]; then
diff --git a/newsfragments/548.bugfix.rst b/newsfragments/548.bugfix.rst
new file mode 100644
index 00000000..90c549af
--- /dev/null
+++ b/newsfragments/548.bugfix.rst
@@ -0,0 +1,1 @@
+Fix a memory leak in :class:`trio.CapacityLimiter`, that could occurr when ``acquire`` or ``acquire_on_behalf_of`` was cancelled.
diff --git a/trio/_ssl.py b/trio/_ssl.py
index 80f56714..74bf0628 100644
--- a/trio/_ssl.py
+++ b/trio/_ssl.py
@@ -839,7 +839,9 @@ class SSLStream(Stream):
class SSLListener(Listener):
"""A :class:`~trio.abc.Listener` for SSL/TLS-encrypted servers.
- :class:`SSLListener` allows you to wrap
+ :class:`SSLListener` wraps around another Listener, and converts
+ all incoming connections to encrypted connections by wrapping them
+ in a :class:`SSLStream`.
Args:
transport_listener (~trio.abc.Listener): The listener whose incoming
diff --git a/trio/_sync.py b/trio/_sync.py
index fe806dd3..a99f75a3 100644
--- a/trio/_sync.py
+++ b/trio/_sync.py
@@ -288,7 +288,11 @@ class CapacityLimiter:
except _core.WouldBlock:
task = _core.current_task()
self._pending_borrowers[task] = borrower
- await self._lot.park()
+ try:
+ await self._lot.park()
+ except _core.Cancelled:
+ self._pending_borrowers.pop(task)
+ raise
except:
await _core.cancel_shielded_checkpoint()
raise
|
python-trio/trio
|
fd0d8770a120a09a506ccd8a3f9969b26a22f38e
|
diff --git a/trio/tests/test_sync.py b/trio/tests/test_sync.py
index bded1b05..64aa3235 100644
--- a/trio/tests/test_sync.py
+++ b/trio/tests/test_sync.py
@@ -147,6 +147,21 @@ async def test_CapacityLimiter_change_total_tokens():
assert c.statistics().tasks_waiting == 0
+# regression test for issue #548
+async def test_CapacityLimiter_memleak_548():
+ limiter = CapacityLimiter(total_tokens=1)
+ await limiter.acquire()
+
+ async with _core.open_nursery() as n:
+ n.start_soon(limiter.acquire)
+ await wait_all_tasks_blocked() # give it a chance to run the task
+ n.cancel_scope.cancel()
+
+ # if this is 1, the acquire call (despite being killed) is still there in the task, and will
+ # leak memory all the while the limiter is active
+ assert len(limiter._pending_borrowers) == 0
+
+
async def test_Semaphore():
with pytest.raises(TypeError):
Semaphore(1.0)
|
Check CapacityLimiter's handling of _pending_borrowers
I was just reading the code for an unrelated reason, and realized that this code looks very suspicious:
https://github.com/python-trio/trio/blob/65729b121c55ff0aa1f5d43bd9cdcd6a81e54f0c/trio/_sync.py#L286-L296
Specifically, if the call to `await self._lot.park()` gets cancelled, it looks like we don't clear `self._pending_borrowers[task]`, which could be a memory leak (since it pins task objects in memory).
|
0.0
|
fd0d8770a120a09a506ccd8a3f9969b26a22f38e
|
[
"trio/tests/test_sync.py::test_CapacityLimiter_memleak_548"
] |
[
"trio/tests/test_sync.py::test_Event",
"trio/tests/test_sync.py::test_CapacityLimiter",
"trio/tests/test_sync.py::test_CapacityLimiter_change_total_tokens",
"trio/tests/test_sync.py::test_Semaphore",
"trio/tests/test_sync.py::test_Semaphore_bounded",
"trio/tests/test_sync.py::test_Lock_and_StrictFIFOLock[Lock]",
"trio/tests/test_sync.py::test_Lock_and_StrictFIFOLock[StrictFIFOLock]",
"trio/tests/test_sync.py::test_Condition",
"trio/tests/test_sync.py::test_Queue",
"trio/tests/test_sync.py::test_553",
"trio/tests/test_sync.py::test_Queue_iter",
"trio/tests/test_sync.py::test_Queue_statistics",
"trio/tests/test_sync.py::test_Queue_fairness",
"trio/tests/test_sync.py::test_Queue_unbuffered",
"trio/tests/test_sync.py::test_generic_lock_exclusion[CapacityLimiter(1)]",
"trio/tests/test_sync.py::test_generic_lock_exclusion[Semaphore(1)]",
"trio/tests/test_sync.py::test_generic_lock_exclusion[Lock]",
"trio/tests/test_sync.py::test_generic_lock_exclusion[StrictFIFOLock]",
"trio/tests/test_sync.py::test_generic_lock_exclusion[QueueLock1(10)]",
"trio/tests/test_sync.py::test_generic_lock_exclusion[QueueLock1(1)]",
"trio/tests/test_sync.py::test_generic_lock_exclusion[QueueLock2]",
"trio/tests/test_sync.py::test_generic_lock_exclusion[QueueLock3]",
"trio/tests/test_sync.py::test_generic_lock_fifo_fairness[CapacityLimiter(1)]",
"trio/tests/test_sync.py::test_generic_lock_fifo_fairness[Semaphore(1)]",
"trio/tests/test_sync.py::test_generic_lock_fifo_fairness[Lock]",
"trio/tests/test_sync.py::test_generic_lock_fifo_fairness[StrictFIFOLock]",
"trio/tests/test_sync.py::test_generic_lock_fifo_fairness[QueueLock1(10)]",
"trio/tests/test_sync.py::test_generic_lock_fifo_fairness[QueueLock1(1)]",
"trio/tests/test_sync.py::test_generic_lock_fifo_fairness[QueueLock2]",
"trio/tests/test_sync.py::test_generic_lock_fifo_fairness[QueueLock3]",
"trio/tests/test_sync.py::test_generic_lock_acquire_nowait_blocks_acquire[CapacityLimiter(1)]",
"trio/tests/test_sync.py::test_generic_lock_acquire_nowait_blocks_acquire[Semaphore(1)]",
"trio/tests/test_sync.py::test_generic_lock_acquire_nowait_blocks_acquire[Lock]",
"trio/tests/test_sync.py::test_generic_lock_acquire_nowait_blocks_acquire[StrictFIFOLock]",
"trio/tests/test_sync.py::test_generic_lock_acquire_nowait_blocks_acquire[QueueLock1(10)]",
"trio/tests/test_sync.py::test_generic_lock_acquire_nowait_blocks_acquire[QueueLock1(1)]",
"trio/tests/test_sync.py::test_generic_lock_acquire_nowait_blocks_acquire[QueueLock2]",
"trio/tests/test_sync.py::test_generic_lock_acquire_nowait_blocks_acquire[QueueLock3]"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-07-29 10:47:28+00:00
|
mit
| 5,099 |
|
python-useful-helpers__logwrap-21
|
diff --git a/README.rst b/README.rst
index 7d46a7e..03d3821 100644
--- a/README.rst
+++ b/README.rst
@@ -116,7 +116,7 @@ Get decorator for use without parameters:
Call example:
-.. code-block:: python3
+.. code-block:: python
import logwrap
@@ -140,18 +140,18 @@ This code during execution will produce log records:
Calling:
'example_function1'(
# POSITIONAL_OR_KEYWORD:
- 'arg1'=u'''arg1''',
- 'arg2'=u'''arg2''',
+ 'arg1'=u'''arg1''', # type: <class 'str'>
+ 'arg2'=u'''arg2''', # type: <class 'str'>
# VAR_POSITIONAL:
'args'=(),
# KEYWORD_ONLY:
- 'kwarg1'=u'''kwarg1''',
- 'kwarg2'=u'''kwarg2''',
+ 'kwarg1'=u'''kwarg1''', # type: <class 'str'>
+ 'kwarg2'=u'''kwarg2''', # type: <class 'str'>
# VAR_KEYWORD:
'kwargs'=
- dict({
+ dict({
'kwarg3': u'''kwarg3''',
- }),
+ }),
)
Done: 'example_function1' with result:
diff --git a/logwrap/_log_wrap_shared.py b/logwrap/_log_wrap_shared.py
index 274454c..0e076ed 100644
--- a/logwrap/_log_wrap_shared.py
+++ b/logwrap/_log_wrap_shared.py
@@ -49,7 +49,7 @@ logger = logging.getLogger(__name__) # type: logging.Logger
indent = 4
-fmt = "\n{spc:<{indent}}{{key!r}}={{val}},".format(
+fmt = "\n{spc:<{indent}}{{key!r}}={{val}},{{annotation}}".format(
spc='',
indent=indent,
).format
@@ -580,8 +580,14 @@ class BaseLogWrap(_class_decorator.BaseDecorator):
param_str += comment(kind=param.kind)
last_kind = param.kind
+ if param.empty == param.annotation:
+ annotation = ""
+ else:
+ annotation = " # type: {param.annotation!s}".format(param=param)
+
param_str += fmt(
key=param.name,
+ annotation=annotation,
val=val,
)
if param_str:
diff --git a/logwrap/_log_wrap_shared.pyi b/logwrap/_log_wrap_shared.pyi
index 88102d5..37b2880 100644
--- a/logwrap/_log_wrap_shared.pyi
+++ b/logwrap/_log_wrap_shared.pyi
@@ -27,11 +27,11 @@ class BoundParameter(object):
'_value'
)
- POSITIONAL_ONLY = Parameter.POSITIONAL_ONLY # type: enum.IntEnum
- POSITIONAL_OR_KEYWORD = Parameter.POSITIONAL_OR_KEYWORD # type: enum.IntEnum
- VAR_POSITIONAL = Parameter.VAR_POSITIONAL # type: enum.IntEnum
- KEYWORD_ONLY = Parameter.KEYWORD_ONLY # type: enum.IntEnum
- VAR_KEYWORD = Parameter.VAR_KEYWORD # type: enum.IntEnum
+ POSITIONAL_ONLY = Parameter.POSITIONAL_ONLY
+ POSITIONAL_OR_KEYWORD = Parameter.POSITIONAL_OR_KEYWORD
+ VAR_POSITIONAL = Parameter.VAR_POSITIONAL
+ KEYWORD_ONLY = Parameter.KEYWORD_ONLY
+ VAR_KEYWORD = Parameter.VAR_KEYWORD
empty = Parameter.empty # type: typing.Type
diff --git a/logwrap/_repr_utils.py b/logwrap/_repr_utils.py
index 987e183..a9752aa 100644
--- a/logwrap/_repr_utils.py
+++ b/logwrap/_repr_utils.py
@@ -54,14 +54,93 @@ def _simple(item): # type: (typing.Any) -> bool
return not isinstance(item, (list, set, tuple, dict, frozenset))
+class ReprParameter(object):
+ """Parameter wrapper wor repr and str operations over signature."""
+
+ __slots__ = (
+ '_value',
+ '_parameter'
+ )
+
+ POSITIONAL_ONLY = Parameter.POSITIONAL_ONLY
+ POSITIONAL_OR_KEYWORD = Parameter.POSITIONAL_OR_KEYWORD
+ VAR_POSITIONAL = Parameter.VAR_POSITIONAL
+ KEYWORD_ONLY = Parameter.KEYWORD_ONLY
+ VAR_KEYWORD = Parameter.VAR_KEYWORD
+
+ empty = Parameter.empty
+
+ def __init__(
+ self,
+ parameter, # type: Parameter
+ value=None # type: typing.Optional[typing.Any]
+ ): # type: (...) -> None
+ """Parameter-like object store for repr and str tasks.
+
+ :param parameter: parameter from signature
+ :type parameter: inspect.Parameter
+ :param value: default value override
+ :type value: typing.Any
+ """
+ self._parameter = parameter
+ self._value = value if value is not None else parameter.default
+
+ @property
+ def parameter(self): # type: () -> Parameter
+ """Parameter object."""
+ return self._parameter
+
+ @property
+ def name(self): # type: () -> typing.Union[None, str]
+ """Parameter name.
+
+ For `*args` and `**kwargs` add prefixes
+ """
+ if self.kind == Parameter.VAR_POSITIONAL:
+ return '*' + self.parameter.name
+ elif self.kind == Parameter.VAR_KEYWORD:
+ return '**' + self.parameter.name
+ return self.parameter.name
+
+ @property
+ def value(self): # type: () -> typing.Any
+ """Parameter value to log.
+
+ If function is bound to class -> value is class instance else default value.
+ """
+ return self._value
+
+ @property
+ def annotation(self): # type: () -> typing.Union[Parameter.empty, str]
+ """Parameter annotation."""
+ return self.parameter.annotation
+
+ @property
+ def kind(self): # type: () -> int
+ """Parameter kind."""
+ return self.parameter.kind
+
+ def __hash__(self): # pragma: no cover
+ """Block hashing.
+
+ :raises TypeError: Not hashable.
+ """
+ msg = "unhashable type: '{0}'".format(self.__class__.__name__)
+ raise TypeError(msg)
+
+ def __repr__(self):
+ """Debug purposes."""
+ return '<{} "{}">'.format(self.__class__.__name__, self)
+
+
# pylint: disable=no-member
def _prepare_repr(
func # type: typing.Union[types.FunctionType, types.MethodType]
-): # type: (...) -> typing.Iterator[typing.Union[str, typing.Tuple[str, typing.Any]]]
+): # type: (...) -> typing.Iterator[ReprParameter]
"""Get arguments lists with defaults.
:type func: typing.Union[types.FunctionType, types.MethodType]
- :rtype: typing.Iterator[typing.Union[str, typing.Tuple[str, typing.Any]]]
+ :rtype: typing.Iterator[ReprParameter]
"""
isfunction = isinstance(func, types.FunctionType)
real_func = func if isfunction else func.__func__ # type: typing.Callable
@@ -71,18 +150,11 @@ def _prepare_repr(
params = iter(parameters)
if not isfunction and func.__self__ is not None:
try:
- yield next(params).name, func.__self__
+ yield ReprParameter(next(params), value=func.__self__)
except StopIteration: # pragma: no cover
return
for arg in params:
- if arg.default != Parameter.empty:
- yield arg.name, arg.default
- elif arg.kind == Parameter.VAR_POSITIONAL:
- yield '*' + arg.name
- elif arg.kind == Parameter.VAR_KEYWORD:
- yield '**' + arg.name
- else:
- yield arg.name
+ yield ReprParameter(arg)
# pylint: enable=no-member
@@ -455,31 +527,35 @@ class PrettyRepr(PrettyFormat):
param_str = ""
for param in _prepare_repr(src):
- if isinstance(param, tuple):
- param_str += "\n{spc:<{indent}}{key}={val},".format(
- spc='',
- indent=self.next_indent(indent),
- key=param[0],
+ param_str += "\n{spc:<{indent}}{param.name}".format(
+ spc='',
+ indent=self.next_indent(indent),
+ param=param
+ )
+ if param.annotation != param.empty:
+ param_str += ': {param.annotation}'.format(param=param)
+ if param.value != param.empty:
+ param_str += '={val}'.format(
val=self.process_element(
- src=param[1],
+ src=param.value,
indent=indent,
no_indent_start=True,
)
)
- else:
- param_str += "\n{spc:<{indent}}{key},".format(
- spc='',
- indent=self.next_indent(indent),
- key=param
- )
+ param_str += ','
if param_str:
param_str += "\n" + " " * indent
- return "\n{spc:<{indent}}<{obj!r} with interface ({args})>".format(
+
+ sig = signature(src)
+ annotation = '' if sig.return_annotation == Parameter.empty else ' -> {sig.return_annotation!r}'.format(sig=sig)
+
+ return "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format(
spc="",
indent=indent,
obj=src,
args=param_str,
+ annotation=annotation
)
@staticmethod
@@ -627,31 +703,35 @@ class PrettyStr(PrettyFormat):
param_str = ""
for param in _prepare_repr(src):
- if isinstance(param, tuple):
- param_str += "\n{spc:<{indent}}{key}={val},".format(
- spc='',
- indent=self.next_indent(indent),
- key=param[0],
+ param_str += "\n{spc:<{indent}}{param.name}".format(
+ spc='',
+ indent=self.next_indent(indent),
+ param=param
+ )
+ if param.annotation != param.empty:
+ param_str += ': {param.annotation}'.format(param=param)
+ if param.value != param.empty:
+ param_str += '={val}'.format(
val=self.process_element(
- src=param[1],
+ src=param.value,
indent=indent,
no_indent_start=True,
)
)
- else:
- param_str += "\n{spc:<{indent}}{key},".format(
- spc='',
- indent=self.next_indent(indent),
- key=param
- )
+ param_str += ','
if param_str:
param_str += "\n" + " " * indent
- return "\n{spc:<{indent}}<{obj!s} with interface ({args})>".format(
+
+ sig = signature(src)
+ annotation = '' if sig.return_annotation == Parameter.empty else ' -> {sig.return_annotation!r}'.format(sig=sig)
+
+ return "\n{spc:<{indent}}<{obj!s} with interface ({args}){annotation}>".format(
spc="",
indent=indent,
obj=src,
args=param_str,
+ annotation=annotation
)
@staticmethod
diff --git a/logwrap/py.typed b/logwrap/py.typed
new file mode 100644
index 0000000..e69de29
diff --git a/setup.py b/setup.py
index e454818..25ed0e7 100644
--- a/setup.py
+++ b/setup.py
@@ -267,6 +267,8 @@ setup_args = dict(
'logwrap': [
os.path.basename(filename)
for filename in glob.glob(os.path.join('logwrap', '*.pyi'))
+ ] + [
+ 'py.typed'
],
},
)
|
python-useful-helpers/logwrap
|
1e040b43e3053f54f74a0b3ec95526e4430425b3
|
diff --git a/test/test_log_wrap_py3.py b/test/test_log_wrap_py3.py
index be03200..bd97db9 100644
--- a/test/test_log_wrap_py3.py
+++ b/test/test_log_wrap_py3.py
@@ -21,6 +21,8 @@ try:
except ImportError:
asyncio = None
import logging
+import sys
+import typing # noqa # pylint: disable=unused-import
import unittest
try:
from unittest import mock
@@ -139,3 +141,42 @@ class TestLogWrapAsync(unittest.TestCase):
),
]
)
+
+
+# noinspection PyUnusedLocal,PyMissingOrEmptyDocstring
[email protected]('logwrap._log_wrap_shared.logger', autospec=True)
[email protected](
+ sys.version_info[:2] < (3, 4),
+ 'Strict python 3.3+ API'
+)
+class TestAnnotated(unittest.TestCase):
+ def test_annotation_args(self, logger):
+ namespace = {'logwrap': logwrap}
+
+ exec("""
+import typing
[email protected]
+def func(a: typing.Optional[int]=None):
+ pass
+ """,
+ namespace
+ )
+ func = namespace['func'] # type: typing.Callable[..., None]
+ func()
+ self.assertEqual(
+ logger.mock_calls,
+ [
+ mock.call.log(
+ level=logging.DEBUG,
+ msg="Calling: \n"
+ "'func'(\n"
+ " # POSITIONAL_OR_KEYWORD:\n"
+ " 'a'=None, # type: typing.Union[int, NoneType]\n"
+ ")"
+ ),
+ mock.call.log(
+ level=logging.DEBUG,
+ msg="Done: 'func' with result:\nNone"
+ )
+ ]
+ )
diff --git a/test/test_repr_utils.py b/test/test_repr_utils.py
index b3edea6..2e45147 100644
--- a/test/test_repr_utils.py
+++ b/test/test_repr_utils.py
@@ -21,11 +21,10 @@
from __future__ import absolute_import
from __future__ import unicode_literals
+import sys
import unittest
import logwrap
-# noinspection PyProtectedMember
-from logwrap import _repr_utils
# noinspection PyUnusedLocal,PyMissingOrEmptyDocstring
@@ -113,74 +112,6 @@ class TestPrettyRepr(unittest.TestCase):
)
self.assertEqual(exp_repr, logwrap.pretty_repr(test_obj))
- def test_prepare_repr(self):
- def empty_func():
- pass
-
- def full_func(arg, darg=1, *positional, **named):
- pass
-
- # noinspection PyMissingOrEmptyDocstring
- class TstClass(object):
- def tst_method(self, arg, darg=1, *positional, **named):
- pass
-
- @classmethod
- def tst_classmethod(cls, arg, darg=1, *positional, **named):
- pass
-
- @staticmethod
- def tst_staticmethod(arg, darg=1, *positional, **named):
- pass
-
- tst_instance = TstClass()
-
- self.assertEqual(
- list(_repr_utils._prepare_repr(empty_func)),
- []
- )
-
- self.assertEqual(
- list(_repr_utils._prepare_repr(full_func)),
- ['arg', ('darg', 1), '*positional', '**named']
- )
-
- self.assertEqual(
- list(_repr_utils._prepare_repr(TstClass.tst_method)),
- ['self', 'arg', ('darg', 1), '*positional', '**named']
- )
-
- self.assertEqual(
- list(_repr_utils._prepare_repr(TstClass.tst_classmethod)),
- [('cls', TstClass), 'arg', ('darg', 1), '*positional', '**named']
- )
-
- self.assertEqual(
- list(_repr_utils._prepare_repr(TstClass.tst_staticmethod)),
- ['arg', ('darg', 1), '*positional', '**named']
- )
-
- self.assertEqual(
- list(_repr_utils._prepare_repr(tst_instance.tst_method)),
- [
- ('self', tst_instance),
- 'arg',
- ('darg', 1),
- '*positional',
- '**named',
- ]
- )
-
- self.assertEqual(
- list(_repr_utils._prepare_repr(tst_instance.tst_classmethod)),
- [('cls', TstClass), 'arg', ('darg', 1), '*positional', '**named']
- )
-
- self.assertEqual(
- list(_repr_utils._prepare_repr(tst_instance.tst_staticmethod)),
- ['arg', ('darg', 1), '*positional', '**named']
- )
-
def test_callable(self):
fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args})>".format
@@ -355,3 +286,115 @@ class TestPrettyRepr(unittest.TestCase):
def test_py2_compatibility_flag(self):
self.assertIsInstance(logwrap.pretty_repr(u'Text', py2_str=True), str)
+
+
+# noinspection PyUnusedLocal,PyMissingOrEmptyDocstring
[email protected](
+ sys.version_info[:2] < (3, 4),
+ 'Strict python 3.3+ API'
+)
+class TestAnnotated(unittest.TestCase):
+ def test_001_annotation_args(self):
+ fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format
+ namespace = {}
+
+ exec("""
+import typing
+def func(a: typing.Optional[int]=None):
+ pass
+ """,
+ namespace
+ )
+ func = namespace['func'] # type: typing.Callable[..., None]
+
+ self.assertEqual(
+ logwrap.pretty_repr(func),
+ fmt(
+ spc='',
+ indent=0,
+ obj=func,
+ args="\n a: typing.Union[int, NoneType]=None,\n",
+ annotation=""
+ )
+ )
+
+ self.assertEqual(
+ logwrap.pretty_str(func),
+ fmt(
+ spc='',
+ indent=0,
+ obj=func,
+ args="\n a: typing.Union[int, NoneType]=None,\n",
+ annotation=""
+ )
+ )
+
+ def test_002_annotation_return(self):
+ fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format
+ namespace = {}
+
+ exec("""
+import typing
+def func() -> None:
+ pass
+ """,
+ namespace
+ )
+ func = namespace['func'] # type: typing.Callable[[], None]
+
+ self.assertEqual(
+ logwrap.pretty_repr(func),
+ fmt(
+ spc='',
+ indent=0,
+ obj=func,
+ args='',
+ annotation=' -> None'
+ )
+ )
+
+ self.assertEqual(
+ logwrap.pretty_str(func),
+ fmt(
+ spc='',
+ indent=0,
+ obj=func,
+ args='',
+ annotation=' -> None'
+ )
+ )
+
+ def test_003_complex(self):
+ fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format
+ namespace = {}
+
+ exec("""
+import typing
+def func(a: typing.Optional[int]=None) -> None:
+ pass
+ """,
+ namespace
+ )
+ func = namespace['func'] # type: typing.Callable[..., None]
+
+ self.assertEqual(
+ logwrap.pretty_repr(func),
+ fmt(
+ spc='',
+ indent=0,
+ obj=func,
+ args="\n a: typing.Union[int, NoneType]=None,\n",
+ annotation=" -> None"
+ )
+ )
+
+ self.assertEqual(
+ logwrap.pretty_str(func),
+ fmt(
+ spc='',
+ indent=0,
+ obj=func,
+ args="\n a: typing.Union[int, NoneType]=None,\n",
+ annotation=" -> None"
+ )
+ )
|
Add type annotations to Callable objects when possible
On python 3 typing annotations is accessible and should be used in logging.
|
0.0
|
1e040b43e3053f54f74a0b3ec95526e4430425b3
|
[
"test/test_repr_utils.py::TestAnnotated::test_002_annotation_return"
] |
[
"test/test_log_wrap_py3.py::TestLogWrapAsync::test_coroutine_async",
"test/test_log_wrap_py3.py::TestLogWrapAsync::test_coroutine_async_as_argumented",
"test/test_log_wrap_py3.py::TestLogWrapAsync::test_coroutine_fail",
"test/test_log_wrap_py3.py::TestLogWrapAsync::test_exceptions_blacklist",
"test/test_repr_utils.py::TestPrettyRepr::test_callable",
"test/test_repr_utils.py::TestPrettyRepr::test_dict",
"test/test_repr_utils.py::TestPrettyRepr::test_indent",
"test/test_repr_utils.py::TestPrettyRepr::test_iterable",
"test/test_repr_utils.py::TestPrettyRepr::test_magic_override",
"test/test_repr_utils.py::TestPrettyRepr::test_nested_obj",
"test/test_repr_utils.py::TestPrettyRepr::test_py2_compatibility_flag",
"test/test_repr_utils.py::TestPrettyRepr::test_simple",
"test/test_repr_utils.py::TestPrettyRepr::test_text"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-17 11:17:03+00:00
|
apache-2.0
| 5,100 |
|
python-visualization__branca-90
|
diff --git a/branca/colormap.py b/branca/colormap.py
index 1544537..8db9583 100644
--- a/branca/colormap.py
+++ b/branca/colormap.py
@@ -70,10 +70,12 @@ class ColorMap(MacroElement):
The right bound of the color scale.
caption: str
A caption to draw with the colormap.
+ max_labels : int, default 10
+ Maximum number of legend tick labels
"""
_template = ENV.get_template('color_scale.js')
- def __init__(self, vmin=0., vmax=1., caption=''):
+ def __init__(self, vmin=0., vmax=1., caption='', max_labels=10):
super(ColorMap, self).__init__()
self._name = 'ColorMap'
@@ -81,13 +83,14 @@ class ColorMap(MacroElement):
self.vmax = vmax
self.caption = caption
self.index = [vmin, vmax]
+ self.max_labels = max_labels
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
self.color_domain = [self.vmin + (self.vmax-self.vmin) * k/499. for
k in range(500)]
self.color_range = [self.__call__(x) for x in self.color_domain]
- self.tick_labels = legend_scaler(self.index)
+ self.tick_labels = legend_scaler(self.index, self.max_labels)
super(ColorMap, self).render(**kwargs)
@@ -180,11 +183,13 @@ class LinearColormap(ColorMap):
Values lower than `vmin` will be bound directly to `colors[0]`.
vmax : float, default 1.
The maximal value for the colormap.
- Values higher than `vmax` will be bound directly to `colors[-1]`."""
+ Values higher than `vmax` will be bound directly to `colors[-1]`.
+ max_labels : int, default 10
+ Maximum number of legend tick labels"""
- def __init__(self, colors, index=None, vmin=0., vmax=1., caption=''):
+ def __init__(self, colors, index=None, vmin=0., vmax=1., caption='', max_labels=10):
super(LinearColormap, self).__init__(vmin=vmin, vmax=vmax,
- caption=caption)
+ caption=caption, max_labels=max_labels)
n = len(colors)
if n < 2:
@@ -216,7 +221,7 @@ class LinearColormap(ColorMap):
in range(4))
def to_step(self, n=None, index=None, data=None, method=None,
- quantiles=None, round_method=None):
+ quantiles=None, round_method=None, max_labels=10):
"""Splits the LinearColormap into a StepColormap.
Parameters
@@ -243,6 +248,8 @@ class LinearColormap(ColorMap):
* If 'log10', all values will be rounded to the nearest
order-of-magnitude integer. For example, 2100 is rounded to
2000, 2790 to 3000.
+ max_labels : int, default 10
+ Maximum number of legend tick labels
Returns
-------
@@ -324,9 +331,10 @@ class LinearColormap(ColorMap):
caption = self.caption
- return StepColormap(colors, index=index, vmin=index[0], vmax=index[-1], caption=caption)
+ return StepColormap(colors, index=index, vmin=index[0], vmax=index[-1], caption=caption,
+ max_labels=max_labels)
- def scale(self, vmin=0., vmax=1.):
+ def scale(self, vmin=0., vmax=1., max_labels=10):
"""Transforms the colorscale so that the minimal and maximal values
fit the given parameters.
"""
@@ -336,6 +344,7 @@ class LinearColormap(ColorMap):
vmin=vmin,
vmax=vmax,
caption=self.caption,
+ max_labels=max_labels
)
@@ -364,11 +373,13 @@ class StepColormap(ColorMap):
vmax : float, default 1.
The maximal value for the colormap.
Values higher than `vmax` will be bound directly to `colors[-1]`.
+ max_labels : int, default 10
+ Maximum number of legend tick labels
"""
- def __init__(self, colors, index=None, vmin=0., vmax=1., caption=''):
+ def __init__(self, colors, index=None, vmin=0., vmax=1., caption='', max_labels=10):
super(StepColormap, self).__init__(vmin=vmin, vmax=vmax,
- caption=caption)
+ caption=caption, max_labels=max_labels)
n = len(colors)
if n < 1:
@@ -393,7 +404,7 @@ class StepColormap(ColorMap):
i = len([u for u in self.index if u < x]) # 0 < i < n.
return tuple(self.colors[i-1])
- def to_linear(self, index=None):
+ def to_linear(self, index=None, max_labels=10):
"""
Transforms the StepColormap into a LinearColormap.
@@ -403,6 +414,8 @@ class StepColormap(ColorMap):
The values corresponding to each color in the output colormap.
It has to be sorted.
If None, a regular grid between `vmin` and `vmax` is created.
+ max_labels : int, default 10
+ Maximum number of legend tick labels
"""
if index is None:
@@ -412,9 +425,9 @@ class StepColormap(ColorMap):
colors = [self.rgba_floats_tuple(x) for x in index]
return LinearColormap(colors, index=index,
- vmin=self.vmin, vmax=self.vmax)
+ vmin=self.vmin, vmax=self.vmax, max_labels=max_labels)
- def scale(self, vmin=0., vmax=1.):
+ def scale(self, vmin=0., vmax=1., max_labels=10):
"""Transforms the colorscale so that the minimal and maximal values
fit the given parameters.
"""
@@ -424,6 +437,7 @@ class StepColormap(ColorMap):
vmin=vmin,
vmax=vmax,
caption=self.caption,
+ max_labels=max_labels
)
|
python-visualization/branca
|
a872bef69cfef4ab40380686b637c99dee6a8187
|
diff --git a/tests/test_colormap.py b/tests/test_colormap.py
index 51cfbb3..4b9483b 100644
--- a/tests/test_colormap.py
+++ b/tests/test_colormap.py
@@ -4,6 +4,7 @@ Folium Colormap Module
----------------------
"""
import branca.colormap as cm
+import pytest
def test_simple_step():
@@ -55,3 +56,30 @@ def test_step_object():
cm.step.PuBu_06.to_linear()
cm.step.YlGn_06.scale(3, 12)
cm.step._repr_html_()
+
[email protected]("max_labels,expected", [
+ (10, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]),
+ (5, [0.0, '', 2.0, '', 4.0, '', 6.0, '', 8.0, '']),
+ (3, [0.0, '', '', '', 4.0, '', '', '', 8.0, '', '', '']),
+])
+def test_max_labels_linear(max_labels, expected):
+ colorbar = cm.LinearColormap(['red'] * 10, vmin=0, vmax=9, max_labels=max_labels)
+ try:
+ colorbar.render()
+ except AssertionError: # rendering outside parent Figure raises error
+ pass
+ assert colorbar.tick_labels == expected
+
+
[email protected]("max_labels,expected", [
+ (10, [0.0, '', 2.0, '', 4.0, '', 6.0, '', 8.0, '', 10.0, '']),
+ (5, [0.0, '', '', 3.0, '', '', 6.0, '', '', 9.0, '', '']),
+ (3, [0.0, '', '', '', 4.0, '', '', '', 8.0, '', '', '']),
+])
+def test_max_labels_step(max_labels, expected):
+ colorbar = cm.StepColormap(['red', 'blue'] * 5, vmin=0, vmax=10, max_labels=max_labels)
+ try:
+ colorbar.render()
+ except AssertionError: # rendering outside parent Figure raises error
+ pass
+ assert colorbar.tick_labels == expected
|
Expose legend_scaler's max_labels in ColorMap
Hi,
I see that `legend_scaler` has an option to specify the number of labels (`max_labels`) but that is not accessible form within `ColorMap`.
Would be great to expose it in `ColorMap.__init__` and then pass it to `render`. With large numbers you get overlaps and there's no way to prevent it.
Relevant bits:
https://github.com/python-visualization/branca/blob/ac45f1e1fa95d10a2409409cf3c697f700cad314/branca/utilities.py#L37
https://github.com/python-visualization/branca/blob/ac45f1e1fa95d10a2409409cf3c697f700cad314/branca/colormap.py#L90
Happy to do a PR for that.
|
0.0
|
a872bef69cfef4ab40380686b637c99dee6a8187
|
[
"tests/test_colormap.py::test_max_labels_linear[10-expected0]",
"tests/test_colormap.py::test_max_labels_linear[5-expected1]",
"tests/test_colormap.py::test_max_labels_linear[3-expected2]",
"tests/test_colormap.py::test_max_labels_step[10-expected0]",
"tests/test_colormap.py::test_max_labels_step[5-expected1]",
"tests/test_colormap.py::test_max_labels_step[3-expected2]"
] |
[
"tests/test_colormap.py::test_simple_step",
"tests/test_colormap.py::test_simple_linear",
"tests/test_colormap.py::test_linear_to_step",
"tests/test_colormap.py::test_step_to_linear",
"tests/test_colormap.py::test_linear_object",
"tests/test_colormap.py::test_step_object"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-11 12:05:08+00:00
|
mit
| 5,101 |
|
python-visualization__folium-1155
|
diff --git a/folium/features.py b/folium/features.py
index 93d65616..7796c29b 100644
--- a/folium/features.py
+++ b/folium/features.py
@@ -521,17 +521,31 @@ class GeoJson(Layer):
.format(name))
def find_identifier(self):
- """Find a unique identifier for each feature, create it if needed."""
- features = self.data['features']
- n = len(features)
- feature = features[0]
- if 'id' in feature and len(set(feat['id'] for feat in features)) == n:
+ """Find a unique identifier for each feature, create it if needed.
+
+ According to the GeoJSON specs a feature:
+ - MAY have an 'id' field with a string or numerical value.
+ - MUST have a 'properties' field. The content can be any json object
+ or even null.
+
+ """
+ feats = self.data['features']
+ # Each feature has an 'id' field with a unique value.
+ unique_ids = set(feat.get('id', None) for feat in feats)
+ if None not in unique_ids and len(unique_ids) == len(feats):
return 'feature.id'
- for key in feature.get('properties', []):
- if len(set(feat['properties'][key] for feat in features)) == n:
- return 'feature.properties.{}'.format(key)
+ # Each feature has a unique string or int property.
+ if all(isinstance(feat.get('properties', None), dict) for feat in feats):
+ for key in feats[0]['properties']:
+ unique_values = set(
+ feat['properties'].get(key, None) for feat in feats
+ if isinstance(feat['properties'].get(key, None), (str, int))
+ )
+ if len(unique_values) == len(feats):
+ return 'feature.properties.{}'.format(key)
+ # We add an 'id' field with a unique value to the data.
if self.embed:
- for i, feature in enumerate(self.data['features']):
+ for i, feature in enumerate(feats):
feature['id'] = str(i)
return 'feature.id'
raise ValueError(
|
python-visualization/folium
|
5d14833595718acad49d45e0a30fb4225e3f9c56
|
diff --git a/tests/test_features.py b/tests/test_features.py
index e77f42ad..fb48e0a9 100644
--- a/tests/test_features.py
+++ b/tests/test_features.py
@@ -12,7 +12,7 @@ import warnings
from branca.element import Element
import folium
-from folium import Map, Popup
+from folium import Map, Popup, GeoJson
import pytest
@@ -213,3 +213,93 @@ def test_geojson_tooltip():
warnings.simplefilter('always')
m._repr_html_()
assert issubclass(w[-1].category, UserWarning), 'GeoJsonTooltip GeometryCollection test failed.'
+
+
+def test_geojson_find_identifier():
+
+ def _create(*properties):
+ return {"type": "FeatureCollection", "features": [
+ {"type": "Feature", "properties": item}
+ for item in properties]}
+
+ def _assert_id_got_added(data):
+ _geojson = GeoJson(data)
+ assert _geojson.find_identifier() == 'feature.id'
+ assert _geojson.data['features'][0]['id'] == '0'
+
+ data_with_id = _create(None, None)
+ data_with_id['features'][0]['id'] = 'this-is-an-id'
+ data_with_id['features'][1]['id'] = 'this-is-another-id'
+ geojson = GeoJson(data_with_id)
+ assert geojson.find_identifier() == 'feature.id'
+ assert geojson.data['features'][0]['id'] == 'this-is-an-id'
+
+ data_with_unique_properties = _create(
+ {'property-key': 'some-value'},
+ {'property-key': 'another-value'},
+ )
+ geojson = GeoJson(data_with_unique_properties)
+ assert geojson.find_identifier() == 'feature.properties.property-key'
+
+ data_with_unique_properties = _create(
+ {'property-key': 42},
+ {'property-key': 43},
+ {'property-key': 'or a string'},
+ )
+ geojson = GeoJson(data_with_unique_properties)
+ assert geojson.find_identifier() == 'feature.properties.property-key'
+
+ # The test cases below have no id field or unique property,
+ # so an id will be added to the data.
+
+ data_with_identical_ids = _create(None, None)
+ data_with_identical_ids['features'][0]['id'] = 'identical-ids'
+ data_with_identical_ids['features'][1]['id'] = 'identical-ids'
+ _assert_id_got_added(data_with_identical_ids)
+
+ data_with_some_missing_ids = _create(None, None)
+ data_with_some_missing_ids['features'][0]['id'] = 'this-is-an-id'
+ # the second feature doesn't have an id
+ _assert_id_got_added(data_with_some_missing_ids)
+
+ data_with_identical_properties = _create(
+ {'property-key': 'identical-value'},
+ {'property-key': 'identical-value'},
+ )
+ _assert_id_got_added(data_with_identical_properties)
+
+ data_bare = _create(None)
+ _assert_id_got_added(data_bare)
+
+ data_empty_dict = _create({})
+ _assert_id_got_added(data_empty_dict)
+
+ data_without_properties = _create(None)
+ del data_without_properties['features'][0]['properties']
+ _assert_id_got_added(data_without_properties)
+
+ data_some_without_properties = _create({'key': 'value'}, 'will be deleted')
+ # the first feature has properties, but the second doesn't
+ del data_some_without_properties['features'][1]['properties']
+ _assert_id_got_added(data_some_without_properties)
+
+ data_with_nested_properties = _create({
+ "summary": {"distance": 343.2},
+ "way_points": [3, 5],
+ })
+ _assert_id_got_added(data_with_nested_properties)
+
+ data_with_incompatible_properties = _create({
+ "summary": {"distances": [0, 6], "durations": None},
+ "way_points": [3, 5],
+ })
+ _assert_id_got_added(data_with_incompatible_properties)
+
+ data_loose_geometry = {"type": "LineString", "coordinates": [
+ [3.961389, 43.583333], [3.968056, 43.580833], [3.974722, 43.578333],
+ [3.986389, 43.575278], [3.998333, 43.5725], [4.163333, 43.530556],
+ ]}
+ geojson = GeoJson(data_loose_geometry)
+ geojson.convert_to_feature_collection()
+ assert geojson.find_identifier() == 'feature.id'
+ assert geojson.data['features'][0]['id'] == '0'
|
GeoJSON feature ID creator fails when properties contain list/dict
This code throws a `TypeError`:
(**edit**: add geometry type to feature)
```python
import folium
json = {
"type": "FeatureCollection",
"features": [
{
"bbox": [
8.546326,
47.417879,
8.548813,
47.420362
],
"type": "Feature",
"properties": {
"summary": {
"distance": 343.2,
"duration": 50.5
},
"way_points": [
0,
15
]
},
"geometry": {
"coordinates": [
[
8.548813,
47.420362
],
[
8.548795,
47.420345
],
[
8.548621,
47.420167
]
],
"type": "LineString"
}
}
]
}
m = folium.Map(location=[47.417879, 8.546326], zoom_start=13)
folium.features.GeoJson(json, style_function=lambda x: {'opacity': 1.0}).add_to(m)
m
```
#### Problem description
If a `style_function` is passed, `folium` tries to find an ID for the GeoJSON features. When no `id` field is present (not required in GeoJSONs AFAIK), it will try to pick a field from properties by checking if the values of the property fields are unique. However, the current implementation with `set` to check uniqueness fails when the property field values are `dict`s or `list`s.
#### Quick Fix
It works with a try/except around the [the appropriate lines](https://github.com/python-visualization/folium/blob/5d14833595718acad49d45e0a30fb4225e3f9c56/folium/features.py#L531):
```python
try:
if len(set(feat['properties'][key] for feat in features)) == n:
return 'feature.properties.{}'.format(key)
except TypeError:
continue
```
I'd be happy with this if was my library, as far as I can see nothing else could raise a `TypeError` here. What do you think?
#### Output of ``0.9.0 ``
```
530 for key in feature.get('properties', []):
531 # try:
--> 532 if len(set(feat['properties'][key] for feat in features)) == n:
533 return 'feature.properties.{}'.format(key)
534 # except TypeError:
TypeError: unhashable type: 'dict'
```
|
0.0
|
5d14833595718acad49d45e0a30fb4225e3f9c56
|
[
"tests/test_features.py::test_geojson_find_identifier"
] |
[
"tests/test_features.py::test_figure_creation",
"tests/test_features.py::test_figure_rendering",
"tests/test_features.py::test_figure_double_rendering",
"tests/test_features.py::test_marker_popups",
"tests/test_features.py::test_divicon",
"tests/test_features.py::test_color_line",
"tests/test_features.py::test_get_vegalite_major_version",
"tests/test_features.py::test_geojson_tooltip"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2019-05-25 15:01:21+00:00
|
mit
| 5,102 |
|
python-visualization__folium-1213
|
diff --git a/folium/features.py b/folium/features.py
index 6cc18f1d..fb2da035 100644
--- a/folium/features.py
+++ b/folium/features.py
@@ -579,6 +579,11 @@ class GeoJson(Layer):
Tests `self.style_function` and `self.highlight_function` to ensure
they are functions returning dictionaries.
"""
+ # If for some reason there are no features (e.g., empty API response)
+ # don't attempt validation
+ if not self.data['features']:
+ return
+
test_feature = self.data['features'][0]
if not callable(func) or not isinstance(func(test_feature), dict):
raise ValueError('{} should be a function that accepts items from '
@@ -629,7 +634,8 @@ class GeoJson(Layer):
def render(self, **kwargs):
self.parent_map = get_obj_in_upper_tree(self, Map)
- if self.style or self.highlight:
+ # Need at least one feature, otherwise style mapping fails
+ if (self.style or self.highlight) and self.data['features']:
mapper = GeoJsonStyleMapper(self.data, self.feature_identifier,
self)
if self.style:
|
python-visualization/folium
|
98184109187006bbd798bba11bee28a2f53b4705
|
diff --git a/tests/test_features.py b/tests/test_features.py
index 5b27104c..49806873 100644
--- a/tests/test_features.py
+++ b/tests/test_features.py
@@ -154,6 +154,7 @@ def test_vegalite_major_version(vegalite_spec, version):
else:
assert vegalite.vegalite_major_version == version
+
# GeoJsonTooltip GeometryCollection
def test_geojson_tooltip():
m = folium.Map([30.5, -97.5], zoom_start=10)
@@ -266,6 +267,14 @@ def test_geojson_find_identifier():
assert geojson.data['features'][0]['id'] == '0'
+def test_geojson_empty_features_with_styling():
+ # test we don't fail style function validation when there are no features
+ m = Map()
+ data = {"type": "FeatureCollection", "features": []}
+ GeoJson(data, style_function=lambda x: {}).add_to(m)
+ m.get_root().render()
+
+
def test_geometry_collection_get_bounds():
"""Assert #1599 is fixed"""
geojson_data = {
|
Empty geojson data fails when combined with a style_function
#### Please add a code sample or a nbviewer link, copy-pastable if possible
This works fine:
```python
geo_json_data = """
{
"type": "FeatureCollection",
"features": []
}
m = folium.Map([43, -100], zoom_start=4)
folium.GeoJson(
geo_json_data
).add_to(m)
m
```
But this does not:
```python
geo_json_data = """
{
"type": "FeatureCollection",
"features": []
}
m = folium.Map([43, -100], zoom_start=4)
folium.GeoJson(
geo_json_data,
style_function=lambda feature: {
'fillColor': '#ffff00',
'color': 'black',
'weight': 2,
'dashArray': '5, 5'
}
).add_to(m)
m
"""
```
#### Problem description
Sometimes a user ends up attempting to plot empty GeoJson (e.g., it came from an API response with no results).
Normally this works, but will fail if you use it in conjunction with a `style_function` .
#### Expected Output
I would expect to see an empty plot even when attempting to plot an empty GeoJson.
#### Output of ``folium.__version__``
0.10.0+2.g60ae79c.dirty
|
0.0
|
98184109187006bbd798bba11bee28a2f53b4705
|
[
"tests/test_features.py::test_geojson_empty_features_with_styling"
] |
[
"tests/test_features.py::test_figure_creation",
"tests/test_features.py::test_figure_rendering",
"tests/test_features.py::test_figure_html",
"tests/test_features.py::test_figure_double_rendering",
"tests/test_features.py::test_marker_popups",
"tests/test_features.py::test_divicon",
"tests/test_features.py::test_color_line",
"tests/test_features.py::test_vegalite_major_version[1]",
"tests/test_features.py::test_vegalite_major_version[2]",
"tests/test_features.py::test_vegalite_major_version[3]",
"tests/test_features.py::test_vegalite_major_version[4]",
"tests/test_features.py::test_vegalite_major_version[5]",
"tests/test_features.py::test_vegalite_major_version[None]",
"tests/test_features.py::test_geojson_tooltip",
"tests/test_features.py::test_geojson_marker",
"tests/test_features.py::test_geojson_find_identifier",
"tests/test_features.py::test_geometry_collection_get_bounds"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2019-10-09 03:43:07+00:00
|
mit
| 5,103 |
|
python-visualization__folium-1240
|
diff --git a/folium/plugins/heat_map_withtime.py b/folium/plugins/heat_map_withtime.py
index aebcdf0f..e7135164 100644
--- a/folium/plugins/heat_map_withtime.py
+++ b/folium/plugins/heat_map_withtime.py
@@ -175,7 +175,7 @@ class HeatMapWithTime(Layer):
name='heatmap.min.js')
figure.header.add_child(
- JavascriptLink('https://rawcdn.githack.com/pa7/heatmap.js/develop/plugins/leaflet-heatmap/leaflet-heatmap.js'), # noqa
+ JavascriptLink('https://rawcdn.githack.com/python-visualization/folium/master/folium/templates/pa7_leaflet_hm.min.js'), # noqa
name='leaflet-heatmap.js')
figure.header.add_child(
diff --git a/folium/templates/pa7_leaflet_hm.min.js b/folium/templates/pa7_leaflet_hm.min.js
new file mode 100644
index 00000000..1f5cd158
--- /dev/null
+++ b/folium/templates/pa7_leaflet_hm.min.js
@@ -0,0 +1,26 @@
+/*
+* Leaflet Heatmap Overlay
+*
+* Copyright (c) 2008-2016, Patrick Wied (https://www.patrick-wied.at)
+* Dual-licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
+* and the Beerware (http://en.wikipedia.org/wiki/Beerware) license.
+*/
+;(function(name,context,factory){if(typeof module!=="undefined"&&module.exports){module.exports=factory(require('heatmap.js'),require('leaflet'));}else if(typeof define==="function"&&define.amd){define(['heatmap.js','leaflet'],factory);}else{if(typeof window.h337==='undefined'){throw new Error('heatmap.js must be loaded before the leaflet heatmap plugin');}
+if(typeof window.L==='undefined'){throw new Error('Leaflet must be loaded before the leaflet heatmap plugin');}
+context[name]=factory(window.h337,window.L);}})("HeatmapOverlay",this,function(h337,L){'use strict';if(typeof L.Layer==='undefined'){L.Layer=L.Class;}
+var HeatmapOverlay=L.Layer.extend({initialize:function(config){this.cfg=config;this._el=L.DomUtil.create('div','leaflet-zoom-hide');this._data=[];this._max=1;this._min=0;this.cfg.container=this._el;},onAdd:function(map){var size=map.getSize();this._map=map;this._width=size.x;this._height=size.y;this._el.style.width=size.x+'px';this._el.style.height=size.y+'px';this._el.style.position='absolute';this._origin=this._map.layerPointToLatLng(new L.Point(0,0));map.getPanes().overlayPane.appendChild(this._el);if(!this._heatmap){this._heatmap=h337.create(this.cfg);}
+map.on('moveend',this._reset,this);this._draw();},addTo:function(map){map.addLayer(this);return this;},onRemove:function(map){map.getPanes().overlayPane.removeChild(this._el);map.off('moveend',this._reset,this);},_draw:function(){if(!this._map){return;}
+var mapPane=this._map.getPanes().mapPane;var point=mapPane._leaflet_pos;this._el.style[HeatmapOverlay.CSS_TRANSFORM]='translate('+
+-Math.round(point.x)+'px,'+
+-Math.round(point.y)+'px)';this._update();},_update:function(){var bounds,zoom,scale;var generatedData={max:this._max,min:this._min,data:[]};bounds=this._map.getBounds();zoom=this._map.getZoom();scale=Math.pow(2,zoom);if(this._data.length==0){if(this._heatmap){this._heatmap.setData(generatedData);}
+return;}
+var latLngPoints=[];var radiusMultiplier=this.cfg.scaleRadius?scale:1;var localMax=0;var localMin=0;var valueField=this.cfg.valueField;var len=this._data.length;while(len--){var entry=this._data[len];var value=entry[valueField];var latlng=entry.latlng;if(!bounds.contains(latlng)){continue;}
+localMax=Math.max(value,localMax);localMin=Math.min(value,localMin);var point=this._map.latLngToContainerPoint(latlng);var latlngPoint={x:Math.round(point.x),y:Math.round(point.y)};latlngPoint[valueField]=value;var radius;if(entry.radius){radius=entry.radius*radiusMultiplier;}else{radius=(this.cfg.radius||2)*radiusMultiplier;}
+latlngPoint.radius=radius;latLngPoints.push(latlngPoint);}
+if(this.cfg.useLocalExtrema){generatedData.max=localMax;generatedData.min=localMin;}
+generatedData.data=latLngPoints;this._heatmap.setData(generatedData);},setData:function(data){this._max=data.max||this._max;this._min=data.min||this._min;var latField=this.cfg.latField||'lat';var lngField=this.cfg.lngField||'lng';var valueField=this.cfg.valueField||'value';var data=data.data;var len=data.length;var d=[];while(len--){var entry=data[len];var latlng=new L.LatLng(entry[latField],entry[lngField]);var dataObj={latlng:latlng};dataObj[valueField]=entry[valueField];if(entry.radius){dataObj.radius=entry.radius;}
+d.push(dataObj);}
+this._data=d;this._draw();},addData:function(pointOrArray){if(pointOrArray.length>0){var len=pointOrArray.length;while(len--){this.addData(pointOrArray[len]);}}else{var latField=this.cfg.latField||'lat';var lngField=this.cfg.lngField||'lng';var valueField=this.cfg.valueField||'value';var entry=pointOrArray;var latlng=new L.LatLng(entry[latField],entry[lngField]);var dataObj={latlng:latlng};dataObj[valueField]=entry[valueField];this._max=Math.max(this._max,dataObj[valueField]);this._min=Math.min(this._min,dataObj[valueField]);if(entry.radius){dataObj.radius=entry.radius;}
+this._data.push(dataObj);this._draw();}},_reset:function(){this._origin=this._map.layerPointToLatLng(new L.Point(0,0));var size=this._map.getSize();if(this._width!==size.x||this._height!==size.y){this._width=size.x;this._height=size.y;this._el.style.width=this._width+'px';this._el.style.height=this._height+'px';this._heatmap._renderer.setDimensions(this._width,this._height);}
+this._draw();}});HeatmapOverlay.CSS_TRANSFORM=(function(){var div=document.createElement('div');var props=['transform','WebkitTransform','MozTransform','OTransform','msTransform'];for(var i=0;i<props.length;i++){var prop=props[i];if(div.style[prop]!==undefined){return prop;}}
+return props[0];})();return HeatmapOverlay;});
|
python-visualization/folium
|
61daf0ccb9dc819523b4bab901e1a07d6e1b1a6f
|
diff --git a/tests/plugins/test_heat_map_withtime.py b/tests/plugins/test_heat_map_withtime.py
index fa5725bb..3bb1736c 100644
--- a/tests/plugins/test_heat_map_withtime.py
+++ b/tests/plugins/test_heat_map_withtime.py
@@ -30,7 +30,7 @@ def test_heat_map_with_time():
assert script in out
script = '<script src="https://rawcdn.githack.com/python-visualization/folium/master/folium/templates/pa7_hm.min.js"></script>' # noqa
assert script in out
- script = '<script src="https://rawcdn.githack.com/pa7/heatmap.js/develop/plugins/leaflet-heatmap/leaflet-heatmap.js"></script>' # noqa
+ script = '<script src="https://rawcdn.githack.com/python-visualization/folium/master/folium/templates/pa7_leaflet_hm.min.js"></script>' # noqa
assert script in out
script = '<link rel="stylesheet" href="http://apps.socib.es/Leaflet.TimeDimension/dist/leaflet.timedimension.control.min.css"/>' # noqa
assert script in out
|
Host any JS dependency with 'heatmap' in the title under a different name
Ad blockers seem to block most resources that have 'heatmap' in the name. We circumvented this before by hosting the resource ourself under a different name.
In the `HeatmapWithTime` plugin, host `https://rawcdn.githack.com/pa7/heatmap.js/develop/plugins/leaflet-heatmap/leaflet-heatmap.js` ourself under a different name.
Search in the code base if there are other uses of JS libraries with the word 'heatmap' in them.
|
0.0
|
61daf0ccb9dc819523b4bab901e1a07d6e1b1a6f
|
[
"tests/plugins/test_heat_map_withtime.py::test_heat_map_with_time"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-05 10:39:55+00:00
|
mit
| 5,104 |
|
python-visualization__folium-1570
|
diff --git a/folium/plugins/float_image.py b/folium/plugins/float_image.py
index 00f32e03..fd3fc21f 100644
--- a/folium/plugins/float_image.py
+++ b/folium/plugins/float_image.py
@@ -12,6 +12,7 @@ class FloatImage(MacroElement):
position:absolute;
bottom:{{this.bottom}}%;
left:{{this.left}}%;
+ width:{{this.width}}%;
}
</style>
{% endmacro %}
@@ -24,9 +25,10 @@ class FloatImage(MacroElement):
{% endmacro %}
""")
- def __init__(self, image, bottom=75, left=75):
+ def __init__(self, image, bottom=75, left=75, width=100):
super(FloatImage, self).__init__()
self._name = 'FloatImage'
self.image = image
self.bottom = bottom
self.left = left
+ self.width = width
|
python-visualization/folium
|
67aab11039cd990d73fdf14566380286835ff84b
|
diff --git a/tests/plugins/test_float_image.py b/tests/plugins/test_float_image.py
index 8fdf02f4..cf98028e 100644
--- a/tests/plugins/test_float_image.py
+++ b/tests/plugins/test_float_image.py
@@ -13,7 +13,7 @@ from jinja2 import Template
def test_float_image():
m = folium.Map([45., 3.], zoom_start=4)
url = 'https://raw.githubusercontent.com/SECOORA/static_assets/master/maps/img/rose.png'
- szt = plugins.FloatImage(url, bottom=60, left=70)
+ szt = plugins.FloatImage(url, bottom=60, left=70, width=20)
m.add_child(szt)
m._repr_html_()
@@ -35,6 +35,7 @@ def test_float_image():
position:absolute;
bottom:60%;
left:70%;
+ width:20%;
}
</style>
""")
|
Styling Imported Images
New to Python, kinda dove into it headfirst to create an interactive map with data. Really enjoying it, and really loving what Folium can do.
I've added a legend.png to create a legend (temporarily, or perhaps permanently, unless something else can be recommended) that I'd like to style by adding a box-shadow as well as adding a radius to curve the edges if I so desire.
Perhaps it's already in the notes somewhere, but I couldn't find it!
The legend itself works as it should and doesn't interfere with interacting with each site bubble (each site is expected to have more than just a "name" at some point. Actual data/graphs/etc. will be contained for nearly each site.)
```python
# Create Map Legend
from folium.plugins import FloatImage
image_file='images/Legend.png'
FloatImage(image_file,bottom=5,left=5).add_to(map)
```
Another quick question: can the output HTML file be modified with a viewport tag to assist with scaling on a mobile environment? I haven't tried it yet, and I assume each time I compile the app after I make changes the subsequent HTML file is entirely overwritten.
Thank you!
|
0.0
|
67aab11039cd990d73fdf14566380286835ff84b
|
[
"tests/plugins/test_float_image.py::test_float_image"
] |
[] |
{
"failed_lite_validators": [
"has_media"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-02-15 18:12:03+00:00
|
mit
| 5,105 |
|
python-visualization__folium-1633
|
diff --git a/folium/utilities.py b/folium/utilities.py
index 875ac015..62f5869f 100644
--- a/folium/utilities.py
+++ b/folium/utilities.py
@@ -331,6 +331,8 @@ def iter_coords(obj):
coords = [geom['geometry']['coordinates'] for geom in obj['features']]
elif 'geometry' in obj:
coords = obj['geometry']['coordinates']
+ elif 'geometries' in obj and 'coordinates' in obj['geometries'][0]:
+ coords = obj['geometries'][0]['coordinates']
else:
coords = obj.get('coordinates', obj)
for coord in coords:
|
python-visualization/folium
|
7f50b4058ac566ab2959bf4358c6bdaf0bd60ffa
|
diff --git a/tests/test_features.py b/tests/test_features.py
index f2f0611a..b0171640 100644
--- a/tests/test_features.py
+++ b/tests/test_features.py
@@ -314,3 +314,24 @@ def test_geojson_find_identifier():
geojson.convert_to_feature_collection()
assert geojson.find_identifier() == 'feature.id'
assert geojson.data['features'][0]['id'] == '0'
+
+
+def test_geometry_collection_get_bounds():
+ """Assert #1599 is fixed"""
+ geojson_data = {
+ "geometries": [
+ {
+ "coordinates": [
+ [
+ [-1, 1],
+ [0, 2],
+ [-3, 4],
+ [2, 0],
+ ]
+ ],
+ "type": "Polygon",
+ },
+ ],
+ "type": "GeometryCollection",
+ }
+ assert folium.GeoJson(geojson_data).get_bounds() == [[0, -3], [4, 2]]
|
map.get_bounds() fails for map with GeometryCollection
**Describe the bug**
If you add a GeoJson with a GeometryCollection to a Map, Map.get_bounds fails
**To Reproduce**
```
import folium
m = folium.Map(location=[39.949610, -75.150282], zoom_start=16)
geojson_data = {
"geometries": [
{
"coordinates": [
[
[-86.1570813, 39.7567006],
[-86.1570169, 39.7566965],
[-86.1570169, 39.7566429],
[-86.1566146, 39.7566181],
[-86.1566092, 39.7566676],
[-86.1565288, 39.7566965],
[-86.1567645, 39.7572846],
[-86.1568399, 39.7572821],
[-86.156904, 39.7574413],
[-86.1568345, 39.7574718],
[-86.1568131, 39.7585688],
[-86.1570223, 39.7585729],
[-86.1570227, 39.7585614],
[-86.1570809, 39.7567123],
[-86.1570813, 39.7567006],
]
],
"type": "Polygon",
},
],
"type": "GeometryCollection",
}
folium.GeoJson(geojson_data).add_to(m)
m.get_bounds()
```
**Expected behavior**
I expected this to return a list of two points
**Environment (please complete the following information):**
- Browser [e.g. chrome, firefox]
- Jupyter Notebook or html files?
- Python version (check it with `import sys; print(sys.version_info)`)
sys.version_info(major=3, minor=9, micro=11, releaselevel='final', serial=0)
- folium version (check it with `import folium; print(folium.__version__)`)
0.12.1.post1
- branca version (check it with `import branca; print(branca.__version__)`)
0.5.0
**Additional context**
Add any other context about the problem here.
**Possible solutions**
List any solutions you may have come up with.
folium is maintained by volunteers. Can you help making a fix for this issue?
|
0.0
|
7f50b4058ac566ab2959bf4358c6bdaf0bd60ffa
|
[
"tests/test_features.py::test_geometry_collection_get_bounds"
] |
[
"tests/test_features.py::test_figure_creation",
"tests/test_features.py::test_figure_rendering",
"tests/test_features.py::test_figure_html",
"tests/test_features.py::test_figure_double_rendering",
"tests/test_features.py::test_marker_popups",
"tests/test_features.py::test_divicon",
"tests/test_features.py::test_color_line",
"tests/test_features.py::test_get_vegalite_major_version",
"tests/test_features.py::test_geojson_tooltip",
"tests/test_features.py::test_geojson_marker",
"tests/test_features.py::test_geojson_find_identifier"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2022-10-11 17:44:51+00:00
|
mit
| 5,106 |
|
python-visualization__folium-668
|
diff --git a/folium/plugins/boat_marker.py b/folium/plugins/boat_marker.py
index d6e8856a..faed487e 100644
--- a/folium/plugins/boat_marker.py
+++ b/folium/plugins/boat_marker.py
@@ -65,5 +65,5 @@ class BoatMarker(Marker):
'if it is not in a Figure.')
figure.header.add_child(
- JavascriptLink('https://thomasbrueggemann.github.io/leaflet.boatmarker/js/leaflet.boatmarker.min.js'), # noqa
+ JavascriptLink('https://unpkg.com/leaflet.boatmarker/leaflet.boatmarker.min.js'), # noqa
name='markerclusterjs')
|
python-visualization/folium
|
55dd6578a55d4127997a9d4f577fde37e7575265
|
diff --git a/tests/plugins/test_boat_marker.py b/tests/plugins/test_boat_marker.py
index b6842784..97a5ad5b 100644
--- a/tests/plugins/test_boat_marker.py
+++ b/tests/plugins/test_boat_marker.py
@@ -34,7 +34,7 @@ def test_boat_marker():
out = m._parent.render()
# We verify that the script import is present.
- script = '<script src="https://thomasbrueggemann.github.io/leaflet.boatmarker/js/leaflet.boatmarker.min.js"></script>' # noqa
+ script = '<script src="https://unpkg.com/leaflet.boatmarker/leaflet.boatmarker.min.js"></script>' # noqa
assert script in out
# We verify that the script part is correct.
|
Leaflet.boatmarker is broken in v0.3.0
The reason is probably the move to `leaflet 1.0`.
|
0.0
|
55dd6578a55d4127997a9d4f577fde37e7575265
|
[
"tests/plugins/test_boat_marker.py::test_boat_marker"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-08-23 19:15:39+00:00
|
mit
| 5,107 |
|
python-visualization__folium-866
|
diff --git a/CHANGES.txt b/CHANGES.txt
index fee3bfb2..f845af64 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,8 @@
0.6.0
~~~~~
+- `Popup` accepts new arguments `show` (render open on page load) and `sticky` (popups
+ only close when explicitly clicked) (jwhendy #778)
- Added leaflet-search plugin (ghandic #759)
- Improved Vector Layers docs, notebooks, and optional arguments (ocefpaf #731)
- Implemented `export=False/True` option to the Draw plugin layer for saving
@@ -24,6 +26,7 @@ Bug Fixes
- Fixed numpy array bug (#749) in _flatten
- Unify `get_bounds` routine to avoid wrong responses
- If Path option `fill_color` is present it will override `fill=False`
+- Fix disappearing layer control when using FastMarkerCluster (conengmo #866)
0.5.0
~~~~~
diff --git a/folium/__init__.py b/folium/__init__.py
index 2574ff8e..e03ff878 100644
--- a/folium/__init__.py
+++ b/folium/__init__.py
@@ -23,6 +23,11 @@ from folium.map import (
from folium.vector_layers import Circle, CircleMarker, PolyLine, Polygon, Rectangle # noqa
+import branca
+if tuple(int(x) for x in branca.__version__.split('.')) < (0, 3, 0):
+ raise ImportError('branca version 0.3.0 or higher is required. '
+ 'Update branca with e.g. `pip install branca --upgrade`.')
+
__version__ = get_versions()['version']
del get_versions
diff --git a/folium/map.py b/folium/map.py
index 4680510c..c2fb7261 100644
--- a/folium/map.py
+++ b/folium/map.py
@@ -276,23 +276,30 @@ class Popup(Element):
True if the popup is a template that needs to the rendered first.
max_width: int, default 300
The maximal width of the popup.
+ show: bool, default False
+ True renders the popup open on page load.
+ sticky: bool, default False
+ True prevents map and other popup clicks from closing.
"""
_template = Template(u"""
- var {{this.get_name()}} = L.popup({maxWidth: '{{this.max_width}}'});
+ var {{this.get_name()}} = L.popup({maxWidth: '{{this.max_width}}'
+ {% if this.show or this.sticky %}, autoClose: false{% endif %}
+ {% if this.sticky %}, closeOnClick: false{% endif %}});
{% for name, element in this.html._children.items() %}
var {{name}} = $('{{element.render(**kwargs).replace('\\n',' ')}}')[0];
{{this.get_name()}}.setContent({{name}});
{% endfor %}
- {{this._parent.get_name()}}.bindPopup({{this.get_name()}});
+ {{this._parent.get_name()}}.bindPopup({{this.get_name()}})
+ {% if this.show %}.openPopup(){% endif %};
{% for name, element in this.script._children.items() %}
{{element.render()}}
{% endfor %}
""") # noqa
- def __init__(self, html=None, parse_html=False, max_width=300):
+ def __init__(self, html=None, parse_html=False, max_width=300, show=False, sticky=False):
super(Popup, self).__init__()
self._name = 'Popup'
self.header = Element()
@@ -311,6 +318,8 @@ class Popup(Element):
self.html.add_child(Html(text_type(html), script=script))
self.max_width = max_width
+ self.show = show
+ self.sticky = sticky
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
diff --git a/folium/plugins/fast_marker_cluster.py b/folium/plugins/fast_marker_cluster.py
index b42cd281..d4a8f756 100644
--- a/folium/plugins/fast_marker_cluster.py
+++ b/folium/plugins/fast_marker_cluster.py
@@ -41,11 +41,11 @@ class FastMarkerCluster(MarkerCluster):
"""
_template = Template(u"""
{% macro script(this, kwargs) %}
- {{this._callback}}
- (function(){
- var data = {{this._data}};
- var map = {{this._parent.get_name()}};
+ var {{ this.get_name() }} = (function(){
+ {{this._callback}}
+
+ var data = {{ this._data }};
var cluster = L.markerClusterGroup();
for (var i = 0; i < data.length; i++) {
@@ -54,7 +54,8 @@ class FastMarkerCluster(MarkerCluster):
marker.addTo(cluster);
}
- cluster.addTo(map);
+ cluster.addTo({{ this._parent.get_name() }});
+ return cluster;
})();
{% endmacro %}""")
@@ -66,15 +67,12 @@ class FastMarkerCluster(MarkerCluster):
self._data = _validate_coordinates(data)
if callback is None:
- self._callback = ('var callback;\n' +
- 'callback = function (row) {\n' +
- '\tvar icon, marker;\n' +
- '\t// Returns a L.marker object\n' +
- '\ticon = L.AwesomeMarkers.icon();\n' +
- '\tmarker = L.marker(new L.LatLng(row[0], ' +
- 'row[1]));\n' +
- '\tmarker.setIcon(icon);\n' +
- '\treturn marker;\n' +
- '};')
+ self._callback = """
+ var callback = function (row) {
+ var icon = L.AwesomeMarkers.icon();
+ var marker = L.marker(new L.LatLng(row[0], row[1]));
+ marker.setIcon(icon);
+ return marker;
+ };"""
else:
self._callback = 'var callback = {};'.format(callback)
diff --git a/requirements.txt b/requirements.txt
index f2c4eb37..69e1a836 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,4 +1,4 @@
-branca
+branca>=0.3.0
jinja2
numpy
requests
|
python-visualization/folium
|
c228c261be42d801809e0ba037dbe14b8229fb4b
|
diff --git a/tests/test_map.py b/tests/test_map.py
index 7a2d49ae..846a2a36 100644
--- a/tests/test_map.py
+++ b/tests/test_map.py
@@ -8,6 +8,7 @@ Folium map Tests
from __future__ import (absolute_import, division, print_function)
+from folium import Map
from folium.map import Popup
@@ -18,6 +19,10 @@ tmpl = u"""
""".format
+def _normalize(rendered):
+ return ''.join(rendered.split())
+
+
def test_popup_ascii():
popup = Popup('Some text.')
_id = list(popup.html._children.keys())[0]
@@ -52,3 +57,33 @@ def test_popup_unicode():
'text': u'Ça c'est chouette',
}
assert ''.join(popup.html.render().split()) == ''.join(tmpl(**kw).split())
+
+
+def test_popup_sticky():
+ m = Map()
+ popup = Popup('Some text.', sticky=True).add_to(m)
+ rendered = popup._template.render(this=popup, kwargs={})
+ expected = """
+ var {popup_name} = L.popup({{maxWidth: \'300\', autoClose: false, closeOnClick: false}});
+ var {html_name} = $(\'<div id="{html_name}" style="width: 100.0%; height: 100.0%;">Some text.</div>\')[0];
+ {popup_name}.setContent({html_name});
+ {map_name}.bindPopup({popup_name});
+ """.format(popup_name=popup.get_name(),
+ html_name=list(popup.html._children.keys())[0],
+ map_name=m.get_name())
+ assert _normalize(rendered) == _normalize(expected)
+
+
+def test_popup_show():
+ m = Map()
+ popup = Popup('Some text.', show=True).add_to(m)
+ rendered = popup._template.render(this=popup, kwargs={})
+ expected = """
+ var {popup_name} = L.popup({{maxWidth: \'300\' , autoClose: false}});
+ var {html_name} = $(\'<div id="{html_name}" style="width: 100.0%; height: 100.0%;">Some text.</div>\')[0];
+ {popup_name}.setContent({html_name});
+ {map_name}.bindPopup({popup_name}).openPopup();
+ """.format(popup_name=popup.get_name(),
+ html_name=list(popup.html._children.keys())[0],
+ map_name=m.get_name())
+ assert _normalize(rendered) == _normalize(expected)
|
Layer selector disappears when using FastMarkerCluster()
When I trying to add a FastMarkerCluster() layer to my multilayer map, the layer selector in the top right of the browser window disappears.
#### Code Sample:
```python
import pandas as pd
import folium
df = pd.read_csv(r'raw_data.csv')
data = df[['lat', 'long']].values.tolist()
m = folium.Map()
folium.plugins.HeatMap(data, name="layer1").add_to(m)
folium.plugins.HeatMap(data, name="layer2").add_to(m)
#folium.plugins.FastMarkerCluster(data, name="layer3").add_to(m)
folium.LayerControl().add_to(m)
m.save("map.html")
```
#### Problem description
When I run the above as is, I get a layer selector in the top right which I can use to switch on/off the two heatmap layers. When I uncomment the FastMarkerCluster() line and run the code, the cluster layer is added to the map, however the layer selector is no longer present.
#### Expected Output
I expect the layer selector in the top right corner of the browser window to be present when adding layers using FastMarkerCluster()
#### Output of ``folium.__version__``
'0.5.0+111.gc228c26'
|
0.0
|
c228c261be42d801809e0ba037dbe14b8229fb4b
|
[
"tests/test_map.py::test_popup_sticky",
"tests/test_map.py::test_popup_show"
] |
[
"tests/test_map.py::test_popup_ascii",
"tests/test_map.py::test_popup_quotes",
"tests/test_map.py::test_popup_unicode"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-12 10:41:08+00:00
|
mit
| 5,108 |
|
python-visualization__folium-886
|
diff --git a/folium/plugins/heat_map_withtime.py b/folium/plugins/heat_map_withtime.py
index 839da494..d4dd2830 100644
--- a/folium/plugins/heat_map_withtime.py
+++ b/folium/plugins/heat_map_withtime.py
@@ -160,7 +160,7 @@ class HeatMapWithTime(Layer):
figure.header.add_child(
JavascriptLink(
- 'https://cdnjs.cloudflare.com/ajax/libs/heatmap.js/2.0.2/heatmap.min.js'),
+ 'https://rawgit.com/python-visualization/folium/master/folium/templates/pa7_hm.min.js'), # noqa
name='heatmap.min.js')
figure.header.add_child(
diff --git a/folium/templates/pa7_hm.min.js b/folium/templates/pa7_hm.min.js
new file mode 100644
index 00000000..3d2f2c90
--- /dev/null
+++ b/folium/templates/pa7_hm.min.js
@@ -0,0 +1,9 @@
+/*
+ * heatmap.js v2.0.5 | JavaScript Heatmap Library
+ *
+ * Copyright 2008-2016 Patrick Wied <[email protected]> - All rights reserved.
+ * Dual licensed under MIT and Beerware license
+ *
+ * :: 2016-09-05 01:16
+ */
+(function(a,b,c){if(typeof module!=="undefined"&&module.exports){module.exports=c()}else if(typeof define==="function"&&define.amd){define(c)}else{b[a]=c()}})("h337",this,function(){var a={defaultRadius:40,defaultRenderer:"canvas2d",defaultGradient:{.25:"rgb(0,0,255)",.55:"rgb(0,255,0)",.85:"yellow",1:"rgb(255,0,0)"},defaultMaxOpacity:1,defaultMinOpacity:0,defaultBlur:.85,defaultXField:"x",defaultYField:"y",defaultValueField:"value",plugins:{}};var b=function h(){var b=function d(a){this._coordinator={};this._data=[];this._radi=[];this._min=10;this._max=1;this._xField=a["xField"]||a.defaultXField;this._yField=a["yField"]||a.defaultYField;this._valueField=a["valueField"]||a.defaultValueField;if(a["radius"]){this._cfgRadius=a["radius"]}};var c=a.defaultRadius;b.prototype={_organiseData:function(a,b){var d=a[this._xField];var e=a[this._yField];var f=this._radi;var g=this._data;var h=this._max;var i=this._min;var j=a[this._valueField]||1;var k=a.radius||this._cfgRadius||c;if(!g[d]){g[d]=[];f[d]=[]}if(!g[d][e]){g[d][e]=j;f[d][e]=k}else{g[d][e]+=j}var l=g[d][e];if(l>h){if(!b){this._max=l}else{this.setDataMax(l)}return false}else if(l<i){if(!b){this._min=l}else{this.setDataMin(l)}return false}else{return{x:d,y:e,value:j,radius:k,min:i,max:h}}},_unOrganizeData:function(){var a=[];var b=this._data;var c=this._radi;for(var d in b){for(var e in b[d]){a.push({x:d,y:e,radius:c[d][e],value:b[d][e]})}}return{min:this._min,max:this._max,data:a}},_onExtremaChange:function(){this._coordinator.emit("extremachange",{min:this._min,max:this._max})},addData:function(){if(arguments[0].length>0){var a=arguments[0];var b=a.length;while(b--){this.addData.call(this,a[b])}}else{var c=this._organiseData(arguments[0],true);if(c){if(this._data.length===0){this._min=this._max=c.value}this._coordinator.emit("renderpartial",{min:this._min,max:this._max,data:[c]})}}return this},setData:function(a){var b=a.data;var c=b.length;this._data=[];this._radi=[];for(var d=0;d<c;d++){this._organiseData(b[d],false)}this._max=a.max;this._min=a.min||0;this._onExtremaChange();this._coordinator.emit("renderall",this._getInternalData());return this},removeData:function(){},setDataMax:function(a){this._max=a;this._onExtremaChange();this._coordinator.emit("renderall",this._getInternalData());return this},setDataMin:function(a){this._min=a;this._onExtremaChange();this._coordinator.emit("renderall",this._getInternalData());return this},setCoordinator:function(a){this._coordinator=a},_getInternalData:function(){return{max:this._max,min:this._min,data:this._data,radi:this._radi}},getData:function(){return this._unOrganizeData()}};return b}();var c=function i(){var a=function(a){var b=a.gradient||a.defaultGradient;var c=document.createElement("canvas");var d=c.getContext("2d");c.width=256;c.height=1;var e=d.createLinearGradient(0,0,256,1);for(var f in b){e.addColorStop(f,b[f])}d.fillStyle=e;d.fillRect(0,0,256,1);return d.getImageData(0,0,256,1).data};var b=function(a,b){var c=document.createElement("canvas");var d=c.getContext("2d");var e=a;var f=a;c.width=c.height=a*2;if(b==1){d.beginPath();d.arc(e,f,a,0,2*Math.PI,false);d.fillStyle="rgba(0,0,0,1)";d.fill()}else{var g=d.createRadialGradient(e,f,a*b,e,f,a);g.addColorStop(0,"rgba(0,0,0,1)");g.addColorStop(1,"rgba(0,0,0,0)");d.fillStyle=g;d.fillRect(0,0,2*a,2*a)}return c};var c=function(a){var b=[];var c=a.min;var d=a.max;var e=a.radi;var a=a.data;var f=Object.keys(a);var g=f.length;while(g--){var h=f[g];var i=Object.keys(a[h]);var j=i.length;while(j--){var k=i[j];var l=a[h][k];var m=e[h][k];b.push({x:h,y:k,value:l,radius:m})}}return{min:c,max:d,data:b}};function d(b){var c=b.container;var d=this.shadowCanvas=document.createElement("canvas");var e=this.canvas=b.canvas||document.createElement("canvas");var f=this._renderBoundaries=[1e4,1e4,0,0];var g=getComputedStyle(b.container)||{};e.className="heatmap-canvas";this._width=e.width=d.width=b.width||+g.width.replace(/px/,"");this._height=e.height=d.height=b.height||+g.height.replace(/px/,"");this.shadowCtx=d.getContext("2d");this.ctx=e.getContext("2d");e.style.cssText=d.style.cssText="position:absolute;left:0;top:0;";c.style.position="relative";c.appendChild(e);this._palette=a(b);this._templates={};this._setStyles(b)}d.prototype={renderPartial:function(a){if(a.data.length>0){this._drawAlpha(a);this._colorize()}},renderAll:function(a){this._clear();if(a.data.length>0){this._drawAlpha(c(a));this._colorize()}},_updateGradient:function(b){this._palette=a(b)},updateConfig:function(a){if(a["gradient"]){this._updateGradient(a)}this._setStyles(a)},setDimensions:function(a,b){this._width=a;this._height=b;this.canvas.width=this.shadowCanvas.width=a;this.canvas.height=this.shadowCanvas.height=b},_clear:function(){this.shadowCtx.clearRect(0,0,this._width,this._height);this.ctx.clearRect(0,0,this._width,this._height)},_setStyles:function(a){this._blur=a.blur==0?0:a.blur||a.defaultBlur;if(a.backgroundColor){this.canvas.style.backgroundColor=a.backgroundColor}this._width=this.canvas.width=this.shadowCanvas.width=a.width||this._width;this._height=this.canvas.height=this.shadowCanvas.height=a.height||this._height;this._opacity=(a.opacity||0)*255;this._maxOpacity=(a.maxOpacity||a.defaultMaxOpacity)*255;this._minOpacity=(a.minOpacity||a.defaultMinOpacity)*255;this._useGradientOpacity=!!a.useGradientOpacity},_drawAlpha:function(a){var c=this._min=a.min;var d=this._max=a.max;var a=a.data||[];var e=a.length;var f=1-this._blur;while(e--){var g=a[e];var h=g.x;var i=g.y;var j=g.radius;var k=Math.min(g.value,d);var l=h-j;var m=i-j;var n=this.shadowCtx;var o;if(!this._templates[j]){this._templates[j]=o=b(j,f)}else{o=this._templates[j]}var p=(k-c)/(d-c);n.globalAlpha=p<.01?.01:p;n.drawImage(o,l,m);if(l<this._renderBoundaries[0]){this._renderBoundaries[0]=l}if(m<this._renderBoundaries[1]){this._renderBoundaries[1]=m}if(l+2*j>this._renderBoundaries[2]){this._renderBoundaries[2]=l+2*j}if(m+2*j>this._renderBoundaries[3]){this._renderBoundaries[3]=m+2*j}}},_colorize:function(){var a=this._renderBoundaries[0];var b=this._renderBoundaries[1];var c=this._renderBoundaries[2]-a;var d=this._renderBoundaries[3]-b;var e=this._width;var f=this._height;var g=this._opacity;var h=this._maxOpacity;var i=this._minOpacity;var j=this._useGradientOpacity;if(a<0){a=0}if(b<0){b=0}if(a+c>e){c=e-a}if(b+d>f){d=f-b}var k=this.shadowCtx.getImageData(a,b,c,d);var l=k.data;var m=l.length;var n=this._palette;for(var o=3;o<m;o+=4){var p=l[o];var q=p*4;if(!q){continue}var r;if(g>0){r=g}else{if(p<h){if(p<i){r=i}else{r=p}}else{r=h}}l[o-3]=n[q];l[o-2]=n[q+1];l[o-1]=n[q+2];l[o]=j?n[q+3]:r}k.data=l;this.ctx.putImageData(k,a,b);this._renderBoundaries=[1e3,1e3,0,0]},getValueAt:function(a){var b;var c=this.shadowCtx;var d=c.getImageData(a.x,a.y,1,1);var e=d.data[3];var f=this._max;var g=this._min;b=Math.abs(f-g)*(e/255)>>0;return b},getDataURL:function(){return this.canvas.toDataURL()}};return d}();var d=function j(){var b=false;if(a["defaultRenderer"]==="canvas2d"){b=c}return b}();var e={merge:function(){var a={};var b=arguments.length;for(var c=0;c<b;c++){var d=arguments[c];for(var e in d){a[e]=d[e]}}return a}};var f=function k(){var c=function h(){function a(){this.cStore={}}a.prototype={on:function(a,b,c){var d=this.cStore;if(!d[a]){d[a]=[]}d[a].push(function(a){return b.call(c,a)})},emit:function(a,b){var c=this.cStore;if(c[a]){var d=c[a].length;for(var e=0;e<d;e++){var f=c[a][e];f(b)}}}};return a}();var f=function(a){var b=a._renderer;var c=a._coordinator;var d=a._store;c.on("renderpartial",b.renderPartial,b);c.on("renderall",b.renderAll,b);c.on("extremachange",function(b){a._config.onExtremaChange&&a._config.onExtremaChange({min:b.min,max:b.max,gradient:a._config["gradient"]||a._config["defaultGradient"]})});d.setCoordinator(c)};function g(){var g=this._config=e.merge(a,arguments[0]||{});this._coordinator=new c;if(g["plugin"]){var h=g["plugin"];if(!a.plugins[h]){throw new Error("Plugin '"+h+"' not found. Maybe it was not registered.")}else{var i=a.plugins[h];this._renderer=new i.renderer(g);this._store=new i.store(g)}}else{this._renderer=new d(g);this._store=new b(g)}f(this)}g.prototype={addData:function(){this._store.addData.apply(this._store,arguments);return this},removeData:function(){this._store.removeData&&this._store.removeData.apply(this._store,arguments);return this},setData:function(){this._store.setData.apply(this._store,arguments);return this},setDataMax:function(){this._store.setDataMax.apply(this._store,arguments);return this},setDataMin:function(){this._store.setDataMin.apply(this._store,arguments);return this},configure:function(a){this._config=e.merge(this._config,a);this._renderer.updateConfig(this._config);this._coordinator.emit("renderall",this._store._getInternalData());return this},repaint:function(){this._coordinator.emit("renderall",this._store._getInternalData());return this},getData:function(){return this._store.getData()},getDataURL:function(){return this._renderer.getDataURL()},getValueAt:function(a){if(this._store.getValueAt){return this._store.getValueAt(a)}else if(this._renderer.getValueAt){return this._renderer.getValueAt(a)}else{return null}}};return g}();var g={create:function(a){return new f(a)},register:function(b,c){a.plugins[b]=c}};return g});
|
python-visualization/folium
|
5bcb7b93e57965104d9044355969359c7dd9ec4b
|
diff --git a/tests/plugins/test_heat_map_withtime.py b/tests/plugins/test_heat_map_withtime.py
index 1901278b..c3c988cb 100644
--- a/tests/plugins/test_heat_map_withtime.py
+++ b/tests/plugins/test_heat_map_withtime.py
@@ -32,7 +32,7 @@ def test_heat_map_with_time():
# We verify that the script imports are present.
script = '<script src="https://rawgit.com/socib/Leaflet.TimeDimension/master/dist/leaflet.timedimension.min.js"></script>' # noqa
assert script in out
- script = '<script src="https://cdnjs.cloudflare.com/ajax/libs/heatmap.js/2.0.2/heatmap.min.js"></script>' # noqa
+ script = '<script src="https://rawgit.com/python-visualization/folium/master/folium/templates/pa7_hm.min.js"></script>' # noqa
assert script in out
script = '<script src="https://rawgit.com/pa7/heatmap.js/develop/plugins/leaflet-heatmap/leaflet-heatmap.js"></script>' # noqa
assert script in out
|
Heatmap javascript resources blocked by adblockers
#### Problem description
Compared with Heatmap.ipynb, HeatMapWithTime.ipynb does not show any result.
#### Expected Output
We run the code, the code is ok, but heatmap shows up?
|
0.0
|
5bcb7b93e57965104d9044355969359c7dd9ec4b
|
[
"tests/plugins/test_heat_map_withtime.py::test_heat_map_with_time"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-19 14:10:56+00:00
|
mit
| 5,109 |
|
python273__telegraph-20
|
diff --git a/telegraph/utils.py b/telegraph/utils.py
index c4b9f8b..41b6df9 100644
--- a/telegraph/utils.py
+++ b/telegraph/utils.py
@@ -83,6 +83,11 @@ class HtmlToNodesParser(HTMLParser):
if tag in VOID_ELEMENTS:
return
+ if not len(self.parent_nodes):
+ raise InvalidHTML('"{}" missing start tag'.format(
+ tag
+ ))
+
self.current_nodes = self.parent_nodes.pop()
last_node = self.current_nodes[-1]
|
python273/telegraph
|
945656298692f6c03aae325f02344caa137f9f7d
|
diff --git a/tests/test_html_converter.py b/tests/test_html_converter.py
index 42af23a..86fecb1 100644
--- a/tests/test_html_converter.py
+++ b/tests/test_html_converter.py
@@ -19,7 +19,7 @@ NODES_TEST_LIST = [
'attrs': {'href': 'https://telegra.ph/'},
'children': ['Test link</a>']
}]
- },
+ },
{'tag': 'figure', 'children': [
{'tag': 'img', 'attrs': {'src': '/file/6c2ecfdfd6881d37913fa.png'}},
{'tag': 'figcaption'}
@@ -45,6 +45,8 @@ HTML_MULTI_LINES_NODES_LIST = [
]},
]
+HTML_NO_STARTTAG = "</a><h1></h1>"
+
class TestHTMLConverter(TestCase):
def test_html_to_nodes(self):
@@ -130,3 +132,7 @@ class TestHTMLConverter(TestCase):
]
self.assertEqual(clear_whitespace_nodes(nodes)[0], expected)
+
+ def test_no_starttag_node(self):
+ with self.assertRaises(InvalidHTML):
+ html_to_nodes(HTML_NO_STARTTAG)
|
IndexErrortelegraph.utils in handle_endtag error pop from empty list
os:linux
version: "==1.3.2"
https://sentry.io/share/issue/f0d73c02680a4f0ea637437b236e9ec9/
|
0.0
|
945656298692f6c03aae325f02344caa137f9f7d
|
[
"tests/test_html_converter.py::TestHTMLConverter::test_no_starttag_node"
] |
[
"tests/test_html_converter.py::TestHTMLConverter::test_clear_whitespace_nodes",
"tests/test_html_converter.py::TestHTMLConverter::test_html_to_nodes",
"tests/test_html_converter.py::TestHTMLConverter::test_html_to_nodes_invalid_html",
"tests/test_html_converter.py::TestHTMLConverter::test_html_to_nodes_multi_line",
"tests/test_html_converter.py::TestHTMLConverter::test_html_to_nodes_not_allowed_tag",
"tests/test_html_converter.py::TestHTMLConverter::test_nodes_to_html",
"tests/test_html_converter.py::TestHTMLConverter::test_nodes_to_html_blank",
"tests/test_html_converter.py::TestHTMLConverter::test_nodes_to_html_nested"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-02-25 10:01:13+00:00
|
mit
| 5,110 |
|
python__bedevere-617
|
diff --git a/bedevere/prtype.py b/bedevere/prtype.py
index 0105e50..bccd879 100644
--- a/bedevere/prtype.py
+++ b/bedevere/prtype.py
@@ -43,7 +43,7 @@ async def classify_by_filepaths(gh, pull_request, filenames):
if util.is_news_dir(filename):
news = True
filepath = pathlib.PurePath(filename)
- if filepath.suffix == ".rst":
+ if filepath.suffix == ".rst" or filepath.name == ".nitignore":
docs = True
elif filepath.name.startswith("test_"):
tests = True
|
python/bedevere
|
b5bcd24e79ad72b47582f89f7e7053f5b3157fa4
|
diff --git a/tests/test_prtype.py b/tests/test_prtype.py
index 4fcaf0c..c9b0777 100644
--- a/tests/test_prtype.py
+++ b/tests/test_prtype.py
@@ -85,6 +85,26 @@ async def test_docs_no_news():
assert gh.post_data[0] == [Labels.docs.value, Labels.skip_news.value]
+async def test_docs_no_news_with_dotnitignore():
+ filenames = {"path/to/docs1.rst", "path/to/.nitignore"}
+ issue = {"labels": [], "labels_url": "https://api.github.com/some/label"}
+ gh = FakeGH(getitem=issue)
+ event_data = {
+ "action": "opened",
+ "number": 1234,
+ "pull_request": {
+ "url": "https://api.github.com/repos/cpython/python/pulls/1234",
+ "statuses_url": "https://api.github.com/some/status",
+ "issue_url": "https://api.github.com/repos/cpython/python/issue/1234",
+ },
+ }
+ await prtype.classify_by_filepaths(gh, event_data["pull_request"], filenames)
+ assert gh.getitem_url == "https://api.github.com/repos/cpython/python/issue/1234"
+ assert len(gh.post_url) == 1
+ assert gh.post_url[0] == "https://api.github.com/some/label"
+ assert gh.post_data[0] == [Labels.docs.value, Labels.skip_news.value]
+
+
async def test_docs_and_news():
filenames = {"/path/to/docs1.rst", f"Misc/NEWS.d/next/Lib/{GOOD_BASENAME}"}
issue = {"labels": [], "labels_url": "https://api.github.com/some/label"}
|
Add docs label for PRs that touch Doc/tools/.nitignore
See e.g. https://github.com/python/cpython/pull/114280 or https://github.com/python/cpython/pull/114194
|
0.0
|
b5bcd24e79ad72b47582f89f7e7053f5b3157fa4
|
[
"tests/test_prtype.py::test_docs_no_news_with_dotnitignore"
] |
[
"tests/test_prtype.py::test_no_files",
"tests/test_prtype.py::test_news_only",
"tests/test_prtype.py::test_docs_no_news",
"tests/test_prtype.py::test_docs_and_news",
"tests/test_prtype.py::test_tests_only",
"tests/test_prtype.py::test_docs_and_tests",
"tests/test_prtype.py::test_leave_existing_type_labels",
"tests/test_prtype.py::test_do_not_post_if_nothing_to_apply",
"tests/test_prtype.py::test_news_and_tests",
"tests/test_prtype.py::test_other_files"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-01-19 08:13:31+00:00
|
apache-2.0
| 5,111 |
|
python__cherry-picker-110
|
diff --git a/cherry_picker/cherry_picker.py b/cherry_picker/cherry_picker.py
index 66bde15..3e59f39 100755
--- a/cherry_picker/cherry_picker.py
+++ b/cherry_picker/cherry_picker.py
@@ -198,7 +198,7 @@ class CherryPicker:
cmd = ["git", "config", "--get", f"remote.{self.pr_remote}.url"]
result = self.run_cmd(cmd, required_real_result=True)
# implicit ssh URIs use : to separate host from user, others just use /
- username = result.replace(":", "/").split("/")[-2]
+ username = result.replace(":", "/").rstrip("/").split("/")[-2]
return username
def get_cherry_pick_branch(self, maint_branch):
|
python/cherry-picker
|
c7a504fef3e261aa3c5f22acb96604c86ce96d81
|
diff --git a/cherry_picker/test_cherry_picker.py b/cherry_picker/test_cherry_picker.py
index bffb11d..3a9f670 100644
--- a/cherry_picker/test_cherry_picker.py
+++ b/cherry_picker/test_cherry_picker.py
@@ -343,10 +343,13 @@ def test_get_pr_url(config):
[
b"[email protected]:mock_user/cpython.git",
b"[email protected]:mock_user/cpython",
+ b"[email protected]:mock_user/cpython/",
b"ssh://[email protected]/mock_user/cpython.git",
b"ssh://[email protected]/mock_user/cpython",
+ b"ssh://[email protected]/mock_user/cpython/",
b"https://github.com/mock_user/cpython.git",
b"https://github.com/mock_user/cpython",
+ b"https://github.com/mock_user/cpython/",
],
)
def test_username(url, config):
|
Username detection fails with a trailing slash
I have my remote origin set to ``https://github.com/AA-Turner/cpython/``.
```ps1con
PS> git remote -v
origin https://github.com/AA-Turner/cpython/ (fetch)
origin https://github.com/AA-Turner/cpython/ (push)
upstream https://github.com/python/cpython/ (fetch)
upstream https://github.com/python/cpython/ (push)
```
``cherry_picker`` runs ``git config --get remote.origin.url``, which returns the above url, and then runs ``username = result.replace(":", "/").split("/")[-2]``. This returns ``cpython``, which means that I have to manually edit the URL on every backport.
``cherry_picker`` should instead trim any trailing slash.
A
|
0.0
|
c7a504fef3e261aa3c5f22acb96604c86ce96d81
|
[
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython/]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython/]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython/]"
] |
[
"cherry_picker/test_cherry_picker.py::test_get_base_branch",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_which_has_dashes",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[backport-22a594a]",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[prefix-22a594a-2.7]",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[backport-22a594a-base]",
"cherry_picker/test_cherry_picker.py::test_get_current_branch",
"cherry_picker/test_cherry_picker.py::test_get_full_sha_from_short",
"cherry_picker/test_cherry_picker.py::test_get_author_info_from_short_sha",
"cherry_picker/test_cherry_picker.py::test_sorted_branch[input_branches0-sorted_branches0]",
"cherry_picker/test_cherry_picker.py::test_sorted_branch[input_branches1-sorted_branches1]",
"cherry_picker/test_cherry_picker.py::test_invalid_branches[input_branches0]",
"cherry_picker/test_cherry_picker.py::test_invalid_branches[input_branches1]",
"cherry_picker/test_cherry_picker.py::test_get_cherry_pick_branch",
"cherry_picker/test_cherry_picker.py::test_upstream_name[upstream-None]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[upstream-upstream]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[origin-None]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[origin-origin]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[python-python]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-upstream-None]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[origin-upstream-upstream]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-origin-None]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[upstream-origin-origin]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[origin-python-python]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-python-None]",
"cherry_picker/test_cherry_picker.py::test_get_pr_url",
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message_without_links_replacement",
"cherry_picker/test_cherry_picker.py::test_is_cpython_repo",
"cherry_picker/test_cherry_picker.py::test_is_not_cpython_repo",
"cherry_picker/test_cherry_picker.py::test_find_config",
"cherry_picker/test_cherry_picker.py::test_find_config_not_found",
"cherry_picker/test_cherry_picker.py::test_find_config_not_git",
"cherry_picker/test_cherry_picker.py::test_load_full_config",
"cherry_picker/test_cherry_picker.py::test_load_partial_config",
"cherry_picker/test_cherry_picker.py::test_load_config_no_head_sha",
"cherry_picker/test_cherry_picker.py::test_normalize_long_commit_message",
"cherry_picker/test_cherry_picker.py::test_normalize_short_commit_message",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message_with_trailers[Fix",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_negative[/some/path/without/revision]",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_negative[HEAD:some/non-existent/path]",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_uncommitted",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read",
"cherry_picker/test_cherry_picker.py::test_states",
"cherry_picker/test_cherry_picker.py::test_paused_flow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[fetch_upstream-Workflow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[checkout_default_branch-Workflow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[checkout_previous_branch-Workflow",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_checkout_previous_branch",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_fail",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_checkout_fail",
"cherry_picker/test_cherry_picker.py::test_cherry_pick",
"cherry_picker/test_cherry_picker.py::test_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_get_state_and_verify_fail",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_fail",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_interactive",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_botflow",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_no_auto_pr",
"cherry_picker/test_cherry_picker.py::test_backport_no_branch",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_crash_ignored",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_branch_already_exists",
"cherry_picker/test_cherry_picker.py::test_backport_success",
"cherry_picker/test_cherry_picker.py::test_backport_pause_and_continue[True-True]",
"cherry_picker/test_cherry_picker.py::test_backport_pause_and_continue[True-False]",
"cherry_picker/test_cherry_picker.py::test_backport_pause_and_continue[False-True]",
"cherry_picker/test_cherry_picker.py::test_backport_pause_and_continue[False-False]",
"cherry_picker/test_cherry_picker.py::test_continue_cherry_pick_invalid_state",
"cherry_picker/test_cherry_picker.py::test_continue_cherry_pick_invalid_branch",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_invalid_state",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_success",
"cherry_picker/test_cherry_picker.py::test_cli_invoked"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-01-20 12:25:13+00:00
|
apache-2.0
| 5,112 |
|
python__cherry-picker-23
|
diff --git a/.travis.yml b/.travis.yml
index 467af9e..ab0b9d7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,16 +4,22 @@ git:
depth: false
-dist: xenial
+dist: focal
cache: pip
language: python
python:
+- "3.9"
+- "3.8"
- "3.7"
- "3.6"
-- "nightly" # currently, it's 3.8-dev
+- "nightly" # currently, it's 3.10
+matrix:
+ allow_failures:
+ - python: "nightly"
+ dist: focal
install:
- python -m pip install --upgrade flit pip
diff --git a/cherry_picker/__init__.py b/cherry_picker/__init__.py
index 34837f2..f8cd9a5 100644
--- a/cherry_picker/__init__.py
+++ b/cherry_picker/__init__.py
@@ -1,2 +1,2 @@
-"""Backport CPython changes from master to maintenance branches."""
-__version__ = '1.3.3.dev1'
+"""Backport CPython changes from main to maintenance branches."""
+__version__ = "2.0.0.dev1"
diff --git a/cherry_picker/__main__.py b/cherry_picker/__main__.py
index 437561a..cc02b31 100644
--- a/cherry_picker/__main__.py
+++ b/cherry_picker/__main__.py
@@ -1,4 +1,4 @@
from .cherry_picker import cherry_pick_cli
-if __name__ == '__main__':
+if __name__ == "__main__":
cherry_pick_cli()
diff --git a/cherry_picker/cherry_picker.py b/cherry_picker/cherry_picker.py
index 4f24e44..a14068c 100755
--- a/cherry_picker/cherry_picker.py
+++ b/cherry_picker/cherry_picker.py
@@ -25,7 +25,7 @@ DEFAULT_CONFIG = collections.ChainMap(
"repo": "cpython",
"check_sha": "7f777ed95a19224294949e1b4ce56bbffcb1fe9f",
"fix_commit_msg": True,
- "default_branch": "master",
+ "default_branch": "main",
}
)
diff --git a/readme.rst b/readme.rst
index 00ad57f..ad95222 100644
--- a/readme.rst
+++ b/readme.rst
@@ -11,7 +11,7 @@ Usage (from a cloned CPython directory) ::
About
=====
-This tool is used to backport CPython changes from ``master`` into one or more
+This tool is used to backport CPython changes from ``main`` into one or more
of the maintenance branches (``3.6``, ``3.5``, ``2.7``).
``cherry_picker`` can be configured to backport other projects with similar
@@ -76,10 +76,10 @@ Commit sha1
-----------
The commit sha1 for cherry-picking is the squashed commit that was merged to
-the ``master`` branch. On the merged pull request, scroll to the bottom of the
+the ``main`` branch. On the merged pull request, scroll to the bottom of the
page. Find the event that says something like::
- <coredeveloper> merged commit <commit_sha1> into python:master <sometime> ago.
+ <coredeveloper> merged commit <commit_sha1> into python:main <sometime> ago.
By following the link to ``<commit_sha1>``, you will get the full commit hash.
Use the full commit hash for ``cherry_picker.py``.
@@ -136,7 +136,7 @@ Available config options::
repo Project's default branch name,
e.g "devel" for https://github.com/ansible/ansible
- ("master" by default)
+ ("main" by default)
To customize the tool for used by other project:
@@ -190,13 +190,13 @@ What this will do:
(venv) $ git checkout -b backport-6de2b78-3.5 upstream/3.5
(venv) $ git cherry-pick -x 6de2b7817f-some-commit-sha1-d064
(venv) $ git push origin backport-6de2b78-3.5
- (venv) $ git checkout master
+ (venv) $ git checkout main
(venv) $ git branch -D backport-6de2b78-3.5
(venv) $ git checkout -b backport-6de2b78-3.6 upstream/3.6
(venv) $ git cherry-pick -x 6de2b7817f-some-commit-sha1-d064
(venv) $ git push origin backport-6de2b78-3.6
- (venv) $ git checkout master
+ (venv) $ git checkout main
(venv) $ git branch -D backport-6de2b78-3.6
In case of merge conflicts or errors, the following message will be displayed::
@@ -226,14 +226,14 @@ steps it would execute without actually executing any of them. For example::
dry_run: git cherry-pick -x 1e32a1be4a1705e34011770026cb64ada2d340b5
dry_run: git push pr backport-1e32a1b-3.6
dry_run: Create new PR: https://github.com/python/cpython/compare/3.6...ncoghlan:backport-1e32a1b-3.6?expand=1
- dry_run: git checkout master
+ dry_run: git checkout main
dry_run: git branch -D backport-1e32a1b-3.6
Now backporting '1e32a1be4a1705e34011770026cb64ada2d340b5' into '3.5'
dry_run: git checkout -b backport-1e32a1b-3.5 origin/3.5
dry_run: git cherry-pick -x 1e32a1be4a1705e34011770026cb64ada2d340b5
dry_run: git push pr backport-1e32a1b-3.5
dry_run: Create new PR: https://github.com/python/cpython/compare/3.5...ncoghlan:backport-1e32a1b-3.5?expand=1
- dry_run: git checkout master
+ dry_run: git checkout main
dry_run: git branch -D backport-1e32a1b-3.5
`--pr-remote` option
@@ -291,7 +291,7 @@ The url of the pull request page looks similar to the following::
Press the ``Create Pull Request`` button.
Bedevere will then remove the ``needs backport to ...`` label from the original
-pull request against ``master``.
+pull request against ``main``.
Running Tests
@@ -329,15 +329,17 @@ in the directory where ``pyproject.toml`` exists::
.. |pypi status| image:: https://img.shields.io/pypi/v/cherry-picker.svg
:target: https://pypi.org/project/cherry-picker/
-.. |travis status| image:: https://travis-ci.com/python/cherry-picker.svg?branch=master
+.. |travis status| image:: https://travis-ci.com/python/cherry-picker.svg?branch=main
:target: https://travis-ci.com/python/cherry-picker
Changelog
=========
-1.3.3 (in development)
+2.0.0 (in development)
----------------------
+- Support the ``main`` branch by default. To use a different default branch,
+ please configure it in the ``.cherry-picker.toml`` file.
1.3.2
-----
|
python/cherry-picker
|
39e8d6d10eecae6b6d096e3e03b69c5104ba5507
|
diff --git a/cherry_picker/test.py b/cherry_picker/test.py
index 6dd5b76..983e053 100644
--- a/cherry_picker/test.py
+++ b/cherry_picker/test.py
@@ -52,7 +52,7 @@ def cd():
@pytest.fixture
def git_init():
- git_init_cmd = "git", "init", "."
+ git_init_cmd = "git", "init", "--initial-branch=main", "."
return lambda: subprocess.run(git_init_cmd, check=True)
@@ -143,8 +143,8 @@ def test_get_base_branch_invalid(subprocess_check_output, cherry_pick_branch):
@mock.patch("subprocess.check_output")
def test_get_current_branch(subprocess_check_output):
- subprocess_check_output.return_value = b"master"
- assert get_current_branch() == "master"
+ subprocess_check_output.return_value = b"main"
+ assert get_current_branch() == "main"
@mock.patch("subprocess.check_output")
@@ -368,7 +368,7 @@ def test_load_partial_config(tmp_git_repo_dir, git_add, git_commit):
"repo": "core-workfolow",
"team": "python",
"fix_commit_msg": True,
- "default_branch": "master",
+ "default_branch": "main",
},
)
@@ -608,7 +608,9 @@ def test_cherry_pick(tmp_git_repo_dir, git_add, git_branch, git_commit, git_chec
cherry_picker.cherry_pick()
-def test_cherry_pick_fail(tmp_git_repo_dir,):
+def test_cherry_pick_fail(
+ tmp_git_repo_dir,
+):
with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
cherry_picker = CherryPicker("origin", "xxx", [])
@@ -616,7 +618,9 @@ def test_cherry_pick_fail(tmp_git_repo_dir,):
cherry_picker.cherry_pick()
-def test_get_state_and_verify_fail(tmp_git_repo_dir,):
+def test_get_state_and_verify_fail(
+ tmp_git_repo_dir,
+):
class tested_state:
name = "invalid_state"
@@ -648,7 +652,7 @@ def test_push_to_remote_fail(tmp_git_repo_dir):
with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
cherry_picker = CherryPicker("origin", "xxx", [])
- cherry_picker.push_to_remote("master", "backport-branch-test")
+ cherry_picker.push_to_remote("main", "backport-branch-test")
assert get_state() == WORKFLOW_STATES.PUSHING_TO_REMOTE_FAILED
@@ -659,7 +663,7 @@ def test_push_to_remote_interactive(tmp_git_repo_dir):
with mock.patch.object(cherry_picker, "run_cmd"), mock.patch.object(
cherry_picker, "open_pr"
), mock.patch.object(cherry_picker, "get_pr_url", return_value="https://pr_url"):
- cherry_picker.push_to_remote("master", "backport-branch-test")
+ cherry_picker.push_to_remote("main", "backport-branch-test")
assert get_state() == WORKFLOW_STATES.PR_OPENING
@@ -671,7 +675,7 @@ def test_push_to_remote_botflow(tmp_git_repo_dir, monkeypatch):
with mock.patch.object(cherry_picker, "run_cmd"), mock.patch.object(
cherry_picker, "create_gh_pr"
):
- cherry_picker.push_to_remote("master", "backport-branch-test")
+ cherry_picker.push_to_remote("main", "backport-branch-test")
assert get_state() == WORKFLOW_STATES.PR_CREATING
|
Use the main branch by default.
After 2021-05-03, CPython's default branch will become `main`.
Since cherry-picker was designed for CPython initially, it would be great to use the `main` branch when backporting.
Others can configure the branch name using the ``default_branch`` config option, documented in https://github.com/python/cherry-picker#options
|
0.0
|
39e8d6d10eecae6b6d096e3e03b69c5104ba5507
|
[
"cherry_picker/test.py::test_load_partial_config",
"cherry_picker/test.py::test_cleanup_branch",
"cherry_picker/test.py::test_cleanup_branch_fail",
"cherry_picker/test.py::test_backport_success",
"cherry_picker/test.py::test_backport_pause_and_continue",
"cherry_picker/test.py::test_abort_cherry_pick_success"
] |
[
"cherry_picker/test.py::test_get_base_branch",
"cherry_picker/test.py::test_get_base_branch_which_has_dashes",
"cherry_picker/test.py::test_get_base_branch_invalid[backport-22a594a]",
"cherry_picker/test.py::test_get_base_branch_invalid[prefix-22a594a-2.7]",
"cherry_picker/test.py::test_get_base_branch_invalid[backport-22a594a-base]",
"cherry_picker/test.py::test_get_current_branch",
"cherry_picker/test.py::test_get_full_sha_from_short",
"cherry_picker/test.py::test_get_author_info_from_short_sha",
"cherry_picker/test.py::test_sorted_branch[input_branches0-sorted_branches0]",
"cherry_picker/test.py::test_sorted_branch[input_branches1-sorted_branches1]",
"cherry_picker/test.py::test_invalid_branches[input_branches0]",
"cherry_picker/test.py::test_invalid_branches[input_branches1]",
"cherry_picker/test.py::test_get_cherry_pick_branch",
"cherry_picker/test.py::test_get_pr_url",
"cherry_picker/test.py::test_username[[email protected]:mock_user/cpython.git]",
"cherry_picker/test.py::test_username[[email protected]:mock_user/cpython]",
"cherry_picker/test.py::test_username[ssh://[email protected]/mock_user/cpython.git]",
"cherry_picker/test.py::test_username[ssh://[email protected]/mock_user/cpython]",
"cherry_picker/test.py::test_username[https://github.com/mock_user/cpython.git]",
"cherry_picker/test.py::test_username[https://github.com/mock_user/cpython]",
"cherry_picker/test.py::test_get_updated_commit_message",
"cherry_picker/test.py::test_get_updated_commit_message_without_links_replacement",
"cherry_picker/test.py::test_is_cpython_repo",
"cherry_picker/test.py::test_is_not_cpython_repo",
"cherry_picker/test.py::test_find_config",
"cherry_picker/test.py::test_find_config_not_found",
"cherry_picker/test.py::test_find_config_not_git",
"cherry_picker/test.py::test_load_full_config",
"cherry_picker/test.py::test_load_config_no_head_sha",
"cherry_picker/test.py::test_normalize_long_commit_message",
"cherry_picker/test.py::test_normalize_short_commit_message",
"cherry_picker/test.py::test_from_git_rev_read_negative[/some/path/without/revision]",
"cherry_picker/test.py::test_from_git_rev_read_negative[HEAD:some/non-existent/path]",
"cherry_picker/test.py::test_from_git_rev_read_uncommitted",
"cherry_picker/test.py::test_from_git_rev_read",
"cherry_picker/test.py::test_states",
"cherry_picker/test.py::test_paused_flow",
"cherry_picker/test.py::test_start_end_states[fetch_upstream-Workflow",
"cherry_picker/test.py::test_start_end_states[checkout_default_branch-Workflow",
"cherry_picker/test.py::test_cherry_pick",
"cherry_picker/test.py::test_cherry_pick_fail",
"cherry_picker/test.py::test_get_state_and_verify_fail",
"cherry_picker/test.py::test_push_to_remote_fail",
"cherry_picker/test.py::test_push_to_remote_interactive",
"cherry_picker/test.py::test_push_to_remote_botflow",
"cherry_picker/test.py::test_backport_no_branch",
"cherry_picker/test.py::test_backport_cherry_pick_fail",
"cherry_picker/test.py::test_backport_cherry_pick_crash_ignored",
"cherry_picker/test.py::test_continue_cherry_pick_invalid_state",
"cherry_picker/test.py::test_continue_cherry_pick_invalid_branch",
"cherry_picker/test.py::test_abort_cherry_pick_invalid_state",
"cherry_picker/test.py::test_abort_cherry_pick_fail"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-05-01 02:53:03+00:00
|
apache-2.0
| 5,113 |
|
python__cherry-picker-35
|
diff --git a/cherry_picker/cherry_picker.py b/cherry_picker/cherry_picker.py
index bb4b848..25da7ad 100755
--- a/cherry_picker/cherry_picker.py
+++ b/cherry_picker/cherry_picker.py
@@ -99,6 +99,7 @@ class CherryPicker:
commit_sha1,
branches,
*,
+ upstream_remote=None,
dry_run=False,
push=True,
prefix_commit=True,
@@ -128,6 +129,7 @@ class CherryPicker:
click.echo("Dry run requested, listing expected command sequence")
self.pr_remote = pr_remote
+ self.upstream_remote = upstream_remote
self.commit_sha1 = commit_sha1
self.branches = branches
self.dry_run = dry_run
@@ -135,6 +137,9 @@ class CherryPicker:
self.auto_pr = auto_pr
self.prefix_commit = prefix_commit
+ # the cached calculated value of self.upstream property
+ self._upstream = None
+
# This is set to the PR number when cherry-picker successfully
# creates a PR through API.
self.pr_number = None
@@ -153,14 +158,33 @@ class CherryPicker:
@property
def upstream(self):
"""Get the remote name to use for upstream branches
- Uses "upstream" if it exists, "origin" otherwise
+
+ Uses the remote passed to `--upstream-remote`.
+ If this flag wasn't passed, it uses "upstream" if it exists or "origin" otherwise.
"""
+ # the cached calculated value of the property
+ if self._upstream is not None:
+ return self._upstream
+
cmd = ["git", "remote", "get-url", "upstream"]
+ if self.upstream_remote is not None:
+ cmd[-1] = self.upstream_remote
+
try:
self.run_cmd(cmd)
except subprocess.CalledProcessError:
- return "origin"
- return "upstream"
+ if self.upstream_remote is not None:
+ raise ValueError(f"There is no remote with name {cmd[-1]!r}.")
+ cmd[-1] = "origin"
+ try:
+ self.run_cmd(cmd)
+ except subprocess.CalledProcessError:
+ raise ValueError(
+ "There are no remotes with name 'upstream' or 'origin'."
+ )
+
+ self._upstream = cmd[-1]
+ return self._upstream
@property
def sorted_branches(self):
@@ -605,6 +629,13 @@ CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
help="git remote to use for PR branches",
default="origin",
)
[email protected](
+ "--upstream-remote",
+ "upstream_remote",
+ metavar="REMOTE",
+ help="git remote to use for upstream branches",
+ default=None,
+)
@click.option(
"--abort",
"abort",
@@ -662,6 +693,7 @@ def cherry_pick_cli(
ctx,
dry_run,
pr_remote,
+ upstream_remote,
abort,
status,
push,
@@ -681,6 +713,7 @@ def cherry_pick_cli(
pr_remote,
commit_sha1,
branches,
+ upstream_remote=upstream_remote,
dry_run=dry_run,
push=push,
auto_pr=auto_pr,
diff --git a/readme.rst b/readme.rst
index 13c5f5c..6028338 100644
--- a/readme.rst
+++ b/readme.rst
@@ -1,6 +1,6 @@
Usage (from a cloned CPython directory) ::
- cherry_picker [--pr-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--status] [--abort/--continue] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
+ cherry_picker [--pr-remote REMOTE] [--upstream-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--status] [--abort/--continue] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
|pyversion status|
|pypi status|
@@ -41,6 +41,8 @@ Requires Python 3.7.
The cherry picking script assumes that if an ``upstream`` remote is defined, then
it should be used as the source of upstream changes and as the base for
cherry-pick branches. Otherwise, ``origin`` is used for that purpose.
+You can override this behavior with the ``--upstream-remote`` option
+(e.g. ``--upstream-remote python`` to use a remote named ``python``).
Verify that an ``upstream`` remote is set to the CPython repository:
@@ -73,7 +75,7 @@ From the cloned CPython directory:
.. code-block:: console
- (venv) $ cherry_picker [--pr-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--abort/--continue] [--status] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
+ (venv) $ cherry_picker [--pr-remote REMOTE] [--upstream-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--abort/--continue] [--status] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
Commit sha1
@@ -94,9 +96,11 @@ Options
::
- --dry-run Dry Run Mode. Prints out the commands, but not executed.
- --pr-remote REMOTE Specify the git remote to push into. Default is 'origin'.
- --status Do `git status` in cpython directory.
+ --dry-run Dry Run Mode. Prints out the commands, but not executed.
+ --pr-remote REMOTE Specify the git remote to push into. Default is 'origin'.
+ --upstream-remote REMOTE Specify the git remote to use for upstream branches.
+ Default is 'upstream' or 'origin' if the former doesn't exist.
+ --status Do `git status` in cpython directory.
Additional options::
@@ -252,6 +256,11 @@ steps it would execute without actually executing any of them. For example:
This will generate pull requests through a remote other than ``origin``
(e.g. ``pr``)
+`--upstream-remote` option
+--------------------------
+
+This will generate branches from a remote other than ``upstream``/``origin``
+(e.g. ``python``)
`--status` option
-----------------
|
python/cherry-picker
|
0ecbf068aeb6ebf42c933f803e55c8b22117c812
|
diff --git a/cherry_picker/test_cherry_picker.py b/cherry_picker/test_cherry_picker.py
index 6f733e3..00caa5c 100644
--- a/cherry_picker/test_cherry_picker.py
+++ b/cherry_picker/test_cherry_picker.py
@@ -57,6 +57,12 @@ def git_init():
return lambda: subprocess.run(git_init_cmd, check=True)
[email protected]
+def git_remote():
+ git_remote_cmd = "git", "remote"
+ return lambda *extra_args: (subprocess.run(git_remote_cmd + extra_args, check=True))
+
+
@pytest.fixture
def git_add():
git_add_cmd = "git", "add"
@@ -238,6 +244,62 @@ def test_get_cherry_pick_branch(os_path_exists, config):
assert cp.get_cherry_pick_branch("3.6") == "backport-22a594a-3.6"
[email protected](
+ "remote_name,upstream_remote",
+ (
+ ("upstream", None),
+ ("upstream", "upstream"),
+ ("origin", None),
+ ("origin", "origin"),
+ ("python", "python"),
+ ),
+)
+def test_upstream_name(remote_name, upstream_remote, config, tmp_git_repo_dir, git_remote):
+ git_remote("add", remote_name, "https://github.com/python/cpython.git")
+ if remote_name != "origin":
+ git_remote("add", "origin", "https://github.com/miss-islington/cpython.git")
+
+ branches = ["3.6"]
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cp = CherryPicker(
+ "origin",
+ "22a594a0047d7706537ff2ac676cdc0f1dcb329c",
+ branches,
+ config=config,
+ upstream_remote=upstream_remote,
+ )
+ assert cp.upstream == remote_name
+
+
[email protected](
+ "remote_to_add,remote_name,upstream_remote",
+ (
+ (None, "upstream", None),
+ ("origin", "upstream", "upstream"),
+ (None, "origin", None),
+ ("upstream", "origin", "origin"),
+ ("origin", "python", "python"),
+ (None, "python", None),
+ ),
+)
+def test_error_on_missing_remote(remote_to_add, remote_name, upstream_remote, config, tmp_git_repo_dir, git_remote):
+ git_remote("add", "some-remote-name", "https://github.com/python/cpython.git")
+ if remote_to_add is not None:
+ git_remote("add", remote_to_add, "https://github.com/miss-islington/cpython.git")
+
+ branches = ["3.6"]
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cp = CherryPicker(
+ "origin",
+ "22a594a0047d7706537ff2ac676cdc0f1dcb329c",
+ branches,
+ config=config,
+ upstream_remote=upstream_remote,
+ )
+ with pytest.raises(ValueError):
+ cp.upstream
+
+
def test_get_pr_url(config):
branches = ["3.6"]
|
cherry_picker hardcodes the name of the python/cpython.git repo
`cherry_picker` needs an option to specify the `git remote` name for the CPython repo.
Currently it is hardcoded to "upstream" or "origin", and can't be used if a meaningful name like "python" is used
E.g.
```
~/repos/cpython$ git remote -v
python [email protected]:python/cpython.git (fetch)
python [email protected]:python/cpython.git (push)
mine [email protected]:markshannon/cpython.git (fetch)
mine [email protected]:markshannon/cpython.git (push)
```
|
0.0
|
0ecbf068aeb6ebf42c933f803e55c8b22117c812
|
[
"cherry_picker/test_cherry_picker.py::test_upstream_name[upstream-None]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[upstream-upstream]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[origin-None]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[origin-origin]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[python-python]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-upstream-None]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[origin-upstream-upstream]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-origin-None]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[upstream-origin-origin]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[origin-python-python]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-python-None]"
] |
[
"cherry_picker/test_cherry_picker.py::test_get_base_branch",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_which_has_dashes",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[backport-22a594a]",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[prefix-22a594a-2.7]",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[backport-22a594a-base]",
"cherry_picker/test_cherry_picker.py::test_get_current_branch",
"cherry_picker/test_cherry_picker.py::test_get_full_sha_from_short",
"cherry_picker/test_cherry_picker.py::test_get_author_info_from_short_sha",
"cherry_picker/test_cherry_picker.py::test_sorted_branch[input_branches0-sorted_branches0]",
"cherry_picker/test_cherry_picker.py::test_sorted_branch[input_branches1-sorted_branches1]",
"cherry_picker/test_cherry_picker.py::test_invalid_branches[input_branches0]",
"cherry_picker/test_cherry_picker.py::test_invalid_branches[input_branches1]",
"cherry_picker/test_cherry_picker.py::test_get_cherry_pick_branch",
"cherry_picker/test_cherry_picker.py::test_get_pr_url",
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message_without_links_replacement",
"cherry_picker/test_cherry_picker.py::test_is_cpython_repo",
"cherry_picker/test_cherry_picker.py::test_is_not_cpython_repo",
"cherry_picker/test_cherry_picker.py::test_find_config",
"cherry_picker/test_cherry_picker.py::test_find_config_not_found",
"cherry_picker/test_cherry_picker.py::test_find_config_not_git",
"cherry_picker/test_cherry_picker.py::test_load_full_config",
"cherry_picker/test_cherry_picker.py::test_load_partial_config",
"cherry_picker/test_cherry_picker.py::test_load_config_no_head_sha",
"cherry_picker/test_cherry_picker.py::test_normalize_long_commit_message",
"cherry_picker/test_cherry_picker.py::test_normalize_short_commit_message",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_negative[/some/path/without/revision]",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_negative[HEAD:some/non-existent/path]",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_uncommitted",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read",
"cherry_picker/test_cherry_picker.py::test_states",
"cherry_picker/test_cherry_picker.py::test_paused_flow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[fetch_upstream-Workflow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[checkout_default_branch-Workflow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[checkout_previous_branch-Workflow",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_checkout_previous_branch",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_fail",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_checkout_fail",
"cherry_picker/test_cherry_picker.py::test_cherry_pick",
"cherry_picker/test_cherry_picker.py::test_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_get_state_and_verify_fail",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_fail",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_interactive",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_botflow",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_no_auto_pr",
"cherry_picker/test_cherry_picker.py::test_backport_no_branch",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_crash_ignored",
"cherry_picker/test_cherry_picker.py::test_backport_success",
"cherry_picker/test_cherry_picker.py::test_backport_pause_and_continue",
"cherry_picker/test_cherry_picker.py::test_continue_cherry_pick_invalid_state",
"cherry_picker/test_cherry_picker.py::test_continue_cherry_pick_invalid_branch",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_invalid_state",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_success",
"cherry_picker/test_cherry_picker.py::test_cli_invoked"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-07 01:00:47+00:00
|
apache-2.0
| 5,114 |
|
python__cherry-picker-36
|
diff --git a/cherry_picker/cherry_picker.py b/cherry_picker/cherry_picker.py
index 48baef5..5c6effc 100755
--- a/cherry_picker/cherry_picker.py
+++ b/cherry_picker/cherry_picker.py
@@ -98,6 +98,7 @@ class CherryPicker:
prefix_commit=True,
config=DEFAULT_CONFIG,
chosen_config_path=None,
+ auto_pr=True,
):
self.chosen_config_path = chosen_config_path
@@ -125,6 +126,7 @@ class CherryPicker:
self.branches = branches
self.dry_run = dry_run
self.push = push
+ self.auto_pr = auto_pr
self.prefix_commit = prefix_commit
def set_paused_state(self):
@@ -297,6 +299,8 @@ Co-authored-by: {get_author_info_from_short_sha(self.commit_sha1)}"""
click.echo(cpe.output)
set_state(WORKFLOW_STATES.PUSHING_TO_REMOTE_FAILED)
else:
+ if not self.auto_pr:
+ return
gh_auth = os.getenv("GH_AUTH")
if gh_auth:
set_state(WORKFLOW_STATES.PR_CREATING)
@@ -526,7 +530,7 @@ To abort the cherry-pick and cleanup:
"Valid states are: "
f'{", ".join(s.name for s in self.ALLOWED_STATES)}. '
"If this looks suspicious, raise an issue at "
- "https://github.com/python/core-workflow/issues/new.\n"
+ "https://github.com/python/cherry-picker/issues/new.\n"
"As the last resort you can reset the runtime state "
"stored in Git config using the following command: "
"`git config --local --remove-section cherry-picker`"
@@ -577,6 +581,17 @@ CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
default=True,
help="Changes won't be pushed to remote",
)
[email protected](
+ "--auto-pr/--no-auto-pr",
+ "auto_pr",
+ is_flag=True,
+ default=True,
+ help=(
+ "If auto PR is enabled, cherry-picker will automatically open a PR"
+ " through API if GH_AUTH env var is set, or automatically open the PR"
+ " creation page in the web browser otherwise."
+ ),
+)
@click.option(
"--config-path",
"config_path",
@@ -592,7 +607,7 @@ CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@click.argument("branches", nargs=-1)
@click.pass_context
def cherry_pick_cli(
- ctx, dry_run, pr_remote, abort, status, push, config_path, commit_sha1, branches
+ ctx, dry_run, pr_remote, abort, status, push, auto_pr, config_path, commit_sha1, branches
):
"""cherry-pick COMMIT_SHA1 into target BRANCHES."""
@@ -607,6 +622,7 @@ def cherry_pick_cli(
branches,
dry_run=dry_run,
push=push,
+ auto_pr=auto_pr,
config=config,
chosen_config_path=chosen_config_path,
)
diff --git a/readme.rst b/readme.rst
index 9270c1f..2aa63e1 100644
--- a/readme.rst
+++ b/readme.rst
@@ -301,7 +301,7 @@ Install pytest: ``pip install -U pytest``
::
- $ pytest test.py
+ $ pytest
Publishing to PyPI
|
python/cherry-picker
|
7122a15bec80326f3fbfa44a2dafa059749c9963
|
diff --git a/cherry_picker/test.py b/cherry_picker/test.py
index 5eb271f..c01ba26 100644
--- a/cherry_picker/test.py
+++ b/cherry_picker/test.py
@@ -636,7 +636,7 @@ def test_get_state_and_verify_fail(
r"Valid states are: "
r"[\w_\s]+(, [\w_\s]+)*\. "
r"If this looks suspicious, raise an issue at "
- r"https://github.com/python/core-workflow/issues/new\."
+ r"https://github.com/python/cherry-picker/issues/new\."
"\n"
r"As the last resort you can reset the runtime state "
r"stored in Git config using the following command: "
@@ -679,6 +679,18 @@ def test_push_to_remote_botflow(tmp_git_repo_dir, monkeypatch):
assert get_state() == WORKFLOW_STATES.PR_CREATING
+def test_push_to_remote_no_auto_pr(tmp_git_repo_dir, monkeypatch):
+ monkeypatch.setenv("GH_AUTH", "True")
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cherry_picker = CherryPicker("origin", "xxx", [], auto_pr=False)
+
+ with mock.patch.object(cherry_picker, "run_cmd"), mock.patch.object(
+ cherry_picker, "create_gh_pr"
+ ):
+ cherry_picker.push_to_remote("main", "backport-branch-test")
+ assert get_state() == WORKFLOW_STATES.PUSHED_TO_REMOTE
+
+
def test_backport_no_branch(tmp_git_repo_dir, monkeypatch):
with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
cherry_picker = CherryPicker("origin", "xxx", [])
|
A way to force cherry_picker to never open a web browser
Cherry picker calls the webbrowser module from open_pr to open a web browser. I never want this. My terminal windows are most often not capable of opening a useful web browser and as such may resort to opening dumb terminal browsers like links or lynx that I refuse to tough github with. Just print the URL (as it already does) and leave it at that.
Some people may want a web browser. making it an option (I don't care what the default is) is fine by me.
|
0.0
|
7122a15bec80326f3fbfa44a2dafa059749c9963
|
[
"cherry_picker/test.py::test_get_state_and_verify_fail",
"cherry_picker/test.py::test_push_to_remote_no_auto_pr"
] |
[
"cherry_picker/test.py::test_get_base_branch",
"cherry_picker/test.py::test_get_base_branch_which_has_dashes",
"cherry_picker/test.py::test_get_base_branch_invalid[backport-22a594a]",
"cherry_picker/test.py::test_get_base_branch_invalid[prefix-22a594a-2.7]",
"cherry_picker/test.py::test_get_base_branch_invalid[backport-22a594a-base]",
"cherry_picker/test.py::test_get_current_branch",
"cherry_picker/test.py::test_get_full_sha_from_short",
"cherry_picker/test.py::test_get_author_info_from_short_sha",
"cherry_picker/test.py::test_sorted_branch[input_branches0-sorted_branches0]",
"cherry_picker/test.py::test_sorted_branch[input_branches1-sorted_branches1]",
"cherry_picker/test.py::test_invalid_branches[input_branches0]",
"cherry_picker/test.py::test_invalid_branches[input_branches1]",
"cherry_picker/test.py::test_get_cherry_pick_branch",
"cherry_picker/test.py::test_get_pr_url",
"cherry_picker/test.py::test_username[[email protected]:mock_user/cpython.git]",
"cherry_picker/test.py::test_username[[email protected]:mock_user/cpython]",
"cherry_picker/test.py::test_username[ssh://[email protected]/mock_user/cpython.git]",
"cherry_picker/test.py::test_username[ssh://[email protected]/mock_user/cpython]",
"cherry_picker/test.py::test_username[https://github.com/mock_user/cpython.git]",
"cherry_picker/test.py::test_username[https://github.com/mock_user/cpython]",
"cherry_picker/test.py::test_get_updated_commit_message",
"cherry_picker/test.py::test_get_updated_commit_message_without_links_replacement",
"cherry_picker/test.py::test_is_cpython_repo",
"cherry_picker/test.py::test_is_not_cpython_repo",
"cherry_picker/test.py::test_find_config",
"cherry_picker/test.py::test_find_config_not_found",
"cherry_picker/test.py::test_find_config_not_git",
"cherry_picker/test.py::test_load_full_config",
"cherry_picker/test.py::test_load_partial_config",
"cherry_picker/test.py::test_load_config_no_head_sha",
"cherry_picker/test.py::test_normalize_long_commit_message",
"cherry_picker/test.py::test_normalize_short_commit_message",
"cherry_picker/test.py::test_from_git_rev_read_negative[/some/path/without/revision]",
"cherry_picker/test.py::test_from_git_rev_read_negative[HEAD:some/non-existent/path]",
"cherry_picker/test.py::test_from_git_rev_read_uncommitted",
"cherry_picker/test.py::test_from_git_rev_read",
"cherry_picker/test.py::test_states",
"cherry_picker/test.py::test_paused_flow",
"cherry_picker/test.py::test_start_end_states[fetch_upstream-Workflow",
"cherry_picker/test.py::test_start_end_states[checkout_default_branch-Workflow",
"cherry_picker/test.py::test_cleanup_branch",
"cherry_picker/test.py::test_cleanup_branch_fail",
"cherry_picker/test.py::test_cherry_pick",
"cherry_picker/test.py::test_cherry_pick_fail",
"cherry_picker/test.py::test_push_to_remote_fail",
"cherry_picker/test.py::test_push_to_remote_interactive",
"cherry_picker/test.py::test_push_to_remote_botflow",
"cherry_picker/test.py::test_backport_no_branch",
"cherry_picker/test.py::test_backport_cherry_pick_fail",
"cherry_picker/test.py::test_backport_cherry_pick_crash_ignored",
"cherry_picker/test.py::test_backport_success",
"cherry_picker/test.py::test_backport_pause_and_continue",
"cherry_picker/test.py::test_continue_cherry_pick_invalid_state",
"cherry_picker/test.py::test_continue_cherry_pick_invalid_branch",
"cherry_picker/test.py::test_abort_cherry_pick_invalid_state",
"cherry_picker/test.py::test_abort_cherry_pick_fail",
"cherry_picker/test.py::test_abort_cherry_pick_success",
"cherry_picker/test.py::test_cli_invoked"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-07 01:20:39+00:00
|
apache-2.0
| 5,115 |
|
python__cherry-picker-39
|
diff --git a/cherry_picker/cherry_picker.py b/cherry_picker/cherry_picker.py
index bb4b848..4c050d6 100755
--- a/cherry_picker/cherry_picker.py
+++ b/cherry_picker/cherry_picker.py
@@ -77,7 +77,9 @@ WORKFLOW_STATES = enum.Enum(
class BranchCheckoutException(Exception):
- pass
+ def __init__(self, branch_name):
+ self.branch_name = branch_name
+ super().__init__(f"Error checking out the branch {branch_name!r}.")
class CherryPickException(Exception):
@@ -99,6 +101,7 @@ class CherryPicker:
commit_sha1,
branches,
*,
+ upstream_remote=None,
dry_run=False,
push=True,
prefix_commit=True,
@@ -128,6 +131,7 @@ class CherryPicker:
click.echo("Dry run requested, listing expected command sequence")
self.pr_remote = pr_remote
+ self.upstream_remote = upstream_remote
self.commit_sha1 = commit_sha1
self.branches = branches
self.dry_run = dry_run
@@ -135,6 +139,9 @@ class CherryPicker:
self.auto_pr = auto_pr
self.prefix_commit = prefix_commit
+ # the cached calculated value of self.upstream property
+ self._upstream = None
+
# This is set to the PR number when cherry-picker successfully
# creates a PR through API.
self.pr_number = None
@@ -153,14 +160,33 @@ class CherryPicker:
@property
def upstream(self):
"""Get the remote name to use for upstream branches
- Uses "upstream" if it exists, "origin" otherwise
+
+ Uses the remote passed to `--upstream-remote`.
+ If this flag wasn't passed, it uses "upstream" if it exists or "origin" otherwise.
"""
+ # the cached calculated value of the property
+ if self._upstream is not None:
+ return self._upstream
+
cmd = ["git", "remote", "get-url", "upstream"]
+ if self.upstream_remote is not None:
+ cmd[-1] = self.upstream_remote
+
try:
self.run_cmd(cmd)
except subprocess.CalledProcessError:
- return "origin"
- return "upstream"
+ if self.upstream_remote is not None:
+ raise ValueError(f"There is no remote with name {cmd[-1]!r}.")
+ cmd[-1] = "origin"
+ try:
+ self.run_cmd(cmd)
+ except subprocess.CalledProcessError:
+ raise ValueError(
+ "There are no remotes with name 'upstream' or 'origin'."
+ )
+
+ self._upstream = cmd[-1]
+ return self._upstream
@property
def sorted_branches(self):
@@ -214,12 +240,10 @@ class CherryPicker:
self.run_cmd(cmd)
except subprocess.CalledProcessError as err:
click.echo(
- f"Error checking out the branch {branch_name}."
+ f"Error checking out the branch {checked_out_branch!r}."
)
click.echo(err.output)
- raise BranchCheckoutException(
- f"Error checking out the branch {branch_name}."
- )
+ raise BranchCheckoutException(checked_out_branch)
def get_commit_message(self, commit_sha):
"""
@@ -425,7 +449,13 @@ Co-authored-by: {get_author_info_from_short_sha(self.commit_sha1)}"""
click.echo(f"Now backporting '{self.commit_sha1}' into '{maint_branch}'")
cherry_pick_branch = self.get_cherry_pick_branch(maint_branch)
- self.checkout_branch(maint_branch, create_branch=True)
+ try:
+ self.checkout_branch(maint_branch, create_branch=True)
+ except BranchCheckoutException:
+ self.checkout_default_branch()
+ reset_stored_config_ref()
+ reset_state()
+ raise
commit_message = ""
try:
self.cherry_pick()
@@ -605,6 +635,13 @@ CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
help="git remote to use for PR branches",
default="origin",
)
[email protected](
+ "--upstream-remote",
+ "upstream_remote",
+ metavar="REMOTE",
+ help="git remote to use for upstream branches",
+ default=None,
+)
@click.option(
"--abort",
"abort",
@@ -662,6 +699,7 @@ def cherry_pick_cli(
ctx,
dry_run,
pr_remote,
+ upstream_remote,
abort,
status,
push,
@@ -681,6 +719,7 @@ def cherry_pick_cli(
pr_remote,
commit_sha1,
branches,
+ upstream_remote=upstream_remote,
dry_run=dry_run,
push=push,
auto_pr=auto_pr,
diff --git a/readme.rst b/readme.rst
index 13c5f5c..6028338 100644
--- a/readme.rst
+++ b/readme.rst
@@ -1,6 +1,6 @@
Usage (from a cloned CPython directory) ::
- cherry_picker [--pr-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--status] [--abort/--continue] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
+ cherry_picker [--pr-remote REMOTE] [--upstream-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--status] [--abort/--continue] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
|pyversion status|
|pypi status|
@@ -41,6 +41,8 @@ Requires Python 3.7.
The cherry picking script assumes that if an ``upstream`` remote is defined, then
it should be used as the source of upstream changes and as the base for
cherry-pick branches. Otherwise, ``origin`` is used for that purpose.
+You can override this behavior with the ``--upstream-remote`` option
+(e.g. ``--upstream-remote python`` to use a remote named ``python``).
Verify that an ``upstream`` remote is set to the CPython repository:
@@ -73,7 +75,7 @@ From the cloned CPython directory:
.. code-block:: console
- (venv) $ cherry_picker [--pr-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--abort/--continue] [--status] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
+ (venv) $ cherry_picker [--pr-remote REMOTE] [--upstream-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--abort/--continue] [--status] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
Commit sha1
@@ -94,9 +96,11 @@ Options
::
- --dry-run Dry Run Mode. Prints out the commands, but not executed.
- --pr-remote REMOTE Specify the git remote to push into. Default is 'origin'.
- --status Do `git status` in cpython directory.
+ --dry-run Dry Run Mode. Prints out the commands, but not executed.
+ --pr-remote REMOTE Specify the git remote to push into. Default is 'origin'.
+ --upstream-remote REMOTE Specify the git remote to use for upstream branches.
+ Default is 'upstream' or 'origin' if the former doesn't exist.
+ --status Do `git status` in cpython directory.
Additional options::
@@ -252,6 +256,11 @@ steps it would execute without actually executing any of them. For example:
This will generate pull requests through a remote other than ``origin``
(e.g. ``pr``)
+`--upstream-remote` option
+--------------------------
+
+This will generate branches from a remote other than ``upstream``/``origin``
+(e.g. ``python``)
`--status` option
-----------------
|
python/cherry-picker
|
0ecbf068aeb6ebf42c933f803e55c8b22117c812
|
diff --git a/cherry_picker/test_cherry_picker.py b/cherry_picker/test_cherry_picker.py
index 6f733e3..1b6d7b0 100644
--- a/cherry_picker/test_cherry_picker.py
+++ b/cherry_picker/test_cherry_picker.py
@@ -11,6 +11,7 @@ import pytest
from .cherry_picker import (
DEFAULT_CONFIG,
WORKFLOW_STATES,
+ BranchCheckoutException,
CherryPicker,
CherryPickException,
InvalidRepoException,
@@ -57,6 +58,12 @@ def git_init():
return lambda: subprocess.run(git_init_cmd, check=True)
[email protected]
+def git_remote():
+ git_remote_cmd = "git", "remote"
+ return lambda *extra_args: (subprocess.run(git_remote_cmd + extra_args, check=True))
+
+
@pytest.fixture
def git_add():
git_add_cmd = "git", "add"
@@ -238,6 +245,62 @@ def test_get_cherry_pick_branch(os_path_exists, config):
assert cp.get_cherry_pick_branch("3.6") == "backport-22a594a-3.6"
[email protected](
+ "remote_name,upstream_remote",
+ (
+ ("upstream", None),
+ ("upstream", "upstream"),
+ ("origin", None),
+ ("origin", "origin"),
+ ("python", "python"),
+ ),
+)
+def test_upstream_name(remote_name, upstream_remote, config, tmp_git_repo_dir, git_remote):
+ git_remote("add", remote_name, "https://github.com/python/cpython.git")
+ if remote_name != "origin":
+ git_remote("add", "origin", "https://github.com/miss-islington/cpython.git")
+
+ branches = ["3.6"]
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cp = CherryPicker(
+ "origin",
+ "22a594a0047d7706537ff2ac676cdc0f1dcb329c",
+ branches,
+ config=config,
+ upstream_remote=upstream_remote,
+ )
+ assert cp.upstream == remote_name
+
+
[email protected](
+ "remote_to_add,remote_name,upstream_remote",
+ (
+ (None, "upstream", None),
+ ("origin", "upstream", "upstream"),
+ (None, "origin", None),
+ ("upstream", "origin", "origin"),
+ ("origin", "python", "python"),
+ (None, "python", None),
+ ),
+)
+def test_error_on_missing_remote(remote_to_add, remote_name, upstream_remote, config, tmp_git_repo_dir, git_remote):
+ git_remote("add", "some-remote-name", "https://github.com/python/cpython.git")
+ if remote_to_add is not None:
+ git_remote("add", remote_to_add, "https://github.com/miss-islington/cpython.git")
+
+ branches = ["3.6"]
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cp = CherryPicker(
+ "origin",
+ "22a594a0047d7706537ff2ac676cdc0f1dcb329c",
+ branches,
+ config=config,
+ upstream_remote=upstream_remote,
+ )
+ with pytest.raises(ValueError):
+ cp.upstream
+
+
def test_get_pr_url(config):
branches = ["3.6"]
@@ -825,6 +888,38 @@ def test_backport_cherry_pick_crash_ignored(
assert get_state() == WORKFLOW_STATES.UNSET
+def test_backport_cherry_pick_branch_already_exists(
+ tmp_git_repo_dir, git_branch, git_add, git_commit, git_checkout
+):
+ cherry_pick_target_branches = ("3.8",)
+ pr_remote = "origin"
+ test_file = "some.file"
+ tmp_git_repo_dir.join(test_file).write("some contents")
+ git_branch(cherry_pick_target_branches[0])
+ git_branch(
+ f"{pr_remote}/{cherry_pick_target_branches[0]}", cherry_pick_target_branches[0]
+ )
+ git_add(test_file)
+ git_commit("Add a test file")
+ scm_revision = get_sha1_from("HEAD")
+
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cherry_picker = CherryPicker(
+ pr_remote, scm_revision, cherry_pick_target_branches
+ )
+
+ backport_branch_name = cherry_picker.get_cherry_pick_branch(cherry_pick_target_branches[0])
+ git_branch(backport_branch_name)
+
+ with mock.patch.object(cherry_picker, "fetch_upstream"), pytest.raises(
+ BranchCheckoutException
+ ) as exc_info:
+ cherry_picker.backport()
+
+ assert exc_info.value.branch_name == backport_branch_name
+ assert get_state() == WORKFLOW_STATES.UNSET
+
+
def test_backport_success(
tmp_git_repo_dir, git_branch, git_add, git_commit, git_checkout
):
|
cherry-picker ends up in bad state if a `backport-...` branch already exists
If, for whatever reason, the `backport-...` branch already exists, cherry-picker ends up in a bad state:
```
λ python -m cherry_picker e5ee6a87a3b6fbf1a7e3856248885811f04d1f89 3.4
🐍 🍒 ⛏
Now backporting 'e5ee6a87a3b6fbf1a7e3856248885811f04d1f89' into '3.4'
Error checking out the branch backport-e5ee6a8-3.4.
fatal: A branch named 'backport-e5ee6a8-3.4' already exists.
λ python -m cherry_picker e5ee6a87a3b6fbf1a7e3856248885811f04d1f89 3.4
🐍 🍒 ⛏
Usage: __main__.py [OPTIONS] [COMMIT_SHA1] [BRANCHES]...
Try '__main__.py -h' for help.
Error: Run state cherry-picker.state=BACKPORT_LOOP_START in Git config is not known.
Perhaps it has been set by a newer version of cherry-picker. Try upgrading.
Valid states are: BACKPORT_PAUSED, UNSET. If this looks suspicious, raise an issue at https://github.com/python/core-workflow/issues/new.
As the last resort you can reset the runtime state stored in Git config using the following command: `git config --local --remove-section cherry-picker`
```
|
0.0
|
0ecbf068aeb6ebf42c933f803e55c8b22117c812
|
[
"cherry_picker/test_cherry_picker.py::test_upstream_name[upstream-None]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[upstream-upstream]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[origin-None]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[origin-origin]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[python-python]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-upstream-None]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[origin-upstream-upstream]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-origin-None]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[upstream-origin-origin]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[origin-python-python]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-python-None]"
] |
[
"cherry_picker/test_cherry_picker.py::test_get_base_branch",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_which_has_dashes",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[backport-22a594a]",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[prefix-22a594a-2.7]",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[backport-22a594a-base]",
"cherry_picker/test_cherry_picker.py::test_get_current_branch",
"cherry_picker/test_cherry_picker.py::test_get_full_sha_from_short",
"cherry_picker/test_cherry_picker.py::test_get_author_info_from_short_sha",
"cherry_picker/test_cherry_picker.py::test_sorted_branch[input_branches0-sorted_branches0]",
"cherry_picker/test_cherry_picker.py::test_sorted_branch[input_branches1-sorted_branches1]",
"cherry_picker/test_cherry_picker.py::test_invalid_branches[input_branches0]",
"cherry_picker/test_cherry_picker.py::test_invalid_branches[input_branches1]",
"cherry_picker/test_cherry_picker.py::test_get_cherry_pick_branch",
"cherry_picker/test_cherry_picker.py::test_get_pr_url",
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message_without_links_replacement",
"cherry_picker/test_cherry_picker.py::test_is_cpython_repo",
"cherry_picker/test_cherry_picker.py::test_is_not_cpython_repo",
"cherry_picker/test_cherry_picker.py::test_find_config",
"cherry_picker/test_cherry_picker.py::test_find_config_not_found",
"cherry_picker/test_cherry_picker.py::test_find_config_not_git",
"cherry_picker/test_cherry_picker.py::test_load_full_config",
"cherry_picker/test_cherry_picker.py::test_load_partial_config",
"cherry_picker/test_cherry_picker.py::test_load_config_no_head_sha",
"cherry_picker/test_cherry_picker.py::test_normalize_long_commit_message",
"cherry_picker/test_cherry_picker.py::test_normalize_short_commit_message",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_negative[/some/path/without/revision]",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_negative[HEAD:some/non-existent/path]",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_uncommitted",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read",
"cherry_picker/test_cherry_picker.py::test_states",
"cherry_picker/test_cherry_picker.py::test_paused_flow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[fetch_upstream-Workflow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[checkout_default_branch-Workflow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[checkout_previous_branch-Workflow",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_checkout_previous_branch",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_fail",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_checkout_fail",
"cherry_picker/test_cherry_picker.py::test_cherry_pick",
"cherry_picker/test_cherry_picker.py::test_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_get_state_and_verify_fail",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_fail",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_interactive",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_botflow",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_no_auto_pr",
"cherry_picker/test_cherry_picker.py::test_backport_no_branch",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_crash_ignored",
"cherry_picker/test_cherry_picker.py::test_backport_success",
"cherry_picker/test_cherry_picker.py::test_backport_pause_and_continue",
"cherry_picker/test_cherry_picker.py::test_continue_cherry_pick_invalid_state",
"cherry_picker/test_cherry_picker.py::test_continue_cherry_pick_invalid_branch",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_invalid_state",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_success",
"cherry_picker/test_cherry_picker.py::test_cli_invoked"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_git_commit_hash",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-07 02:48:27+00:00
|
apache-2.0
| 5,116 |
|
python__cherry-picker-43
|
diff --git a/cherry_picker/cherry_picker.py b/cherry_picker/cherry_picker.py
index bb4b848..73f2794 100755
--- a/cherry_picker/cherry_picker.py
+++ b/cherry_picker/cherry_picker.py
@@ -77,7 +77,9 @@ WORKFLOW_STATES = enum.Enum(
class BranchCheckoutException(Exception):
- pass
+ def __init__(self, branch_name):
+ self.branch_name = branch_name
+ super().__init__(f"Error checking out the branch {branch_name!r}.")
class CherryPickException(Exception):
@@ -99,6 +101,7 @@ class CherryPicker:
commit_sha1,
branches,
*,
+ upstream_remote=None,
dry_run=False,
push=True,
prefix_commit=True,
@@ -128,6 +131,7 @@ class CherryPicker:
click.echo("Dry run requested, listing expected command sequence")
self.pr_remote = pr_remote
+ self.upstream_remote = upstream_remote
self.commit_sha1 = commit_sha1
self.branches = branches
self.dry_run = dry_run
@@ -135,6 +139,9 @@ class CherryPicker:
self.auto_pr = auto_pr
self.prefix_commit = prefix_commit
+ # the cached calculated value of self.upstream property
+ self._upstream = None
+
# This is set to the PR number when cherry-picker successfully
# creates a PR through API.
self.pr_number = None
@@ -153,14 +160,33 @@ class CherryPicker:
@property
def upstream(self):
"""Get the remote name to use for upstream branches
- Uses "upstream" if it exists, "origin" otherwise
+
+ Uses the remote passed to `--upstream-remote`.
+ If this flag wasn't passed, it uses "upstream" if it exists or "origin" otherwise.
"""
+ # the cached calculated value of the property
+ if self._upstream is not None:
+ return self._upstream
+
cmd = ["git", "remote", "get-url", "upstream"]
+ if self.upstream_remote is not None:
+ cmd[-1] = self.upstream_remote
+
try:
self.run_cmd(cmd)
except subprocess.CalledProcessError:
- return "origin"
- return "upstream"
+ if self.upstream_remote is not None:
+ raise ValueError(f"There is no remote with name {cmd[-1]!r}.")
+ cmd[-1] = "origin"
+ try:
+ self.run_cmd(cmd)
+ except subprocess.CalledProcessError:
+ raise ValueError(
+ "There are no remotes with name 'upstream' or 'origin'."
+ )
+
+ self._upstream = cmd[-1]
+ return self._upstream
@property
def sorted_branches(self):
@@ -214,12 +240,10 @@ class CherryPicker:
self.run_cmd(cmd)
except subprocess.CalledProcessError as err:
click.echo(
- f"Error checking out the branch {branch_name}."
+ f"Error checking out the branch {checked_out_branch!r}."
)
click.echo(err.output)
- raise BranchCheckoutException(
- f"Error checking out the branch {branch_name}."
- )
+ raise BranchCheckoutException(checked_out_branch)
def get_commit_message(self, commit_sha):
"""
@@ -317,6 +341,21 @@ Co-authored-by: {get_author_info_from_short_sha(self.commit_sha1)}"""
click.echo(cpe.output)
return updated_commit_message
+ def pause_after_committing(self, cherry_pick_branch):
+ click.echo(
+ f"""
+Finished cherry-pick {self.commit_sha1} into {cherry_pick_branch} \U0001F600
+--no-push option used.
+... Stopping here.
+To continue and push the changes:
+$ cherry_picker --continue
+
+To abort the cherry-pick and cleanup:
+$ cherry_picker --abort
+"""
+ )
+ self.set_paused_state()
+
def push_to_remote(self, base_branch, head_branch, commit_message=""):
"""git push <origin> <branchname>"""
set_state(WORKFLOW_STATES.PUSHING_TO_REMOTE)
@@ -425,7 +464,13 @@ Co-authored-by: {get_author_info_from_short_sha(self.commit_sha1)}"""
click.echo(f"Now backporting '{self.commit_sha1}' into '{maint_branch}'")
cherry_pick_branch = self.get_cherry_pick_branch(maint_branch)
- self.checkout_branch(maint_branch, create_branch=True)
+ try:
+ self.checkout_branch(maint_branch, create_branch=True)
+ except BranchCheckoutException:
+ self.checkout_default_branch()
+ reset_stored_config_ref()
+ reset_state()
+ raise
commit_message = ""
try:
self.cherry_pick()
@@ -445,19 +490,7 @@ Co-authored-by: {get_author_info_from_short_sha(self.commit_sha1)}"""
if not self.is_mirror():
self.cleanup_branch(cherry_pick_branch)
else:
- click.echo(
- f"""
-Finished cherry-pick {self.commit_sha1} into {cherry_pick_branch} \U0001F600
---no-push option used.
-... Stopping here.
-To continue and push the changes:
- $ cherry_picker --continue
-
-To abort the cherry-pick and cleanup:
- $ cherry_picker --abort
-"""
- )
- self.set_paused_state()
+ self.pause_after_committing(cherry_pick_branch)
return # to preserve the correct state
set_state(WORKFLOW_STATES.BACKPORT_LOOP_END)
reset_stored_previous_branch()
@@ -470,14 +503,19 @@ To abort the cherry-pick and cleanup:
if self.initial_state != WORKFLOW_STATES.BACKPORT_PAUSED:
raise ValueError("One can only abort a paused process.")
- cmd = ["git", "cherry-pick", "--abort"]
try:
- set_state(WORKFLOW_STATES.ABORTING)
- click.echo(self.run_cmd(cmd))
- set_state(WORKFLOW_STATES.ABORTED)
- except subprocess.CalledProcessError as cpe:
- click.echo(cpe.output)
- set_state(WORKFLOW_STATES.ABORTING_FAILED)
+ validate_sha("CHERRY_PICK_HEAD")
+ except ValueError:
+ pass
+ else:
+ cmd = ["git", "cherry-pick", "--abort"]
+ try:
+ set_state(WORKFLOW_STATES.ABORTING)
+ click.echo(self.run_cmd(cmd))
+ set_state(WORKFLOW_STATES.ABORTED)
+ except subprocess.CalledProcessError as cpe:
+ click.echo(cpe.output)
+ set_state(WORKFLOW_STATES.ABORTING_FAILED)
# only delete backport branch created by cherry_picker.py
if get_current_branch().startswith("backport-"):
self.cleanup_branch(get_current_branch())
@@ -504,30 +542,39 @@ To abort the cherry-pick and cleanup:
cherry_pick_branch.index("-") + 1 : cherry_pick_branch.index(base) - 1
]
self.commit_sha1 = get_full_sha_from_short(short_sha)
- updated_commit_message = self.get_updated_commit_message(cherry_pick_branch)
- if self.dry_run:
- click.echo(
- f" dry-run: git commit -a -m '{updated_commit_message}' --allow-empty"
- )
- else:
- cmd = [
- "git",
- "commit",
- "-a",
- "-m",
- updated_commit_message,
- "--allow-empty",
- ]
- self.run_cmd(cmd)
-
- self.push_to_remote(base, cherry_pick_branch)
- if not self.is_mirror():
- self.cleanup_branch(cherry_pick_branch)
-
- click.echo("\nBackport PR:\n")
- click.echo(updated_commit_message)
- set_state(WORKFLOW_STATES.BACKPORTING_CONTINUATION_SUCCEED)
+ commits = get_commits_from_backport_branch(base)
+ if len(commits) == 1:
+ commit_message = self.amend_commit_message(cherry_pick_branch)
+ else:
+ commit_message = self.get_updated_commit_message(cherry_pick_branch)
+ if self.dry_run:
+ click.echo(
+ f" dry-run: git commit -a -m '{commit_message}' --allow-empty"
+ )
+ else:
+ cmd = [
+ "git",
+ "commit",
+ "-a",
+ "-m",
+ commit_message,
+ "--allow-empty",
+ ]
+ self.run_cmd(cmd)
+
+ if self.push:
+ self.push_to_remote(base, cherry_pick_branch)
+
+ if not self.is_mirror():
+ self.cleanup_branch(cherry_pick_branch)
+
+ click.echo("\nBackport PR:\n")
+ click.echo(commit_message)
+ set_state(WORKFLOW_STATES.BACKPORTING_CONTINUATION_SUCCEED)
+ else:
+ self.pause_after_committing(cherry_pick_branch)
+ return # to preserve the correct state
else:
click.echo(
@@ -605,6 +652,13 @@ CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
help="git remote to use for PR branches",
default="origin",
)
[email protected](
+ "--upstream-remote",
+ "upstream_remote",
+ metavar="REMOTE",
+ help="git remote to use for upstream branches",
+ default=None,
+)
@click.option(
"--abort",
"abort",
@@ -662,6 +716,7 @@ def cherry_pick_cli(
ctx,
dry_run,
pr_remote,
+ upstream_remote,
abort,
status,
push,
@@ -681,6 +736,7 @@ def cherry_pick_cli(
pr_remote,
commit_sha1,
branches,
+ upstream_remote=upstream_remote,
dry_run=dry_run,
push=push,
auto_pr=auto_pr,
@@ -795,6 +851,13 @@ def get_author_info_from_short_sha(short_sha):
return author
+def get_commits_from_backport_branch(cherry_pick_branch):
+ cmd = ["git", "log", "--format=%H", f"{cherry_pick_branch}.."]
+ output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
+ commits = output.strip().decode("utf-8").splitlines()
+ return commits
+
+
def normalize_commit_message(commit_message):
"""
Return a tuple of title and body from the commit message
diff --git a/readme.rst b/readme.rst
index 13c5f5c..6028338 100644
--- a/readme.rst
+++ b/readme.rst
@@ -1,6 +1,6 @@
Usage (from a cloned CPython directory) ::
- cherry_picker [--pr-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--status] [--abort/--continue] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
+ cherry_picker [--pr-remote REMOTE] [--upstream-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--status] [--abort/--continue] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
|pyversion status|
|pypi status|
@@ -41,6 +41,8 @@ Requires Python 3.7.
The cherry picking script assumes that if an ``upstream`` remote is defined, then
it should be used as the source of upstream changes and as the base for
cherry-pick branches. Otherwise, ``origin`` is used for that purpose.
+You can override this behavior with the ``--upstream-remote`` option
+(e.g. ``--upstream-remote python`` to use a remote named ``python``).
Verify that an ``upstream`` remote is set to the CPython repository:
@@ -73,7 +75,7 @@ From the cloned CPython directory:
.. code-block:: console
- (venv) $ cherry_picker [--pr-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--abort/--continue] [--status] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
+ (venv) $ cherry_picker [--pr-remote REMOTE] [--upstream-remote REMOTE] [--dry-run] [--config-path CONFIG-PATH] [--abort/--continue] [--status] [--push/--no-push] [--auto-pr/--no-auto-pr] <commit_sha1> <branches>
Commit sha1
@@ -94,9 +96,11 @@ Options
::
- --dry-run Dry Run Mode. Prints out the commands, but not executed.
- --pr-remote REMOTE Specify the git remote to push into. Default is 'origin'.
- --status Do `git status` in cpython directory.
+ --dry-run Dry Run Mode. Prints out the commands, but not executed.
+ --pr-remote REMOTE Specify the git remote to push into. Default is 'origin'.
+ --upstream-remote REMOTE Specify the git remote to use for upstream branches.
+ Default is 'upstream' or 'origin' if the former doesn't exist.
+ --status Do `git status` in cpython directory.
Additional options::
@@ -252,6 +256,11 @@ steps it would execute without actually executing any of them. For example:
This will generate pull requests through a remote other than ``origin``
(e.g. ``pr``)
+`--upstream-remote` option
+--------------------------
+
+This will generate branches from a remote other than ``upstream``/``origin``
+(e.g. ``python``)
`--status` option
-----------------
|
python/cherry-picker
|
0ecbf068aeb6ebf42c933f803e55c8b22117c812
|
diff --git a/cherry_picker/test_cherry_picker.py b/cherry_picker/test_cherry_picker.py
index 6f733e3..bc5638b 100644
--- a/cherry_picker/test_cherry_picker.py
+++ b/cherry_picker/test_cherry_picker.py
@@ -11,6 +11,7 @@ import pytest
from .cherry_picker import (
DEFAULT_CONFIG,
WORKFLOW_STATES,
+ BranchCheckoutException,
CherryPicker,
CherryPickException,
InvalidRepoException,
@@ -18,6 +19,7 @@ from .cherry_picker import (
from_git_rev_read,
get_author_info_from_short_sha,
get_base_branch,
+ get_commits_from_backport_branch,
get_current_branch,
get_full_sha_from_short,
get_sha1_from,
@@ -57,6 +59,12 @@ def git_init():
return lambda: subprocess.run(git_init_cmd, check=True)
[email protected]
+def git_remote():
+ git_remote_cmd = "git", "remote"
+ return lambda *extra_args: (subprocess.run(git_remote_cmd + extra_args, check=True))
+
+
@pytest.fixture
def git_add():
git_add_cmd = "git", "add"
@@ -101,6 +109,12 @@ def git_cherry_pick():
)
[email protected]
+def git_reset():
+ git_reset_cmd = "git", "reset"
+ return lambda *extra_args: (subprocess.run(git_reset_cmd + extra_args, check=True))
+
+
@pytest.fixture
def git_config():
git_config_cmd = "git", "config"
@@ -238,6 +252,62 @@ def test_get_cherry_pick_branch(os_path_exists, config):
assert cp.get_cherry_pick_branch("3.6") == "backport-22a594a-3.6"
[email protected](
+ "remote_name,upstream_remote",
+ (
+ ("upstream", None),
+ ("upstream", "upstream"),
+ ("origin", None),
+ ("origin", "origin"),
+ ("python", "python"),
+ ),
+)
+def test_upstream_name(remote_name, upstream_remote, config, tmp_git_repo_dir, git_remote):
+ git_remote("add", remote_name, "https://github.com/python/cpython.git")
+ if remote_name != "origin":
+ git_remote("add", "origin", "https://github.com/miss-islington/cpython.git")
+
+ branches = ["3.6"]
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cp = CherryPicker(
+ "origin",
+ "22a594a0047d7706537ff2ac676cdc0f1dcb329c",
+ branches,
+ config=config,
+ upstream_remote=upstream_remote,
+ )
+ assert cp.upstream == remote_name
+
+
[email protected](
+ "remote_to_add,remote_name,upstream_remote",
+ (
+ (None, "upstream", None),
+ ("origin", "upstream", "upstream"),
+ (None, "origin", None),
+ ("upstream", "origin", "origin"),
+ ("origin", "python", "python"),
+ (None, "python", None),
+ ),
+)
+def test_error_on_missing_remote(remote_to_add, remote_name, upstream_remote, config, tmp_git_repo_dir, git_remote):
+ git_remote("add", "some-remote-name", "https://github.com/python/cpython.git")
+ if remote_to_add is not None:
+ git_remote("add", remote_to_add, "https://github.com/miss-islington/cpython.git")
+
+ branches = ["3.6"]
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cp = CherryPicker(
+ "origin",
+ "22a594a0047d7706537ff2ac676cdc0f1dcb329c",
+ branches,
+ config=config,
+ upstream_remote=upstream_remote,
+ )
+ with pytest.raises(ValueError):
+ cp.upstream
+
+
def test_get_pr_url(config):
branches = ["3.6"]
@@ -825,6 +895,38 @@ def test_backport_cherry_pick_crash_ignored(
assert get_state() == WORKFLOW_STATES.UNSET
+def test_backport_cherry_pick_branch_already_exists(
+ tmp_git_repo_dir, git_branch, git_add, git_commit, git_checkout
+):
+ cherry_pick_target_branches = ("3.8",)
+ pr_remote = "origin"
+ test_file = "some.file"
+ tmp_git_repo_dir.join(test_file).write("some contents")
+ git_branch(cherry_pick_target_branches[0])
+ git_branch(
+ f"{pr_remote}/{cherry_pick_target_branches[0]}", cherry_pick_target_branches[0]
+ )
+ git_add(test_file)
+ git_commit("Add a test file")
+ scm_revision = get_sha1_from("HEAD")
+
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cherry_picker = CherryPicker(
+ pr_remote, scm_revision, cherry_pick_target_branches
+ )
+
+ backport_branch_name = cherry_picker.get_cherry_pick_branch(cherry_pick_target_branches[0])
+ git_branch(backport_branch_name)
+
+ with mock.patch.object(cherry_picker, "fetch_upstream"), pytest.raises(
+ BranchCheckoutException
+ ) as exc_info:
+ cherry_picker.backport()
+
+ assert exc_info.value.branch_name == backport_branch_name
+ assert get_state() == WORKFLOW_STATES.UNSET
+
+
def test_backport_success(
tmp_git_repo_dir, git_branch, git_add, git_commit, git_checkout
):
@@ -857,8 +959,10 @@ def test_backport_success(
assert get_state() == WORKFLOW_STATES.UNSET
[email protected]("already_committed", (True, False))
[email protected]("push", (True, False))
def test_backport_pause_and_continue(
- tmp_git_repo_dir, git_branch, git_add, git_commit, git_checkout
+ tmp_git_repo_dir, git_branch, git_add, git_commit, git_checkout, git_reset, already_committed, push
):
cherry_pick_target_branches = ("3.8",)
pr_remote = "origin"
@@ -879,16 +983,27 @@ def test_backport_pause_and_continue(
pr_remote, scm_revision, cherry_pick_target_branches, push=False
)
- with mock.patch.object(cherry_picker, "checkout_branch"), mock.patch.object(
- cherry_picker, "fetch_upstream"
- ), mock.patch.object(
+ with mock.patch.object(cherry_picker, "fetch_upstream"), mock.patch.object(
cherry_picker, "amend_commit_message", return_value="commit message"
):
cherry_picker.backport()
+ assert len(get_commits_from_backport_branch(cherry_pick_target_branches[0])) == 1
assert get_state() == WORKFLOW_STATES.BACKPORT_PAUSED
- cherry_picker.initial_state = get_state()
+ if not already_committed:
+ git_reset("HEAD~1")
+ assert len(get_commits_from_backport_branch(cherry_pick_target_branches[0])) == 0
+
+ with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
+ cherry_picker = CherryPicker(pr_remote, "", [], push=push)
+
+ commit_message = f"""[{cherry_pick_target_branches[0]}] commit message
+(cherry picked from commit xxxxxxyyyyyy)
+
+
+Co-authored-by: Author Name <[email protected]>"""
+
with mock.patch(
"cherry_picker.cherry_picker.wipe_cfg_vals_from_git_cfg"
), mock.patch(
@@ -900,21 +1015,29 @@ def test_backport_pause_and_continue(
"cherry_picker.cherry_picker.get_current_branch",
return_value="backport-xxx-3.8",
), mock.patch.object(
- cherry_picker,
- "get_updated_commit_message",
- return_value="""[3.8] commit message
-(cherry picked from commit xxxxxxyyyyyy)
-
-
-Co-authored-by: Author Name <[email protected]>""",
- ), mock.patch.object(
+ cherry_picker, "amend_commit_message", return_value=commit_message
+ ) as amend_commit_message, mock.patch.object(
+ cherry_picker, "get_updated_commit_message", return_value=commit_message
+ ) as get_updated_commit_message, mock.patch.object(
cherry_picker, "checkout_branch"
), mock.patch.object(
cherry_picker, "fetch_upstream"
+ ), mock.patch.object(
+ cherry_picker, "cleanup_branch"
):
cherry_picker.continue_cherry_pick()
- assert get_state() == WORKFLOW_STATES.BACKPORTING_CONTINUATION_SUCCEED
+ if already_committed:
+ amend_commit_message.assert_called_once()
+ get_updated_commit_message.assert_not_called()
+ else:
+ get_updated_commit_message.assert_called_once()
+ amend_commit_message.assert_not_called()
+
+ if push:
+ assert get_state() == WORKFLOW_STATES.BACKPORTING_CONTINUATION_SUCCEED
+ else:
+ assert get_state() == WORKFLOW_STATES.BACKPORT_PAUSED
def test_continue_cherry_pick_invalid_state(tmp_git_repo_dir):
@@ -955,18 +1078,6 @@ def test_abort_cherry_pick_invalid_state(tmp_git_repo_dir):
cherry_picker.abort_cherry_pick()
-def test_abort_cherry_pick_fail(tmp_git_repo_dir):
- set_state(WORKFLOW_STATES.BACKPORT_PAUSED)
-
- with mock.patch("cherry_picker.cherry_picker.validate_sha", return_value=True):
- cherry_picker = CherryPicker("origin", "xxx", [])
-
- with mock.patch("cherry_picker.cherry_picker.wipe_cfg_vals_from_git_cfg"):
- cherry_picker.abort_cherry_pick()
-
- assert get_state() == WORKFLOW_STATES.ABORTING_FAILED
-
-
def test_abort_cherry_pick_success(
tmp_git_repo_dir, git_branch, git_add, git_commit, git_checkout, git_cherry_pick
):
|
`cherry_picker --continue` does not respect `--no-push` option
If after resolving conflict, I use `cherry_picker --no-push --continue`, `cherry_picker` will push to remote (and open webbrowser/make PR through API) regardless.
|
0.0
|
0ecbf068aeb6ebf42c933f803e55c8b22117c812
|
[
"cherry_picker/test_cherry_picker.py::test_get_base_branch",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_which_has_dashes",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[backport-22a594a]",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[prefix-22a594a-2.7]",
"cherry_picker/test_cherry_picker.py::test_get_base_branch_invalid[backport-22a594a-base]",
"cherry_picker/test_cherry_picker.py::test_get_current_branch",
"cherry_picker/test_cherry_picker.py::test_get_full_sha_from_short",
"cherry_picker/test_cherry_picker.py::test_get_author_info_from_short_sha",
"cherry_picker/test_cherry_picker.py::test_sorted_branch[input_branches0-sorted_branches0]",
"cherry_picker/test_cherry_picker.py::test_sorted_branch[input_branches1-sorted_branches1]",
"cherry_picker/test_cherry_picker.py::test_invalid_branches[input_branches0]",
"cherry_picker/test_cherry_picker.py::test_invalid_branches[input_branches1]",
"cherry_picker/test_cherry_picker.py::test_get_cherry_pick_branch",
"cherry_picker/test_cherry_picker.py::test_upstream_name[upstream-None]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[upstream-upstream]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[origin-None]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[origin-origin]",
"cherry_picker/test_cherry_picker.py::test_upstream_name[python-python]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-upstream-None]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[origin-upstream-upstream]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-origin-None]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[upstream-origin-origin]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[origin-python-python]",
"cherry_picker/test_cherry_picker.py::test_error_on_missing_remote[None-python-None]",
"cherry_picker/test_cherry_picker.py::test_get_pr_url",
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[[email protected]:mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[ssh://[email protected]/mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython.git]",
"cherry_picker/test_cherry_picker.py::test_username[https://github.com/mock_user/cpython]",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message",
"cherry_picker/test_cherry_picker.py::test_get_updated_commit_message_without_links_replacement",
"cherry_picker/test_cherry_picker.py::test_is_cpython_repo",
"cherry_picker/test_cherry_picker.py::test_is_not_cpython_repo",
"cherry_picker/test_cherry_picker.py::test_find_config",
"cherry_picker/test_cherry_picker.py::test_find_config_not_found",
"cherry_picker/test_cherry_picker.py::test_find_config_not_git",
"cherry_picker/test_cherry_picker.py::test_load_full_config",
"cherry_picker/test_cherry_picker.py::test_load_partial_config",
"cherry_picker/test_cherry_picker.py::test_load_config_no_head_sha",
"cherry_picker/test_cherry_picker.py::test_normalize_long_commit_message",
"cherry_picker/test_cherry_picker.py::test_normalize_short_commit_message",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_negative[/some/path/without/revision]",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_negative[HEAD:some/non-existent/path]",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read_uncommitted",
"cherry_picker/test_cherry_picker.py::test_from_git_rev_read",
"cherry_picker/test_cherry_picker.py::test_states",
"cherry_picker/test_cherry_picker.py::test_paused_flow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[fetch_upstream-Workflow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[checkout_default_branch-Workflow",
"cherry_picker/test_cherry_picker.py::test_start_end_states[checkout_previous_branch-Workflow",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_checkout_previous_branch",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_fail",
"cherry_picker/test_cherry_picker.py::test_cleanup_branch_checkout_fail",
"cherry_picker/test_cherry_picker.py::test_cherry_pick",
"cherry_picker/test_cherry_picker.py::test_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_get_state_and_verify_fail",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_fail",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_interactive",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_botflow",
"cherry_picker/test_cherry_picker.py::test_push_to_remote_no_auto_pr",
"cherry_picker/test_cherry_picker.py::test_backport_no_branch",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_fail",
"cherry_picker/test_cherry_picker.py::test_backport_cherry_pick_crash_ignored",
"cherry_picker/test_cherry_picker.py::test_backport_success",
"cherry_picker/test_cherry_picker.py::test_continue_cherry_pick_invalid_state",
"cherry_picker/test_cherry_picker.py::test_continue_cherry_pick_invalid_branch",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_invalid_state",
"cherry_picker/test_cherry_picker.py::test_abort_cherry_pick_success",
"cherry_picker/test_cherry_picker.py::test_cli_invoked"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-07 17:59:45+00:00
|
apache-2.0
| 5,117 |
|
python__mypy_extensions-47
|
diff --git a/mypy_extensions.py b/mypy_extensions.py
index 6600b21..aff5145 100644
--- a/mypy_extensions.py
+++ b/mypy_extensions.py
@@ -42,17 +42,32 @@ def _typeddict_new(cls, _typename, _fields=None, **kwargs):
except (AttributeError, ValueError):
pass
- return _TypedDictMeta(_typename, (), ns)
+ return _TypedDictMeta(_typename, (), ns, _from_functional_call=True)
class _TypedDictMeta(type):
- def __new__(cls, name, bases, ns, total=True):
+ def __new__(cls, name, bases, ns, total=True, _from_functional_call=False):
# Create new typed dict class object.
# This method is called directly when TypedDict is subclassed,
# or via _typeddict_new when TypedDict is instantiated. This way
# TypedDict supports all three syntaxes described in its docstring.
# Subclasses and instances of TypedDict return actual dictionaries
# via _dict_new.
+
+ # We need the `if TypedDict in globals()` check,
+ # or we emit a DeprecationWarning when creating mypy_extensions.TypedDict itself
+ if 'TypedDict' in globals():
+ import warnings
+ warnings.warn(
+ (
+ "mypy_extensions.TypedDict is deprecated, "
+ "and will be removed in a future version. "
+ "Use typing.TypedDict or typing_extensions.TypedDict instead."
+ ),
+ DeprecationWarning,
+ stacklevel=(3 if _from_functional_call else 2)
+ )
+
ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
diff --git a/tox.ini b/tox.ini
index 9f64a32..b0766b5 100644
--- a/tox.ini
+++ b/tox.ini
@@ -5,7 +5,7 @@ envlist = py35, py36, py37, py38, py39, py310, py311
[testenv]
description = run the test driver with {basepython}
-commands = python -m unittest discover tests
+commands = python -We -m unittest discover tests
[testenv:lint]
description = check the code style
|
python/mypy_extensions
|
a1b59f718e28c5dc897272211e0d00e0f58cc908
|
diff --git a/tests/testextensions.py b/tests/testextensions.py
index 991c4e5..a41f5f6 100644
--- a/tests/testextensions.py
+++ b/tests/testextensions.py
@@ -1,6 +1,8 @@
import sys
import pickle
import typing
+from contextlib import contextmanager
+from textwrap import dedent
from unittest import TestCase, main, skipUnless
from mypy_extensions import TypedDict, i64, i32, i16, u8
@@ -25,17 +27,22 @@ class BaseTestCase(TestCase):
PY36 = sys.version_info[:2] >= (3, 6)
PY36_TESTS = """
-Label = TypedDict('Label', [('label', str)])
+import warnings
-class Point2D(TypedDict):
- x: int
- y: int
+with warnings.catch_warnings():
+ warnings.simplefilter("ignore", category=DeprecationWarning)
-class LabelPoint2D(Point2D, Label): ...
+ Label = TypedDict('Label', [('label', str)])
-class Options(TypedDict, total=False):
- log_level: int
- log_path: str
+ class Point2D(TypedDict):
+ x: int
+ y: int
+
+ class LabelPoint2D(Point2D, Label): ...
+
+ class Options(TypedDict, total=False):
+ log_level: int
+ log_path: str
"""
if PY36:
@@ -43,9 +50,16 @@ if PY36:
class TypedDictTests(BaseTestCase):
+ @contextmanager
+ def assert_typeddict_deprecated(self):
+ with self.assertWarnsRegex(
+ DeprecationWarning, "mypy_extensions.TypedDict is deprecated"
+ ):
+ yield
def test_basics_iterable_syntax(self):
- Emp = TypedDict('Emp', {'name': str, 'id': int})
+ with self.assert_typeddict_deprecated():
+ Emp = TypedDict('Emp', {'name': str, 'id': int})
self.assertIsSubclass(Emp, dict)
self.assertIsSubclass(Emp, typing.MutableMapping)
if sys.version_info[0] >= 3:
@@ -62,7 +76,8 @@ class TypedDictTests(BaseTestCase):
self.assertEqual(Emp.__total__, True)
def test_basics_keywords_syntax(self):
- Emp = TypedDict('Emp', name=str, id=int)
+ with self.assert_typeddict_deprecated():
+ Emp = TypedDict('Emp', name=str, id=int)
self.assertIsSubclass(Emp, dict)
self.assertIsSubclass(Emp, typing.MutableMapping)
if sys.version_info[0] >= 3:
@@ -79,7 +94,8 @@ class TypedDictTests(BaseTestCase):
self.assertEqual(Emp.__total__, True)
def test_typeddict_errors(self):
- Emp = TypedDict('Emp', {'name': str, 'id': int})
+ with self.assert_typeddict_deprecated():
+ Emp = TypedDict('Emp', {'name': str, 'id': int})
self.assertEqual(TypedDict.__module__, 'mypy_extensions')
jim = Emp(name='Jim', id=1)
with self.assertRaises(TypeError):
@@ -88,9 +104,9 @@ class TypedDictTests(BaseTestCase):
isinstance(jim, Emp) # type: ignore
with self.assertRaises(TypeError):
issubclass(dict, Emp) # type: ignore
- with self.assertRaises(TypeError):
+ with self.assertRaises(TypeError), self.assert_typeddict_deprecated():
TypedDict('Hi', x=())
- with self.assertRaises(TypeError):
+ with self.assertRaises(TypeError), self.assert_typeddict_deprecated():
TypedDict('Hi', [('x', int), ('y', ())])
with self.assertRaises(TypeError):
TypedDict('Hi', [('x', int)], y=int)
@@ -109,9 +125,20 @@ class TypedDictTests(BaseTestCase):
other = LabelPoint2D(x=0, y=1, label='hi') # noqa
self.assertEqual(other['label'], 'hi')
+ if PY36:
+ exec(dedent(
+ """
+ def test_py36_class_usage_emits_deprecations(self):
+ with self.assert_typeddict_deprecated():
+ class Foo(TypedDict):
+ bar: int
+ """
+ ))
+
def test_pickle(self):
global EmpD # pickle wants to reference the class by name
- EmpD = TypedDict('EmpD', name=str, id=int)
+ with self.assert_typeddict_deprecated():
+ EmpD = TypedDict('EmpD', name=str, id=int)
jane = EmpD({'name': 'jane', 'id': 37})
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(jane, proto)
@@ -123,13 +150,15 @@ class TypedDictTests(BaseTestCase):
self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane)
def test_optional(self):
- EmpD = TypedDict('EmpD', name=str, id=int)
+ with self.assert_typeddict_deprecated():
+ EmpD = TypedDict('EmpD', name=str, id=int)
self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD])
self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD])
def test_total(self):
- D = TypedDict('D', {'x': int}, total=False)
+ with self.assert_typeddict_deprecated():
+ D = TypedDict('D', {'x': int}, total=False)
self.assertEqual(D(), {})
self.assertEqual(D(x=1), {'x': 1})
self.assertEqual(D.__total__, False)
|
Deprecate `mypy_extensions.TypedDict`?
`mypy_extensions.TypedDict` is problematic for several reasons:
- `mypy_extensions.TypedDict` is missing quite a few features that have been added to `typing.TypedDict` at runtime (and have been backported to `typing_extensions.TypedDict`).
- I think the existence of both `mypy_extensions.TypedDict` and `typing_extensions.TypedDict` has the potential to be pretty confusing for users.
- It's quite annoying and error-prone that at typeshed, we have to remember to keep `typing._TypedDict`, `typing_extensions._TypedDict` and `mypy_extensions._TypedDict` all in sync. Unfortunately, we can't put them all in `_typeshed` and have all three modules import `_TypedDict` from `_typeshed`, as the three classes all have slightly subtle differences. (E.g. `mypy_extensions._TypedDict` doesn't have the `__required_keys__` and `__optional_keys__` ClassVars that both `typing._TypedDict` and `typing_extensions._TypedDict` have.)
- Mypy now maintains its own copy of the `mypy-extensions` stubs anyway, so its stubs for `mypy_extensions` are no longer automatically updated with each typeshed sync. That means that even if we update the stubs for `mypy_extensions.TypedDict` in typeshed (as we did in https://github.com/python/typeshed/pull/10565), those updates are no longer of any benefit to mypy users unless mypy maintainers remember to copy across the changes to their forked version of the `mypy_extensions` stubs.
I propose that we deprecate `mypy_extensions.TypedDict`, and steer people towards `typing_extensions.TypedDict` instead: it's up-to-date with the features on `typing.TypedDict`, it's much more comprehensively tested, and it has up-to-date stubs.
Thoughts?
|
0.0
|
a1b59f718e28c5dc897272211e0d00e0f58cc908
|
[
"tests/testextensions.py::TypedDictTests::test_basics_iterable_syntax",
"tests/testextensions.py::TypedDictTests::test_basics_keywords_syntax",
"tests/testextensions.py::TypedDictTests::test_optional",
"tests/testextensions.py::TypedDictTests::test_pickle",
"tests/testextensions.py::TypedDictTests::test_py36_class_usage_emits_deprecations",
"tests/testextensions.py::TypedDictTests::test_total",
"tests/testextensions.py::TypedDictTests::test_typeddict_errors"
] |
[
"tests/testextensions.py::TypedDictTests::test_py36_class_syntax_usage",
"tests/testextensions.py::MypycNativeIntTests::test_construction",
"tests/testextensions.py::MypycNativeIntTests::test_docstring",
"tests/testextensions.py::MypycNativeIntTests::test_isinstance"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-17 18:03:28+00:00
|
mit
| 5,118 |
|
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 |
|
pytorch__ignite-1044
|
diff --git a/ignite/contrib/metrics/gpu_info.py b/ignite/contrib/metrics/gpu_info.py
index d4b60df2..35e848f3 100644
--- a/ignite/contrib/metrics/gpu_info.py
+++ b/ignite/contrib/metrics/gpu_info.py
@@ -11,6 +11,10 @@ class GpuInfo(Metric):
"""Provides GPU information: a) used memory percentage, b) gpu utilization percentage values as Metric
on each iterations.
+ .. Note ::
+
+ In case if gpu utilization reports "N/A" on a given GPU, corresponding metric value is not set.
+
Examples:
.. code-block:: python
@@ -90,11 +94,14 @@ class GpuInfo(Metric):
util_report = data_by_rank["utilization"]
if not ("gpu_util" in util_report):
warnings.warn(
- "GPU utilization information does not provide 'gpu_util' information in " "{}".format(util_report)
+ "GPU utilization information does not provide 'gpu_util' information in {}".format(util_report)
)
continue
-
- engine.state.metrics[util_name] = int(util_report["gpu_util"])
+ try:
+ engine.state.metrics[util_name] = int(util_report["gpu_util"])
+ except ValueError:
+ # Do not set GPU utilization information
+ pass
def attach(self, engine, name="gpu", event_name=Events.ITERATION_COMPLETED):
engine.add_event_handler(event_name, self.completed, name)
|
pytorch/ignite
|
7e3ee043e86fc74802baeaa36ebb0a982aabb908
|
diff --git a/tests/ignite/contrib/metrics/test_gpu_info.py b/tests/ignite/contrib/metrics/test_gpu_info.py
index 75413ac5..d37fc7e7 100644
--- a/tests/ignite/contrib/metrics/test_gpu_info.py
+++ b/tests/ignite/contrib/metrics/test_gpu_info.py
@@ -66,13 +66,16 @@ def _test_gpu_info(device="cpu"):
gpu_info.completed(engine, name="gpu")
assert "gpu:0 mem(%)" in engine.state.metrics
- assert "gpu:0 util(%)" in engine.state.metrics
assert isinstance(engine.state.metrics["gpu:0 mem(%)"], int)
assert int(mem_report["used"] * 100.0 / mem_report["total"]) == engine.state.metrics["gpu:0 mem(%)"]
- assert isinstance(engine.state.metrics["gpu:0 util(%)"], int)
- assert int(util_report["gpu_util"]) == engine.state.metrics["gpu:0 util(%)"]
+ if util_report["gpu_util"] != "N/A":
+ assert "gpu:0 util(%)" in engine.state.metrics
+ assert isinstance(engine.state.metrics["gpu:0 util(%)"], int)
+ assert int(util_report["gpu_util"]) == engine.state.metrics["gpu:0 util(%)"]
+ else:
+ assert "gpu:0 util(%)" not in engine.state.metrics
@pytest.mark.skipif(python_below_36 or not (torch.cuda.is_available()), reason="No pynvml for python < 3.6 and no GPU")
@@ -80,6 +83,9 @@ def test_gpu_info_on_cuda():
_test_gpu_info(device="cuda")
+query_resp = None
+
+
@pytest.fixture
def mock_pynvml_module():
@@ -95,7 +101,7 @@ def mock_pynvml_module():
from pynvml.smi import nvidia_smi
def query(*args, **kwargs):
- return {"gpu": [{"fb_memory_usage": {"used": 100.0, "total": 11000.0}, "utilization": {"gpu_util": 50.0}}]}
+ return query_resp
def getInstance():
nvsmi = Mock()
@@ -116,10 +122,17 @@ def mock_gpu_is_available():
@pytest.mark.skipif(torch.cuda.is_available(), reason="No need to mock if has GPU")
def test_gpu_info_mock(mock_pynvml_module, mock_gpu_is_available):
+ global query_resp
+
+ query_resp = {"gpu": [{"fb_memory_usage": {"used": 100.0, "total": 11000.0}, "utilization": {"gpu_util": 50.0}}]}
assert torch.cuda.is_available()
_test_gpu_info()
+ # Tests https://github.com/pytorch/ignite/issues/1040
+ query_resp = {"gpu": [{"fb_memory_usage": {"used": 100.0, "total": 11000.0}, "utilization": {"gpu_util": "N/A"}}]}
+ _test_gpu_info()
+
def _test_with_custom_query(resp, warn_msg, check_compute=False):
from pynvml.smi import nvidia_smi
|
gpu_info crashes because it cannot parse "N/A"
## 🐛 Bug description
When trying to use gpu_info, it throws:
```
File "/home/blackhc/anaconda3/envs/hello-mnist/lib/python3.7/site-packages/ignite/contrib/metrics/gpu_info.py", line 91, in completed
engine.state.metrics[util_name] = int(util_report['gpu_util'])
ValueError: invalid literal for int() with base 10: 'N/A'
```
There is error handling code above it, but it does not catch the issue ("N/A" is returned).
I assume my GPU does not support it. However, it would be neat to have a graceful failure mode.
Thank you!
Andreas
## Environment
torch 1.5 on a GTX 780 TI (source)
ignite 0.3.0 (conda)
pynvml 8.0.4 (pip)
|
0.0
|
7e3ee043e86fc74802baeaa36ebb0a982aabb908
|
[
"tests/ignite/contrib/metrics/test_gpu_info.py::test_gpu_info_mock"
] |
[] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-05-16 13:54:05+00:00
|
bsd-3-clause
| 5,120 |
|
pytorch__ignite-1063
|
diff --git a/docs/source/handlers.rst b/docs/source/handlers.rst
index 196ce8ea..96b18175 100644
--- a/docs/source/handlers.rst
+++ b/docs/source/handlers.rst
@@ -5,6 +5,7 @@ Complete list of handlers
-------------------------
- :class:`~ignite.handlers.Checkpoint`
+ - :class:`~ignite.handlers.checkpoint.BaseSaveHandler`
- :class:`~ignite.handlers.DiskSaver`
- :class:`~ignite.handlers.ModelCheckpoint`
- :class:`~ignite.handlers.EarlyStopping`
@@ -17,6 +18,9 @@ Complete list of handlers
.. autoclass:: Checkpoint
:members: load_objects
+.. autoclass:: ignite.handlers.checkpoint.BaseSaveHandler
+ :members: __call__, remove
+
.. autoclass:: DiskSaver
.. autoclass:: ModelCheckpoint
diff --git a/ignite/contrib/handlers/neptune_logger.py b/ignite/contrib/handlers/neptune_logger.py
index e342cf30..434d6182 100644
--- a/ignite/contrib/handlers/neptune_logger.py
+++ b/ignite/contrib/handlers/neptune_logger.py
@@ -1,7 +1,7 @@
import numbers
import tempfile
import warnings
-from typing import Mapping
+from typing import Mapping, Optional
import torch
@@ -574,7 +574,7 @@ class NeptuneSaver(BaseSaveHandler):
def __init__(self, neptune_logger: NeptuneLogger):
self._logger = neptune_logger
- def __call__(self, checkpoint: Mapping, filename: str) -> None:
+ def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mapping] = None) -> None:
with tempfile.NamedTemporaryFile() as tmp:
torch.save(checkpoint, tmp.name)
diff --git a/ignite/contrib/handlers/trains_logger.py b/ignite/contrib/handlers/trains_logger.py
index 28e520a4..7cae3d24 100644
--- a/ignite/contrib/handlers/trains_logger.py
+++ b/ignite/contrib/handlers/trains_logger.py
@@ -643,8 +643,8 @@ class TrainsSaver(DiskSaver):
if output_uri:
self.task.output_uri = output_uri
- def __call__(self, checkpoint: Mapping, filename: str) -> None:
- super(TrainsSaver, self).__call__(checkpoint, filename)
+ def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mapping] = None) -> None:
+ super(TrainsSaver, self).__call__(checkpoint, filename, metadata)
try:
import trains
diff --git a/ignite/handlers/checkpoint.py b/ignite/handlers/checkpoint.py
index 80342f52..dd62d70f 100644
--- a/ignite/handlers/checkpoint.py
+++ b/ignite/handlers/checkpoint.py
@@ -15,14 +15,39 @@ __all__ = ["Checkpoint", "DiskSaver", "ModelCheckpoint", "BaseSaveHandler"]
class BaseSaveHandler(metaclass=ABCMeta):
- """Base class for save handlers"""
+ """Base class for save handlers
+
+ Methods to override:
+
+ - :meth:`~ignite.handlers.checkpoint.BaseSaveHandler.__call__`
+ - :meth:`~ignite.handlers.checkpoint.BaseSaveHandler.remove`
+ """
@abstractmethod
- def __call__(self, checkpoint: Mapping, filename: str) -> None:
+ def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mapping] = None) -> None:
+ """Method to save `checkpoint` with `filename`. Additionally, metadata dictionary is provided.
+
+ Metadata contains:
+
+ - `basename`: file prefix (if provided) with checkpoint name, e.g. `epoch_checkpoint`.
+ - `score_name`: score name if provided, e.g `val_acc`.
+ - `priority`: checkpoint priority value (higher is better), e.g. `12` or `0.6554435`
+
+ Args:
+ checkpoint (Mapping): checkpoint dictionary to save.
+ filename (str): filename associated with checkpoint.
+ metadata (Mapping, optional): metadata on checkpoint to save.
+
+ """
pass
@abstractmethod
def remove(self, filename: str) -> None:
+ """Method to remove saved checkpoint.
+
+ Args:
+ filename (str): filename associated with checkpoint.
+ """
pass
@@ -34,9 +59,9 @@ class Checkpoint:
Args:
to_save (Mapping): Dictionary with the objects to save. Objects should have implemented `state_dict` and `
load_state_dict` methods.
- save_handler (callable or `BaseSaveHandler`): Method or callable class to use to save engine and other provided
- objects. Function receives two objects: checkpoint as a dictionary and filename. If `save_handler` is
- callable class, it can
+ save_handler (callable or :class:`~ignite.handlers.checkpoint.BaseSaveHandler`): Method or callable class to
+ use to save engine and other provided objects. Function receives two objects: checkpoint as a dictionary
+ and filename. If `save_handler` is callable class, it can
inherit of :class:`~ignite.handlers.checkpoint.BaseSaveHandler` and optionally implement `remove` method to
keep a fixed number of saved checkpoints. In case if user needs to save engine's checkpoint on a disk,
`save_handler` can be defined with :class:`~ignite.handlers.DiskSaver`.
@@ -184,7 +209,7 @@ class Checkpoint:
self.global_step_transform = global_step_transform
@property
- def last_checkpoint(self) -> str:
+ def last_checkpoint(self) -> Optional[str]:
if len(self._saved) < 1:
return None
return self._saved[-1].filename
@@ -237,7 +262,16 @@ class Checkpoint:
if any(item.filename == filename for item in self._saved):
return
- self.save_handler(checkpoint, filename)
+ metadata = {
+ "basename": "{}{}".format(self._fname_prefix, name),
+ "score_name": self._score_name,
+ "priority": priority,
+ }
+
+ try:
+ self.save_handler(checkpoint, filename, metadata)
+ except TypeError:
+ self.save_handler(checkpoint, filename)
self._saved.append(Checkpoint.Item(priority, filename))
self._saved.sort(key=lambda item: item[0])
@@ -350,7 +384,7 @@ class DiskSaver(BaseSaveHandler):
"".format(matched, dirname)
)
- def __call__(self, checkpoint: Mapping, filename: str) -> None:
+ def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mapping] = None) -> None:
path = os.path.join(self.dirname, filename)
if not self._atomic:
|
pytorch/ignite
|
c012166f93e56f8e9538741f5745a5010983ba38
|
diff --git a/tests/ignite/handlers/test_checkpoint.py b/tests/ignite/handlers/test_checkpoint.py
index c646bc85..495d9272 100644
--- a/tests/ignite/handlers/test_checkpoint.py
+++ b/tests/ignite/handlers/test_checkpoint.py
@@ -87,13 +87,15 @@ def test_checkpoint_default():
checkpointer(trainer)
assert save_handler.call_count == 1
- save_handler.assert_called_with(obj, "{}_0.pt".format(name))
+ metadata = {"basename": name, "score_name": None, "priority": 0}
+ save_handler.assert_called_with(obj, "{}_0.pt".format(name), metadata)
trainer.state.epoch = 12
trainer.state.iteration = 1234
checkpointer(trainer)
assert save_handler.call_count == 2
- save_handler.assert_called_with(obj, "{}_1234.pt".format(name))
+ metadata["priority"] = 1234
+ save_handler.assert_called_with(obj, "{}_1234.pt".format(name), metadata)
assert save_handler.remove.call_count == 1
save_handler.remove.assert_called_with("{}_0.pt".format(name))
assert checkpointer.last_checkpoint == "{}_1234.pt".format(name)
@@ -128,13 +130,15 @@ def test_checkpoint_with_global_step_transform():
if len(filename_prefix) > 0:
filename_prefix += "_"
- save_handler.assert_called_with(obj, "{}{}_1.pt".format(filename_prefix, name))
+ metadata = {"basename": "{}{}".format(filename_prefix, name), "score_name": None, "priority": 1}
+ save_handler.assert_called_with(obj, "{}{}_1.pt".format(filename_prefix, name), metadata)
trainer.state.epoch = 12
trainer.state.iteration = 1234
checkpointer(trainer)
assert save_handler.call_count == 2
- save_handler.assert_called_with(obj, "{}{}_12.pt".format(filename_prefix, name))
+ metadata["priority"] = 1234
+ save_handler.assert_called_with(obj, "{}{}_12.pt".format(filename_prefix, name), metadata)
assert save_handler.remove.call_count == 1
save_handler.remove.assert_called_with("{}{}_1.pt".format(filename_prefix, name))
assert checkpointer.last_checkpoint == "{}{}_12.pt".format(filename_prefix, name)
@@ -162,7 +166,8 @@ def test_checkpoint_with_score_function():
checkpointer(trainer)
assert save_handler.call_count == 1
- save_handler.assert_called_with(obj, "{}_0.7700.pt".format(name))
+ metadata = {"basename": name, "score_name": None, "priority": 0.77}
+ save_handler.assert_called_with(obj, "{}_0.7700.pt".format(name), metadata)
trainer.state.epoch = 12
trainer.state.iteration = 1234
@@ -170,7 +175,8 @@ def test_checkpoint_with_score_function():
checkpointer(trainer)
assert save_handler.call_count == 2
- save_handler.assert_called_with(obj, "{}_0.7800.pt".format(name))
+ metadata["priority"] = 0.78
+ save_handler.assert_called_with(obj, "{}_0.7800.pt".format(name), metadata)
assert save_handler.remove.call_count == 1
save_handler.remove.assert_called_with("{}_0.7700.pt".format(name))
assert checkpointer.last_checkpoint == "{}_0.7800.pt".format(name)
@@ -199,7 +205,8 @@ def test_checkpoint_with_score_name_and_function():
checkpointer(trainer)
assert save_handler.call_count == 1
- save_handler.assert_called_with(obj, "{}_loss=-0.7700.pt".format(name))
+ metadata = {"basename": name, "score_name": "loss", "priority": -0.77}
+ save_handler.assert_called_with(obj, "{}_loss=-0.7700.pt".format(name), metadata)
trainer.state.epoch = 12
trainer.state.iteration = 1234
@@ -207,7 +214,8 @@ def test_checkpoint_with_score_name_and_function():
checkpointer(trainer)
assert save_handler.call_count == 2
- save_handler.assert_called_with(obj, "{}_loss=-0.7600.pt".format(name))
+ metadata["priority"] = -0.76
+ save_handler.assert_called_with(obj, "{}_loss=-0.7600.pt".format(name), metadata)
assert save_handler.remove.call_count == 1
save_handler.remove.assert_called_with("{}_loss=-0.7700.pt".format(name))
assert checkpointer.last_checkpoint == "{}_loss=-0.7600.pt".format(name)
@@ -241,14 +249,16 @@ def test_checkpoint_with_int_score():
checkpointer(trainer)
assert save_handler.call_count == 1
- save_handler.assert_called_with(obj, "{}_{}1.pt".format(name, score_name))
+ metadata = {"basename": name, "score_name": score_name[:-1] if len(score_name) > 0 else None, "priority": 1}
+ save_handler.assert_called_with(obj, "{}_{}1.pt".format(name, score_name), metadata)
trainer.state.epoch = 12
trainer.state.iteration = 1234
checkpointer(trainer)
assert save_handler.call_count == 2
- save_handler.assert_called_with(obj, "{}_{}12.pt".format(name, score_name))
+ metadata["priority"] = 12
+ save_handler.assert_called_with(obj, "{}_{}12.pt".format(name, score_name), metadata)
assert save_handler.remove.call_count == 1
save_handler.remove.assert_called_with("{}_{}1.pt".format(name, score_name))
assert checkpointer.last_checkpoint == "{}_{}12.pt".format(name, score_name)
@@ -284,14 +294,16 @@ def test_checkpoint_with_score_function_and_trainer_epoch():
checkpointer(evaluator)
assert save_handler.call_count == 1
- save_handler.assert_called_with(obj, "{}_11_0.7700.pt".format(name))
+ metadata = {"basename": name, "score_name": None, "priority": 0.77}
+ save_handler.assert_called_with(obj, "{}_11_0.7700.pt".format(name), metadata)
trainer.state.epoch = 12
evaluator.state.metrics["val_acc"] = 0.78
checkpointer(evaluator)
assert save_handler.call_count == 2
- save_handler.assert_called_with(obj, "{}_12_0.7800.pt".format(name))
+ metadata["priority"] = 0.78
+ save_handler.assert_called_with(obj, "{}_12_0.7800.pt".format(name), metadata)
assert save_handler.remove.call_count == 1
save_handler.remove.assert_called_with("{}_11_0.7700.pt".format(name))
assert checkpointer.last_checkpoint == "{}_12_0.7800.pt".format(name)
@@ -322,14 +334,16 @@ def test_checkpoint_with_score_name_and_function_and_trainer_epoch():
checkpointer(evaluator)
assert save_handler.call_count == 1
- save_handler.assert_called_with(obj, "{}_11_val_acc=0.7700.pt".format(name))
+ metadata = {"basename": name, "score_name": "val_acc", "priority": 0.77}
+ save_handler.assert_called_with(obj, "{}_11_val_acc=0.7700.pt".format(name), metadata)
trainer.state.epoch = 12
evaluator.state.metrics["val_acc"] = 0.78
checkpointer(evaluator)
assert save_handler.call_count == 2
- save_handler.assert_called_with(obj, "{}_12_val_acc=0.7800.pt".format(name))
+ metadata["priority"] = 0.78
+ save_handler.assert_called_with(obj, "{}_12_val_acc=0.7800.pt".format(name), metadata)
assert save_handler.remove.call_count == 1
save_handler.remove.assert_called_with("{}_11_val_acc=0.7700.pt".format(name))
assert checkpointer.last_checkpoint == "{}_12_val_acc=0.7800.pt".format(name)
@@ -379,6 +393,20 @@ def test_checkpoint_last_checkpoint_on_score():
assert checkpointer.last_checkpoint == "{}_val_acc=0.9000.pt".format("model")
+def test_checkpoint_save_handler_callable():
+ def save_handler(c, f):
+ assert f == "model_12.pt"
+
+ to_save = {"model": DummyModel()}
+
+ checkpointer = Checkpoint(to_save, save_handler=save_handler,)
+
+ trainer = Engine(lambda e, b: None)
+
+ trainer.state = State(epoch=1, iteration=12)
+ checkpointer(trainer)
+
+
def test_model_checkpoint_args_validation(dirname):
existing = os.path.join(dirname, "existing_dir")
nonempty = os.path.join(dirname, "nonempty")
|
Add meta-data as optional arg for BaseSaveHandler
## 🚀 Feature
According to https://github.com/pytorch/ignite/issues/1056#issuecomment-632919883
it could be helpful to provide checkpoint metadata to a save handler.
Idea is to have
```python
class BaseSaveHandler(metaclass=ABCMeta):
"""Base class for save handlers"""
@abstractmethod
def __call__(self, checkpoint: Mapping, filename: str, metadata: Mapping =None) -> None:
pass
```
We also need to make sure to update all existing save handlers like `DiskSaver`, `NeptuneSaver` etc.
|
0.0
|
c012166f93e56f8e9538741f5745a5010983ba38
|
[
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_default",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_global_step_transform",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_function",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_name_and_function",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_int_score",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_function_and_trainer_epoch",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_with_score_name_and_function_and_trainer_epoch"
] |
[
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_wrong_input",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_score_function_wrong_output",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_last_checkpoint",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_last_checkpoint_on_score",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_save_handler_callable",
"tests/ignite/handlers/test_checkpoint.py::test_model_checkpoint_args_validation",
"tests/ignite/handlers/test_checkpoint.py::test_model_checkpoint_simple_recovery",
"tests/ignite/handlers/test_checkpoint.py::test_model_checkpoint_simple_recovery_from_existing_non_empty",
"tests/ignite/handlers/test_checkpoint.py::test_disk_saver_atomic",
"tests/ignite/handlers/test_checkpoint.py::test_last_k",
"tests/ignite/handlers/test_checkpoint.py::test_disabled_n_saved",
"tests/ignite/handlers/test_checkpoint.py::test_best_k",
"tests/ignite/handlers/test_checkpoint.py::test_best_k_with_suffix",
"tests/ignite/handlers/test_checkpoint.py::test_removes_each_score_at_most_once",
"tests/ignite/handlers/test_checkpoint.py::test_with_engine",
"tests/ignite/handlers/test_checkpoint.py::test_valid_state_dict_save",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_load_objects",
"tests/ignite/handlers/test_checkpoint.py::test_checkpoint_load_objects_from_saved_file",
"tests/ignite/handlers/test_checkpoint.py::test_load_checkpoint_with_different_num_classes",
"tests/ignite/handlers/test_checkpoint.py::test_disksaver_wrong_input"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-23 00:18:42+00:00
|
bsd-3-clause
| 5,121 |
|
pytorch__ignite-1171
|
diff --git a/ignite/contrib/engines/common.py b/ignite/contrib/engines/common.py
index 76c25e2b..a4833e50 100644
--- a/ignite/contrib/engines/common.py
+++ b/ignite/contrib/engines/common.py
@@ -4,6 +4,7 @@ from collections.abc import Mapping, Sequence
from functools import partial
import torch
+import torch.nn as nn
from torch.utils.data.distributed import DistributedSampler
import ignite.distributed as idist
@@ -40,6 +41,8 @@ def setup_common_training_handlers(
device=None,
stop_on_nan=True,
clear_cuda_cache=True,
+ save_handler=None,
+ **kwargs
):
"""Helper method to setup trainer with common handlers (it also supports distributed configuration):
- :class:`~ignite.handlers.TerminateOnNan`
@@ -57,7 +60,8 @@ def setup_common_training_handlers(
:class:`~ignite.handlers.Checkpoint` instance.
save_every_iters (int, optional): saving interval. By default, `to_save` objects are stored
each 1000 iterations.
- output_path (str, optional): output path to indicate where `to_save` objects are stored.
+ output_path (str, optional): output path to indicate where `to_save` objects are stored. Argument is mutually
+ exclusive with ``save_handler``.
lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): learning rate scheduler
as native torch LRScheduler or ignite's parameter scheduler.
with_gpu_stats (bool, optional): if True, :class:`~ignite.contrib.metrics.handlers.GpuInfo` is attached to the
@@ -73,12 +77,16 @@ def setup_common_training_handlers(
Default, True.
clear_cuda_cache (bool, optional): if True, `torch.cuda.empty_cache()` is called every end of epoch.
Default, True.
+ save_handler (callable or :class:`~ignite.handlers.checkpoint.BaseSaveHandler`, optional): Method or callable
+ class to use to store ``to_save``. See :class:`~ignite.handlers.checkpoint.Checkpoint` for more details.
+ Argument is mutually exclusive with ``output_path``.
+ **kwargs: optional keyword args to be passed to construct :class:`~ignite.handlers.checkpoint.Checkpoint`.
device (str of torch.device, optional): deprecated argument, it will be removed in v0.5.0.
"""
if device is not None:
warnings.warn("Argument device is unused and deprecated. It will be removed in v0.5.0")
- kwargs = dict(
+ _kwargs = dict(
to_save=to_save,
save_every_iters=save_every_iters,
output_path=output_path,
@@ -90,10 +98,12 @@ def setup_common_training_handlers(
log_every_iters=log_every_iters,
stop_on_nan=stop_on_nan,
clear_cuda_cache=clear_cuda_cache,
+ save_handler=save_handler,
)
+ _kwargs.update(kwargs)
if idist.get_world_size() > 1:
- _setup_common_distrib_training_handlers(trainer, train_sampler=train_sampler, **kwargs)
+ _setup_common_distrib_training_handlers(trainer, train_sampler=train_sampler, **_kwargs)
else:
if train_sampler is not None and isinstance(train_sampler, DistributedSampler):
warnings.warn(
@@ -102,7 +112,7 @@ def setup_common_training_handlers(
"Train sampler argument will be ignored",
UserWarning,
)
- _setup_common_training_handlers(trainer, **kwargs)
+ _setup_common_training_handlers(trainer, **_kwargs)
setup_common_distrib_training_handlers = setup_common_training_handlers
@@ -121,7 +131,14 @@ def _setup_common_training_handlers(
log_every_iters=100,
stop_on_nan=True,
clear_cuda_cache=True,
+ save_handler=None,
+ **kwargs
):
+ if output_path is not None and save_handler is not None:
+ raise ValueError(
+ "Arguments output_path and save_handler are mutually exclusive. Please, define only one of them"
+ )
+
if stop_on_nan:
trainer.add_event_handler(Events.ITERATION_COMPLETED, TerminateOnNan())
@@ -137,11 +154,15 @@ def _setup_common_training_handlers(
trainer.add_event_handler(Events.EPOCH_COMPLETED, empty_cuda_cache)
if to_save is not None:
- if output_path is None:
- raise ValueError("If to_save argument is provided then output_path argument should be also defined")
- checkpoint_handler = Checkpoint(
- to_save, DiskSaver(dirname=output_path, require_empty=False), filename_prefix="training",
- )
+
+ if output_path is None and save_handler is None:
+ raise ValueError(
+ "If to_save argument is provided then output_path or save_handler arguments should be also defined"
+ )
+ if output_path is not None:
+ save_handler = DiskSaver(dirname=output_path, require_empty=False)
+
+ checkpoint_handler = Checkpoint(to_save, save_handler, filename_prefix="training", **kwargs)
trainer.add_event_handler(Events.ITERATION_COMPLETED(every=save_every_iters), checkpoint_handler)
if with_gpu_stats:
@@ -192,6 +213,8 @@ def _setup_common_distrib_training_handlers(
log_every_iters=100,
stop_on_nan=True,
clear_cuda_cache=True,
+ save_handler=None,
+ **kwargs
):
_setup_common_training_handlers(
@@ -207,6 +230,8 @@ def _setup_common_distrib_training_handlers(
log_every_iters=log_every_iters,
stop_on_nan=stop_on_nan,
clear_cuda_cache=clear_cuda_cache,
+ save_handler=save_handler,
+ **kwargs,
)
if train_sampler is not None:
@@ -450,19 +475,29 @@ def get_default_score_fn(metric_name):
return wrapper
-def save_best_model_by_val_score(output_path, evaluator, model, metric_name, n_saved=3, trainer=None, tag="val"):
- """Method adds a handler to `evaluator` to save best models based on the score (named by `metric_name`)
- provided by `evaluator`.
+def gen_save_best_models_by_val_score(
+ save_handler, evaluator, models, metric_name, n_saved=3, trainer=None, tag="val", **kwargs
+):
+ """Method adds a handler to ``evaluator`` to save ``n_saved`` of best models based on the metric
+ (named by ``metric_name``) provided by ``evaluator`` (i.e. ``evaluator.state.metrics[metric_name]``).
+ The logic of how to store objects is delegated to ``save_handler``.
Args:
- output_path (str): output path to indicate where to save best models
+ save_handler (callable or :class:`~ignite.handlers.checkpoint.BaseSaveHandler`): Method or callable class to
+ use to save engine and other provided objects. Function receives two objects: checkpoint as a dictionary
+ and filename. If ``save_handler`` is callable class, it can
+ inherit of :class:`~ignite.handlers.checkpoint.BaseSaveHandler` and optionally implement ``remove`` method
+ to keep a fixed number of saved checkpoints. In case if user needs to save engine's checkpoint on a disk,
+ ``save_handler`` can be defined with :class:`~ignite.handlers.DiskSaver`.
evaluator (Engine): evaluation engine used to provide the score
- model (nn.Module): model to store
+ models (nn.Module or Mapping): model or dictionary with the object to save. Objects should have
+ implemented ``state_dict`` and ``load_state_dict`` methods.
metric_name (str): metric name to use for score evaluation. This metric should be present in
`evaluator.state.metrics`.
n_saved (int, optional): number of best models to store
trainer (Engine, optional): trainer engine to fetch the epoch when saving the best model.
tag (str, optional): score name prefix: `{tag}_{metric_name}`. By default, tag is "val".
+ **kwargs: optional keyword args to be passed to construct :class:`~ignite.handlers.checkpoint.Checkpoint`.
Returns:
A :class:`~ignite.handlers.checkpoint.Checkpoint` handler.
@@ -471,14 +506,19 @@ def save_best_model_by_val_score(output_path, evaluator, model, metric_name, n_s
if trainer is not None:
global_step_transform = global_step_from_engine(trainer)
+ to_save = models
+ if isinstance(models, nn.Module):
+ to_save = {"model": models}
+
best_model_handler = Checkpoint(
- {"model": model,},
- DiskSaver(dirname=output_path, require_empty=False),
+ to_save,
+ save_handler,
filename_prefix="best",
n_saved=n_saved,
global_step_transform=global_step_transform,
score_name="{}_{}".format(tag, metric_name.lower()),
score_function=get_default_score_fn(metric_name),
+ **kwargs,
)
evaluator.add_event_handler(
Events.COMPLETED, best_model_handler,
@@ -487,6 +527,38 @@ def save_best_model_by_val_score(output_path, evaluator, model, metric_name, n_s
return best_model_handler
+def save_best_model_by_val_score(
+ output_path, evaluator, model, metric_name, n_saved=3, trainer=None, tag="val", **kwargs
+):
+ """Method adds a handler to ``evaluator`` to save on a disk ``n_saved`` of best models based on the metric
+ (named by ``metric_name``) provided by ``evaluator`` (i.e. ``evaluator.state.metrics[metric_name]``).
+
+ Args:
+ output_path (str): output path to indicate where to save best models
+ evaluator (Engine): evaluation engine used to provide the score
+ model (nn.Module): model to store
+ metric_name (str): metric name to use for score evaluation. This metric should be present in
+ `evaluator.state.metrics`.
+ n_saved (int, optional): number of best models to store
+ trainer (Engine, optional): trainer engine to fetch the epoch when saving the best model.
+ tag (str, optional): score name prefix: `{tag}_{metric_name}`. By default, tag is "val".
+ **kwargs: optional keyword args to be passed to construct :class:`~ignite.handlers.checkpoint.Checkpoint`.
+
+ Returns:
+ A :class:`~ignite.handlers.checkpoint.Checkpoint` handler.
+ """
+ return gen_save_best_models_by_val_score(
+ save_handler=DiskSaver(dirname=output_path, require_empty=False),
+ evaluator=evaluator,
+ models=model,
+ metric_name=metric_name,
+ n_saved=n_saved,
+ trainer=trainer,
+ tag=tag,
+ **kwargs,
+ )
+
+
def add_early_stopping_by_val_score(patience, evaluator, trainer, metric_name):
"""Method setups early stopping handler based on the score (named by `metric_name`) provided by `evaluator`.
|
pytorch/ignite
|
4b59484170d4af1d66f891e6f78e312f0276708c
|
diff --git a/tests/ignite/contrib/engines/test_common.py b/tests/ignite/contrib/engines/test_common.py
index 2b17af87..8d9a8ee7 100644
--- a/tests/ignite/contrib/engines/test_common.py
+++ b/tests/ignite/contrib/engines/test_common.py
@@ -1,6 +1,6 @@
import os
import sys
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, call
import pytest
import torch
@@ -12,6 +12,7 @@ import ignite.distributed as idist
from ignite.contrib.engines.common import (
_setup_logging,
add_early_stopping_by_val_score,
+ gen_save_best_models_by_val_score,
save_best_model_by_val_score,
setup_any_logging,
setup_common_training_handlers,
@@ -24,7 +25,7 @@ from ignite.contrib.engines.common import (
setup_wandb_logging,
)
from ignite.engine import Engine, Events
-from ignite.handlers import TerminateOnNan
+from ignite.handlers import DiskSaver, TerminateOnNan
class DummyModel(nn.Module):
@@ -36,7 +37,9 @@ class DummyModel(nn.Module):
return self.net(x)
-def _test_setup_common_training_handlers(dirname, device, rank=0, local_rank=0, distributed=False, lr_scheduler=None):
+def _test_setup_common_training_handlers(
+ dirname, device, rank=0, local_rank=0, distributed=False, lr_scheduler=None, save_handler=None
+):
lr = 0.01
step_size = 100
@@ -86,6 +89,7 @@ def _test_setup_common_training_handlers(dirname, device, rank=0, local_rank=0,
to_save={"model": model, "optimizer": optimizer},
save_every_iters=75,
output_path=dirname,
+ save_handler=save_handler,
lr_scheduler=lr_scheduler,
with_gpu_stats=False,
output_names=["batch_loss",],
@@ -107,6 +111,8 @@ def _test_setup_common_training_handlers(dirname, device, rank=0, local_rank=0,
# Check saved checkpoint
if rank == 0:
+ if save_handler is not None:
+ dirname = save_handler.dirname
checkpoints = list(os.listdir(dirname))
assert len(checkpoints) == 1
for v in [
@@ -124,10 +130,14 @@ def test_asserts_setup_common_training_handlers():
trainer = Engine(lambda e, b: None)
with pytest.raises(
- ValueError, match=r"If to_save argument is provided then output_path argument should be also defined"
+ ValueError,
+ match=r"If to_save argument is provided then output_path or save_handler arguments should be also defined",
):
setup_common_training_handlers(trainer, to_save={})
+ with pytest.raises(ValueError, match=r"Arguments output_path and save_handler are mutually exclusive"):
+ setup_common_training_handlers(trainer, to_save={}, output_path="abc", save_handler=lambda c, f, m: None)
+
with pytest.warns(UserWarning, match=r"Argument train_sampler is a distributed sampler"):
train_sampler = MagicMock(spec=DistributedSampler)
setup_common_training_handlers(trainer, train_sampler=train_sampler)
@@ -167,10 +177,23 @@ def test_setup_common_training_handlers(dirname, capsys):
out = captured.err.split("\r")
out = list(map(lambda x: x.strip(), out))
out = list(filter(None, out))
- assert "Epoch:" in out[-1], "{}".format(out[-1])
+ assert "Epoch" in out[-1] or "Epoch" in out[-2], "{}, {}".format(out[-2], out[-1])
+
+
+def test_setup_common_training_handlers_using_save_handler(dirname, capsys):
+
+ save_handler = DiskSaver(dirname=dirname, require_empty=False)
+ _test_setup_common_training_handlers(dirname=None, device="cpu", save_handler=save_handler)
+
+ # Check epoch-wise pbar
+ captured = capsys.readouterr()
+ out = captured.err.split("\r")
+ out = list(map(lambda x: x.strip(), out))
+ out = list(filter(None, out))
+ assert "Epoch" in out[-1] or "Epoch" in out[-2], "{}, {}".format(out[-2], out[-1])
-def test_save_best_model_by_val_score(dirname, capsys):
+def test_save_best_model_by_val_score(dirname):
trainer = Engine(lambda e, b: None)
evaluator = Engine(lambda e, b: None)
@@ -180,9 +203,7 @@ def test_save_best_model_by_val_score(dirname, capsys):
@trainer.on(Events.EPOCH_COMPLETED)
def validate(engine):
- evaluator.run(
- [0,]
- )
+ evaluator.run([0, 1])
@evaluator.on(Events.EPOCH_COMPLETED)
def set_eval_metric(engine):
@@ -190,12 +211,49 @@ def test_save_best_model_by_val_score(dirname, capsys):
save_best_model_by_val_score(dirname, evaluator, model, metric_name="acc", n_saved=2, trainer=trainer)
- data = [
- 0,
- ]
- trainer.run(data, max_epochs=len(acc_scores))
+ trainer.run([0, 1], max_epochs=len(acc_scores))
- assert set(os.listdir(dirname)) == set(["best_model_8_val_acc=0.6100.pt", "best_model_9_val_acc=0.7000.pt"])
+ assert set(os.listdir(dirname)) == {"best_model_8_val_acc=0.6100.pt", "best_model_9_val_acc=0.7000.pt"}
+
+
+def test_gen_save_best_models_by_val_score():
+
+ trainer = Engine(lambda e, b: None)
+ evaluator = Engine(lambda e, b: None)
+ model = DummyModel()
+
+ acc_scores = [0.1, 0.2, 0.3, 0.4, 0.3, 0.5, 0.6, 0.61, 0.7, 0.5]
+
+ @trainer.on(Events.EPOCH_COMPLETED)
+ def validate(engine):
+ evaluator.run([0, 1])
+
+ @evaluator.on(Events.EPOCH_COMPLETED)
+ def set_eval_metric(engine):
+ engine.state.metrics = {"acc": acc_scores[trainer.state.epoch - 1]}
+
+ save_handler = MagicMock()
+
+ gen_save_best_models_by_val_score(
+ save_handler, evaluator, {"a": model, "b": model}, metric_name="acc", n_saved=2, trainer=trainer
+ )
+
+ trainer.run([0, 1], max_epochs=len(acc_scores))
+
+ assert save_handler.call_count == len(acc_scores) - 2 # 2 score values (0.3 and 0.5) are not the best
+ print(save_handler.mock_calls)
+ obj_to_save = {"a": model.state_dict(), "b": model.state_dict()}
+ save_handler.assert_has_calls(
+ [
+ call(
+ obj_to_save,
+ "best_checkpoint_{}_val_acc={:.4f}.pt".format(e, p),
+ dict([("basename", "best_checkpoint"), ("score_name", "val_acc"), ("priority", p)]),
+ )
+ for e, p in zip([1, 2, 3, 4, 6, 7, 8, 9], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.61, 0.7])
+ ],
+ any_order=True,
+ )
def test_add_early_stopping_by_val_score():
@@ -206,9 +264,7 @@ def test_add_early_stopping_by_val_score():
@trainer.on(Events.EPOCH_COMPLETED)
def validate(engine):
- evaluator.run(
- [0,]
- )
+ evaluator.run([0, 1])
@evaluator.on(Events.EPOCH_COMPLETED)
def set_eval_metric(engine):
@@ -216,10 +272,7 @@ def test_add_early_stopping_by_val_score():
add_early_stopping_by_val_score(patience=3, evaluator=evaluator, trainer=trainer, metric_name="acc")
- data = [
- 0,
- ]
- state = trainer.run(data, max_epochs=len(acc_scores))
+ state = trainer.run([0, 1], max_epochs=len(acc_scores))
assert state.epoch == 7
@@ -259,9 +312,7 @@ def _test_setup_logging(
@trainer.on(Events.EPOCH_COMPLETED)
def validate(engine):
- evaluator.run(
- [0,]
- )
+ evaluator.run([0, 1])
@evaluator.on(Events.EPOCH_COMPLETED)
def set_eval_metric(engine):
|
Improve usage of contrib common methods with other save handlers
## 🚀 Feature
Currently, methods like `common.save_best_model_by_val_score` and `common.setup_common_training_handlers` work with local storage setup by `output_path`.
If we would like to use other save handlers than `DiskSaver`, it is almost impossible to use those helpers.
Idea is to be able user's setup of save handler for internal `Checkpoint` class.
There can be several ways, I see, how to accomplish that:
- make `output_path` accept instances of `BaseSaveHandler`
```python
from ignite.contrib.engines import common
save_handler = TrainsSaver(dirname=output_path)
common.save_best_model_by_val_score(
save_handler, evaluator, model=model, metric_name="accuracy", n_saved=3, trainer=trainer, tag="test"
)
```
- set module-wise default save handler as DiskSaver and allow user to replace it by another save hander:
```python
from ignite.contrib.engines import common
common.default_save_handler = TrainsSaver(dirname=output_path)
common.save_best_model_by_val_score(
None, evaluator, model=model, metric_name="accuracy", n_saved=3, trainer=trainer, tag="test"
)
```
- add another argument `save_handler=None`
```python
save_handler = TrainsSaver(dirname=output_path)
common.save_best_model_by_val_score(
None, evaluator, model=model, metric_name="accuracy", n_saved=3, trainer=trainer, tag="test", save_handler=save_handler
)
```
Any other ideas @sdesrozis @erip ?
|
0.0
|
4b59484170d4af1d66f891e6f78e312f0276708c
|
[
"tests/ignite/contrib/engines/test_common.py::test_save_best_model_by_val_score",
"tests/ignite/contrib/engines/test_common.py::test_gen_save_best_models_by_val_score",
"tests/ignite/contrib/engines/test_common.py::test_add_early_stopping_by_val_score",
"tests/ignite/contrib/engines/test_common.py::test_deprecated_setup_any_logging",
"tests/ignite/contrib/engines/test_common.py::test__setup_logging_wrong_args",
"tests/ignite/contrib/engines/test_common.py::test_setup_wandb_logging"
] |
[] |
{
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-07-01 15:03:59+00:00
|
bsd-3-clause
| 5,122 |
|
pytorch__ignite-1265
|
diff --git a/ignite/distributed/auto.py b/ignite/distributed/auto.py
index 6d617fdd..49ae70ca 100644
--- a/ignite/distributed/auto.py
+++ b/ignite/distributed/auto.py
@@ -24,7 +24,7 @@ def auto_dataloader(dataset, **kwargs):
- batch size is scaled by world size: ``batch_size / world_size`` if larger or equal world size.
- number of workers is scaled by number of local processes: ``num_workers / nprocs`` if larger or equal world size.
- - if no sampler provided by user, `torch DistributedSampler` is setup.
+ - if no sampler provided by user, `torch DistributedSampler`_ is setup.
- if a sampler is provided by user, it is wrapped by :class:`~ignite.distributed.auto.DistributedProxySampler`.
- if the default device is 'cuda', `pin_memory` is automatically set to `True`.
@@ -122,7 +122,7 @@ def auto_dataloader(dataset, **kwargs):
return dataloader
-def auto_model(model: nn.Module) -> nn.Module:
+def auto_model(model: nn.Module, sync_bn: bool = False) -> nn.Module:
"""Helper method to adapt provided model for non-distributed and distributed configurations (supporting
all available backends from :meth:`~ignite.distributed.utils.available_backends()`).
@@ -152,12 +152,19 @@ def auto_model(model: nn.Module) -> nn.Module:
Args:
model (torch.nn.Module): model to adapt.
+ sync_bn (bool): if True, applies `torch convert_sync_batchnorm`_ to the model for native torch
+ distributed only. Default, False. Note, if using Nvidia/Apex, batchnorm conversion should be
+ applied before calling ``amp.initialize``.
Returns:
torch.nn.Module
- .. _torch DistributedDataParallel: https://pytorch.org/docs/stable/nn.html#torch.nn.parallel.DistributedDataParallel
- .. _torch DataParallel: https://pytorch.org/docs/stable/nn.html#torch.nn.DataParallel
+ .. _torch DistributedDataParallel: https://pytorch.org/docs/stable/generated/torch.nn.parallel.
+ DistributedDataParallel.html
+ .. _torch DataParallel: https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html
+ .. _torch convert_sync_batchnorm: https://pytorch.org/docs/stable/generated/torch.nn.SyncBatchNorm.html#
+ torch.nn.SyncBatchNorm.convert_sync_batchnorm
+
"""
logger = setup_logger(__name__ + ".auto_model")
@@ -170,10 +177,18 @@ def auto_model(model: nn.Module) -> nn.Module:
if idist.get_world_size() > 1:
bnd = idist.backend()
if idist.has_native_dist_support and bnd == idist_native.NCCL:
+ if sync_bn:
+ logger.info("Convert batch norm to sync batch norm")
+ model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
+
lrank = idist.get_local_rank()
logger.info("Apply torch DistributedDataParallel on model, device id: {}".format(lrank))
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[lrank,])
elif idist.has_native_dist_support and bnd == idist_native.GLOO:
+ if sync_bn:
+ logger.info("Convert batch norm to sync batch norm")
+ model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
+
logger.info("Apply torch DistributedDataParallel on model")
model = torch.nn.parallel.DistributedDataParallel(model)
elif idist.has_hvd_support and bnd == idist_hvd.HOROVOD:
|
pytorch/ignite
|
789958afe49c5b7a9c8e6d51d5522db541e4000e
|
diff --git a/tests/ignite/distributed/test_auto.py b/tests/ignite/distributed/test_auto.py
index 9635572f..2caf05c1 100644
--- a/tests/ignite/distributed/test_auto.py
+++ b/tests/ignite/distributed/test_auto.py
@@ -51,14 +51,14 @@ def _test_auto_dataloader(ws, nproc, batch_size, num_workers=1, sampler_name=Non
assert dataloader.pin_memory == ("cuda" in idist.device().type)
-def _test_auto_model_optimizer(ws, device):
- # Test auto_model
- model = nn.Linear(10, 10)
- model = auto_model(model)
+def _test_auto_model(model, ws, device, sync_bn=False):
+ model = auto_model(model, sync_bn=sync_bn)
bnd = idist.backend()
if ws > 1 and device in ("cuda", "cpu"):
if idist.has_native_dist_support and bnd in ("nccl" or "gloo"):
assert isinstance(model, nn.parallel.DistributedDataParallel)
+ if sync_bn:
+ assert any([isinstance(m, nn.SyncBatchNorm) for m in model.modules()])
elif idist.has_hvd_support and bnd in ("horovod",):
assert isinstance(model, nn.Module)
elif device != "cpu" and torch.cuda.is_available() and torch.cuda.device_count() > 1:
@@ -70,7 +70,17 @@ def _test_auto_model_optimizer(ws, device):
[p.device.type for p in model.parameters()], device
)
+
+def _test_auto_model_optimizer(ws, device):
+ # Test auto_model
+ model = nn.Linear(10, 10)
+ _test_auto_model(model, ws, device)
+
+ model = nn.Sequential(nn.Linear(20, 100), nn.BatchNorm1d(100))
+ _test_auto_model(model, ws, device, sync_bn="cuda" in device)
+
# Test auto_optim
+ bnd = idist.backend()
optimizer = optim.SGD(model.parameters(), lr=0.01)
optimizer = auto_optim(optimizer)
if idist.has_xla_support and "xla" in device:
|
Add option to replace bn by sync bn in auto_model
## 🚀 Feature
Idea is to add an option `sync_bn` (default, False) to apply [`convert_sync_batchnorm`](https://pytorch.org/docs/master/generated/torch.nn.SyncBatchNorm.html#torch.nn.SyncBatchNorm.convert_sync_batchnorm) on the input model if a DDP wrapper is used further.
- Check performances on PascalVOC
- Update ref examples
|
0.0
|
789958afe49c5b7a9c8e6d51d5522db541e4000e
|
[
"tests/ignite/distributed/test_auto.py::test_auto_methods_gloo",
"tests/ignite/distributed/test_auto.py::test_auto_methods_nccl"
] |
[
"tests/ignite/distributed/test_auto.py::test_dist_proxy_sampler"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-04 23:36:27+00:00
|
bsd-3-clause
| 5,123 |
|
pyupio__changelogs-232
|
diff --git a/changelogs/finder.py b/changelogs/finder.py
index c34bbd2..8bba1e5 100644
--- a/changelogs/finder.py
+++ b/changelogs/finder.py
@@ -68,7 +68,8 @@ def find_repo_urls(session, name, candidates):
:return: str, URL to a repo
"""
for _url in candidates:
- if validate_url(_url):
+ _url = validate_url(_url)
+ if _url:
try:
resp = session.get(_url)
if resp.status_code == 200:
|
pyupio/changelogs
|
734763fa320d5fbf71016f74f188c5a51e60c45f
|
diff --git a/tests/test_finder.py b/tests/test_finder.py
index a127632..0631ad4 100644
--- a/tests/test_finder.py
+++ b/tests/test_finder.py
@@ -1,4 +1,6 @@
-from changelogs.finder import contains_project_name
+from unittest.mock import Mock
+
+from changelogs.finder import contains_project_name, find_repo_urls
def test_contains_project_name():
@@ -19,5 +21,19 @@ def test_not_contains_project_name():
assert not call('dj-dashboard', 'https://github.com/pydanny/cookiecutter-djangopackage')
-def test_find_repo_urls():
- pass
+def test_find_repo_urls_invalid_candidate():
+ session = Mock()
+ list(find_repo_urls(session, 'foobar', ['invalid-link']))
+ assert not session.get.called
+
+
+def test_find_repo_urls_valid_candidate():
+ session = Mock()
+ list(find_repo_urls(session, 'foobar', ['http://example.com/link']))
+ session.get.assert_called_with('http://example.com/link')
+
+
+def test_find_repo_urls_domain_candidate():
+ session = Mock()
+ list(find_repo_urls(session, 'foobar', ['example.com']))
+ session.get.assert_called_with('http://example.com')
|
Url validation ignored
```In [12]: changelogs.get('1')
---------------------------------------------------------------------------
MissingSchema Traceback (most recent call last)
<ipython-input-12-47f2b1bcf4e3> in <module>
----> 1 changelogs.get('1')
~/src/cve-search/env/lib/python3.6/site-packages/changelogs/changelogs.py in get(name, vendor, functions, _depth)
166 data=data,
167 releases=releases,
--> 168 find_changelogs_fn=fns["find_changelogs"]
169 )
170
~/src/cve-search/env/lib/python3.6/site-packages/changelogs/pypi.py in get_urls(session, name, data, find_changelogs_fn, **kwargs)
91 if data['info']['description']:
92 candidates.extend(changelogs.url_re.findall(data["info"]["description"]))
---> 93 return find_changelogs_fn(session=session, name=name, candidates=candidates)
94 return set(), set()
~/src/cve-search/env/lib/python3.6/site-packages/changelogs/finder.py in find_changelogs(session, name, candidates)
217 if not repos:
218 logger.info("No repo found, trying to find one on related sites {}".format(candidates))
--> 219 repos = set(find_repo_urls(session, name, candidates))
220
221 urls = []
~/src/cve-search/env/lib/python3.6/site-packages/changelogs/finder.py in find_repo_urls(session, name, candidates)
71 if validate_url(_url):
72 try:
---> 73 resp = session.get(_url)
74 if resp.status_code == 200:
75 tree = etree.HTML(resp.content)
~/src/cve-search/env/lib/python3.6/site-packages/requests/sessions.py in get(self, url, **kwargs)
523
524 kwargs.setdefault('allow_redirects', True)
--> 525 return self.request('GET', url, **kwargs)
526
527 def options(self, url, **kwargs):
~/src/cve-search/env/lib/python3.6/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
496 hooks=hooks,
497 )
--> 498 prep = self.prepare_request(req)
499
500 proxies = proxies or {}
~/src/cve-search/env/lib/python3.6/site-packages/requests/sessions.py in prepare_request(self, request)
439 auth=merge_setting(auth, self.auth),
440 cookies=merged_cookies,
--> 441 hooks=merge_hooks(request.hooks, self.hooks),
442 )
443 return p
~/src/cve-search/env/lib/python3.6/site-packages/requests/models.py in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json)
307
308 self.prepare_method(method)
--> 309 self.prepare_url(url, params)
310 self.prepare_headers(headers)
311 self.prepare_cookies(cookies)
~/src/cve-search/env/lib/python3.6/site-packages/requests/models.py in prepare_url(self, url, params)
381 error = error.format(to_native_string(url, 'utf8'))
382
--> 383 raise MissingSchema(error)
384
385 if not host:
MissingSchema: Invalid URL 'gxc.online': No schema supplied. Perhaps you meant http://gxc.online?
```
Basically, [this line](https://github.com/pyupio/changelogs/blob/0cdb929ac4546c766cd7eef9ae4eb4baaa08f452/changelogs/finder.py#L71) should be like this:
```
_url = validate_url(_url)
if _url:
```
I'm gonna send a PR soon unless you fix it before that.
|
0.0
|
734763fa320d5fbf71016f74f188c5a51e60c45f
|
[
"tests/test_finder.py::test_find_repo_urls_domain_candidate"
] |
[
"tests/test_finder.py::test_contains_project_name",
"tests/test_finder.py::test_not_contains_project_name",
"tests/test_finder.py::test_find_repo_urls_invalid_candidate",
"tests/test_finder.py::test_find_repo_urls_valid_candidate"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-04 15:29:02+00:00
|
mit
| 5,124 |
|
pyupio__safety-151
|
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..57f3ee6
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,3 @@
+FROM python:3.6-slim
+RUN pip install --trusted-host pypi.python.org safety
+CMD ["python"]
diff --git a/README.md b/README.md
index ae903dc..4cecdb6 100644
--- a/README.md
+++ b/README.md
@@ -110,6 +110,19 @@ echo "insecure-package==0.1" | safety check --stdin
*For more examples, take a look at the [options](#options) section.*
+## Using Safety in Docker
+
+Safety can be easily executed as Docker container. To build the container just execute:
+```
+docker build -t safety-docker .
+```
+
+The container can be used just as described in the [examples](#examples) section.
+```
+echo "insecure-package==0.1" | docker run -i --rm safety-docker safety check --stdin
+cat requirements_dev.txt | docker run -i --rm safety-docker safety check --stdin
+```
+
## Using Safety with a CI service
Safety works great in your CI pipeline. It returns a non-zero exit status if it finds a vulnerability.
@@ -139,7 +152,7 @@ and displays a status on GitHub.
Safety is free and open source (MIT Licensed). The underlying open vulnerability database is updated once per month.
-To get access to all vulnerabilites as soon as they are added, you need a [Safety API key](https://github.com/pyupio/safety/blob/master/docs/api_key.md) that comes with a paid [pyup.io](https://pyup.io) account, starting at $14.99 for individuals, or $49.99 for organizations.
+To get access to all vulnerabilites as soon as they are added, you need a [Safety API key](https://github.com/pyupio/safety/blob/master/docs/api_key.md) that comes with a paid [pyup.io](https://pyup.io) account, starting at $99 for organizations.
## Options
diff --git a/requirements_dev.txt b/requirements_dev.txt
index b8fb533..a634ab3 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -1,9 +1,8 @@
pip==9.0.3
-wheel==0.29.0
-watchdog==0.8.3
+wheel==0.32.3
+watchdog==0.9.0
flake8==3.3.0
-coverage==4.4
-cryptography==2.3
-Sphinx==1.5.5
-PyYAML==3.12
-
+PyYAML==3.13
+cryptography==2.4.2
+coverage==4.5.2
+Sphinx==1.8.3
\ No newline at end of file
diff --git a/safety/cli.py b/safety/cli.py
index 37ae3ac..2991ff3 100644
--- a/safety/cli.py
+++ b/safety/cli.py
@@ -10,14 +10,6 @@ from safety.util import read_requirements
from safety.errors import DatabaseFetchError, DatabaseFileNotFoundError, InvalidKeyError
-try:
- # pip 9
- from pip import get_installed_distributions
-except ImportError:
- # pip 10
- from pip._internal.utils.misc import get_installed_distributions
-
-
@click.group()
@click.version_option(version=__version__)
def cli():
@@ -57,20 +49,25 @@ def check(key, db, json, full_report, bare, stdin, files, cache, ignore):
elif stdin:
packages = list(read_requirements(sys.stdin))
else:
- packages = get_installed_distributions()
+ import pkg_resources
+ packages = [
+ d for d in pkg_resources.working_set
+ if d.key not in {"python", "wsgiref", "argparse"}
+ ]
try:
vulns = safety.check(packages=packages, key=key, db_mirror=db, cached=cache, ignore_ids=ignore)
click.secho(report(
- vulns=vulns,
- full=full_report,
- json_report=json,
- bare_report=bare,
- checked_packages=len(packages),
- db=db,
- key=key
+ vulns=vulns,
+ full=full_report,
+ json_report=json,
+ bare_report=bare,
+ checked_packages=len(packages),
+ db=db,
+ key=key
+ ),
+ nl=False if bare and not vulns else True
)
- )
sys.exit(-1 if vulns else 0)
except InvalidKeyError:
click.secho("Your API Key '{key}' is invalid. See {link}".format(
diff --git a/safety/formatter.py b/safety/formatter.py
index 8bc57ec..c19bff1 100644
--- a/safety/formatter.py
+++ b/safety/formatter.py
@@ -3,6 +3,7 @@ import platform
import sys
import json
import os
+import textwrap
# python 2.7 compat
try:
@@ -110,9 +111,10 @@ class SheetReport(object):
descr = get_advisory(vuln)
- for chunk in [descr[i:i + 76] for i in range(0, len(descr), 76)]:
-
- for line in chunk.splitlines():
+ for pn, paragraph in enumerate(descr.replace('\r', '').split('\n\n')):
+ if pn:
+ table.append("│ {:76} │".format(''))
+ for line in textwrap.wrap(paragraph, width=76):
try:
table.append("│ {:76} │".format(line.encode('utf-8')))
except TypeError:
diff --git a/setup.py b/setup.py
index f1b7a1d..a3c50b7 100644
--- a/setup.py
+++ b/setup.py
@@ -18,7 +18,7 @@ except TypeError:
history = history_file.read()
requirements = [
- 'pip',
+ 'setuptools',
'Click>=6.0',
'requests',
'packaging',
|
pyupio/safety
|
7e4e40e5d0e1e8cb59ca9c23379ca6c62c63a37b
|
diff --git a/tests/test_safety.py b/tests/test_safety.py
index 0777254..c67f568 100644
--- a/tests/test_safety.py
+++ b/tests/test_safety.py
@@ -9,9 +9,8 @@ Tests for `safety` module.
"""
-import sys
import unittest
-from contextlib import contextmanager
+import textwrap
from click.testing import CliRunner
from safety import safety
@@ -40,6 +39,8 @@ class TestSafetyCLI(unittest.TestCase):
class TestFormatter(unittest.TestCase):
+ maxDiff = None
+
def test_get_terminal_size(self):
try:
formatter.get_terminal_size()
@@ -56,6 +57,50 @@ class TestFormatter(unittest.TestCase):
assert 'pyup.io\'s DB' == formatter.get_used_db(key='foo', db='')
assert 'local DB' == formatter.get_used_db(key=None, db='/usr/local/some-db')
+ def test_full_report(self):
+ vulns = [
+ safety.Vulnerability(
+ name='libfoo',
+ spec='<2.0.0',
+ version='1.9.3',
+ advisory='libfoo prior to version 2.0.0 had a vulnerability'
+ + ' blah' * 15 + '.\r\n\r\n'
+ + 'All users are urged to upgrade please.\r\n',
+ vuln_id=1234,
+ ),
+ ]
+ full_report = formatter.SheetReport.render(
+ vulns, full=True, checked_packages=5, used_db='test DB')
+ self.assertMultiLineEqual(full_report + "\n", textwrap.dedent(r"""
+ ╒══════════════════════════════════════════════════════════════════════════════╕
+ │ │
+ │ /$$$$$$ /$$ │
+ │ /$$__ $$ | $$ │
+ │ /$$$$$$$ /$$$$$$ | $$ \__//$$$$$$ /$$$$$$ /$$ /$$ │
+ │ /$$_____/ |____ $$| $$$$ /$$__ $$|_ $$_/ | $$ | $$ │
+ │ | $$$$$$ /$$$$$$$| $$_/ | $$$$$$$$ | $$ | $$ | $$ │
+ │ \____ $$ /$$__ $$| $$ | $$_____/ | $$ /$$| $$ | $$ │
+ │ /$$$$$$$/| $$$$$$$| $$ | $$$$$$$ | $$$$/| $$$$$$$ │
+ │ |_______/ \_______/|__/ \_______/ \___/ \____ $$ │
+ │ /$$ | $$ │
+ │ | $$$$$$/ │
+ │ by pyup.io \______/ │
+ │ │
+ ╞══════════════════════════════════════════════════════════════════════════════╡
+ │ REPORT │
+ │ checked 5 packages, using test DB │
+ ╞════════════════════════════╤═══════════╤══════════════════════════╤══════════╡
+ │ package │ installed │ affected │ ID │
+ ╞════════════════════════════╧═══════════╧══════════════════════════╧══════════╡
+ │ libfoo │ 1.9.3 │ <2.0.0 │ 1234 │
+ ╞══════════════════════════════════════════════════════════════════════════════╡
+ │ libfoo prior to version 2.0.0 had a vulnerability blah blah blah blah blah │
+ │ blah blah blah blah blah blah blah blah blah blah. │
+ │ │
+ │ All users are urged to upgrade please. │
+ ╘══════════════════════════════════════════════════════════════════════════════╛
+ """.lstrip('\n')))
+
class TestSafety(unittest.TestCase):
|
pip 10 api breakage
Quoting distutils-sig:
> We're in the process of starting to plan for a release of pip (the
long-awaited pip 10). We're likely still a month or two away from a
release, but now is the time for people to start ensuring that
everything works for them. One key change in the new version will be
that all of the internal APIs of pip will no longer be available, so
any code that currently calls functions in the "pip" namespace will
break. Calling pip's internal APIs has never been supported, and
always carried a risk of such breakage, so projects doing so should,
in theory, be prepared for such things. However, reality is not always
that simple, and we are aware that people will need time to deal with
the implications.
> Just in case it's not clear, simply finding where the internal APIs
have moved to and calling them under the new names is *not* what
people should do. We can't stop people calling the internal APIs,
obviously, but the idea of this change is to give people the incentive
to find a supported approach, not just to annoy people who are doing
things we don't want them to ;-)
> So please - if you're calling pip's internals in your code, take the
opportunity *now* to check out the in-development version of pip, and
ensure your project will still work when pip 10 is released.
> And many thanks to anyone else who helps by testing out the new
version, as well :-)
> Thanks,
Paul
_________
Safety uses `pip.get_installed_distributions` which has moved to https://github.com/pypa/pip/blob/master/src/pip/_internal/utils/misc.py#L333
|
0.0
|
7e4e40e5d0e1e8cb59ca9c23379ca6c62c63a37b
|
[
"tests/test_safety.py::TestSafetyCLI::test_command_line_interface",
"tests/test_safety.py::TestFormatter::test_full_report",
"tests/test_safety.py::TestFormatter::test_get_terminal_size",
"tests/test_safety.py::TestFormatter::test_get_used_db",
"tests/test_safety.py::TestFormatter::test_report_json",
"tests/test_safety.py::TestSafety::test_check_from_file",
"tests/test_safety.py::TestSafety::test_check_live",
"tests/test_safety.py::TestSafety::test_check_live_cached",
"tests/test_safety.py::TestSafety::test_multiple_versions",
"tests/test_safety.py::ReadRequirementsTestCase::test_unpinned_vcs_requirement"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-29 23:52:25+00:00
|
mit
| 5,125 |
|
pyupio__safety-177
|
diff --git a/.gitignore b/.gitignore
index 4ea7593..177ba7f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -61,6 +61,8 @@ target/
# pyenv python configuration file
.python-version
sandbox.py
+*.idea/*
# Virtual Env
venv/
+.venv/
diff --git a/README.md b/README.md
index 4cecdb6..d8aa35c 100644
--- a/README.md
+++ b/README.md
@@ -307,4 +307,88 @@ safety check --ignore=1234
```bash
safety check -i 1234 -i 4567 -i 89101
```
+
+### `--output`, `-o`
+
+*Save the report to a file*
+
+**Example**
+```bash
+safety check -o insecure_report.txt
+```
+```bash
+safety check --output --json insecure_report.json
+```
+___
+
+# Review
+
+If you save the report in JSON format you can review in the report format again.
+
+## Options
+
+### `--file`, `-f` (REQUIRED)
+
+*Read an insecure report.*
+
+**Example**
+```bash
+safety check -f insecure.json
+```
+```bash
+safety check --file=insecure.json
+```
+___
+
+### `--full-report`
+
+*Full reports include a security advisory (if available).*
+
+**Example**
+```bash
+safety review -r insecure.json --full-report
+```
+
+```
+╒══════════════════════════════════════════════════════════════════════════════╕
+│ │
+│ /$$$$$$ /$$ │
+│ /$$__ $$ | $$ │
+│ /$$$$$$$ /$$$$$$ | $$ \__//$$$$$$ /$$$$$$ /$$ /$$ │
+│ /$$_____/ |____ $$| $$$$ /$$__ $$|_ $$_/ | $$ | $$ │
+│ | $$$$$$ /$$$$$$$| $$_/ | $$$$$$$$ | $$ | $$ | $$ │
+│ \____ $$ /$$__ $$| $$ | $$_____/ | $$ /$$| $$ | $$ │
+│ /$$$$$$$/| $$$$$$$| $$ | $$$$$$$ | $$$$/| $$$$$$$ │
+│ |_______/ \_______/|__/ \_______/ \___/ \____ $$ │
+│ /$$ | $$ │
+│ | $$$$$$/ │
+│ by pyup.io \______/ │
+│ │
+╞══════════════════════════════════════════════════════════════════════════════╡
+│ REPORT │
+╞════════════════════════════╤═══════════╤══════════════════════════╤══════════╡
+│ package │ installed │ affected │ ID │
+╞════════════════════════════╧═══════════╧══════════════════════════╧══════════╡
+│ django │ 1.2 │ <1.2.2 │ 25701 │
+╞══════════════════════════════════════════════════════════════════════════════╡
+│ Cross-site scripting (XSS) vulnerability in Django 1.2.x before 1.2.2 allows │
+│ remote attackers to inject arbitrary web script or HTML via a csrfmiddlewar │
+│ etoken (aka csrf_token) cookie. │
+╘══════════════════════════════════════════════════════════════════════════════╛
+```
___
+
+### `--bare`
+
+*Output vulnerable packages only. *
+
+**Example**
+```bash
+safety review --file report.json --bare
+```
+
+```
+django
+```
+___
+
diff --git a/safety/cli.py b/safety/cli.py
index fa7ccfe..351bdd8 100644
--- a/safety/cli.py
+++ b/safety/cli.py
@@ -6,9 +6,13 @@ from safety import __version__
from safety import safety
from safety.formatter import report
import itertools
-from safety.util import read_requirements
+from safety.util import read_requirements, read_vulnerabilities
from safety.errors import DatabaseFetchError, DatabaseFileNotFoundError, InvalidKeyError
+try:
+ from json.decoder import JSONDecodeError
+except ImportError:
+ JSONDecodeError = ValueError
@click.group()
@click.version_option(version=__version__)
@@ -38,14 +42,15 @@ def cli():
help="Read input from one (or multiple) requirement files. Default: empty")
@click.option("ignore", "--ignore", "-i", multiple=True, type=str, default=[],
help="Ignore one (or multiple) vulnerabilities by ID. Default: empty")
[email protected]("--output", "-o", default="",
+ help="Path to where output file will be placed. Default: empty")
@click.option("proxyhost", "--proxy-host", "-ph", multiple=False, type=str, default=None,
help="Proxy host IP or DNS --proxy-host")
@click.option("proxyport", "--proxy-port", "-pp", multiple=False, type=int, default=80,
help="Proxy port number --proxy-port")
@click.option("proxyprotocol", "--proxy-protocol", "-pr", multiple=False, type=str, default='http',
help="Proxy protocol (https or http) --proxy-protocol")
-def check(key, db, json, full_report, bare, stdin, files, cache, ignore, proxyprotocol, proxyhost, proxyport):
-
+def check(key, db, json, full_report, bare, stdin, files, cache, ignore, output, proxyprotocol, proxyhost, proxyport):
if files and stdin:
click.secho("Can't read from --stdin and --file at the same time, exiting", fg="red")
sys.exit(-1)
@@ -69,17 +74,19 @@ def check(key, db, json, full_report, bare, stdin, files, cache, ignore, proxypr
sys.exit(-1)
try:
vulns = safety.check(packages=packages, key=key, db_mirror=db, cached=cache, ignore_ids=ignore, proxy=proxy_dictionary)
- click.secho(report(
- vulns=vulns,
- full=full_report,
- json_report=json,
- bare_report=bare,
- checked_packages=len(packages),
- db=db,
- key=key
- ),
- nl=False if bare and not vulns else True
- )
+ output_report = report(vulns=vulns,
+ full=full_report,
+ json_report=json,
+ bare_report=bare,
+ checked_packages=len(packages),
+ db=db,
+ key=key)
+
+ if output:
+ with open(output, 'w+') as output_file:
+ output_file.write(output_report)
+ else:
+ click.secho(output_report, nl=False if bare and not vulns else True)
sys.exit(-1 if vulns else 0)
except InvalidKeyError:
click.secho("Your API Key '{key}' is invalid. See {link}".format(
@@ -94,5 +101,30 @@ def check(key, db, json, full_report, bare, stdin, files, cache, ignore, proxypr
sys.exit(-1)
[email protected]()
[email protected]("--full-report/--short-report", default=False,
+ help='Full reports include a security advisory (if available). Default: '
+ '--short-report')
[email protected]("--bare/--not-bare", default=False,
+ help='Output vulnerable packages only. Useful in combination with other tools.'
+ 'Default: --not-bare')
[email protected]("file", "--file", "-f", type=click.File(), required=True,
+ help="Read input from an insecure report file. Default: empty")
+def review(full_report, bare, file):
+ if full_report and bare:
+ click.secho("Can't choose both --bare and --full-report/--short-report", fg="red")
+ sys.exit(-1)
+
+ try:
+ input_vulns = read_vulnerabilities(file)
+ except JSONDecodeError:
+ click.secho("Not a valid JSON file", fg="red")
+ sys.exit(-1)
+
+ vulns = safety.review(input_vulns)
+ output_report = report(vulns=vulns, full=full_report, bare_report=bare)
+ click.secho(output_report, nl=False if bare and not vulns else True)
+
+
if __name__ == "__main__":
cli()
diff --git a/safety/safety.py b/safety/safety.py
index ca9fb04..871bd77 100644
--- a/safety/safety.py
+++ b/safety/safety.py
@@ -9,6 +9,7 @@ import json
import time
import errno
+
class Vulnerability(namedtuple("Vulnerability",
["name", "spec", "version", "advisory", "vuln_id"])):
pass
@@ -150,3 +151,19 @@ def check(packages, key, db_mirror, cached, ignore_ids, proxy):
)
)
return vulnerable
+
+
+def review(vulnerabilities):
+ vulnerable = []
+ for vuln in vulnerabilities:
+ current_vuln = {
+ "name": vuln[0],
+ "spec": vuln[1],
+ "version": vuln[2],
+ "advisory": vuln[3],
+ "vuln_id": vuln[4],
+ }
+ vulnerable.append(
+ Vulnerability(**current_vuln)
+ )
+ return vulnerable
diff --git a/safety/util.py b/safety/util.py
index 2e6efae..00a40d9 100644
--- a/safety/util.py
+++ b/safety/util.py
@@ -1,11 +1,16 @@
from dparse.parser import setuptools_parse_requirements_backport as _parse_requirements
from collections import namedtuple
import click
+import json
import os
Package = namedtuple("Package", ["key", "version"])
RequirementFile = namedtuple("RequirementFile", ["path"])
+def read_vulnerabilities(fh):
+ return json.load(fh)
+
+
def iter_lines(fh, lineno=0):
for line in fh.readlines()[lineno:]:
yield line
|
pyupio/safety
|
0879d6f83bd69c58cc7115098f91e01a15b7bfb0
|
diff --git a/tests/test_db/example_report.json b/tests/test_db/example_report.json
new file mode 100644
index 0000000..a68da92
--- /dev/null
+++ b/tests/test_db/example_report.json
@@ -0,0 +1,23 @@
+[
+ [
+ "django",
+ "<1.2.7",
+ "1.2.2",
+ "django.contrib.sessions in Django before 1.2.7 and 1.3.x before 1.3.1, when session data is stored in the cache, uses the root namespace for both session identifiers and application-data keys, which allows remote attackers to modify a session by triggering use of a key that is equal to that session's identifier.",
+ "33063"
+ ],
+ [
+ "django",
+ "<1.2.7",
+ "1.2.2",
+ "The verify_exists functionality in the URLField implementation in Django before 1.2.7 and 1.3.x before 1.3.1 relies on Python libraries that attempt access to an arbitrary URL with no timeout, which allows remote attackers to cause a denial of service (resource consumption) via a URL associated with (1) a slow response, (2) a completed TCP connection with no application data sent, or (3) a large amount of application data, a related issue to CVE-2011-1521.",
+ "33064"
+ ],
+ [
+ "django",
+ "<1.2.7",
+ "1.2.2",
+ "The verify_exists functionality in the URLField implementation in Django before 1.2.7 and 1.3.x before 1.3.1 originally tests a URL's validity through a HEAD request, but then uses a GET request for the new target URL in the case of a redirect, which might allow remote attackers to trigger arbitrary GET requests with an unintended source IP address via a crafted Location header.",
+ "33065"
+ ]
+]
diff --git a/tests/test_db/invalid_example_report.json b/tests/test_db/invalid_example_report.json
new file mode 100644
index 0000000..5cd3752
--- /dev/null
+++ b/tests/test_db/invalid_example_report.json
@@ -0,0 +1,21 @@
+[
+ [
+ "django",
+ "<1.2.7",
+ "1.2.2",
+ "django.contrib.sessions in Django before 1.2.7 and 1.3.x before 1.3.1, when session data is stored in the cache, uses the root namespace for both session identifiers and application-data keys, which allows remote attackers to modify a session by triggering use of a key that is equal to that session's identifier.",
+ "33063"
+ ],
+ [
+ "django",
+ "<1.2.7",
+ "1.2.2",
+ "The verify_exists functionality in the URLField implementation in Django before 1.2.7 and 1.3.x before 1.3.1 relies on Python libraries that attempt access to an arbitrary URL with no timeout, which allows remote attackers to cause a denial of service (resource consumption) via a URL associated with (1) a slow response, (2) a completed TCP connection with no application data sent, or (3) a large amount of application data, a related issue to CVE-2011-1521.",
+ "33064"
+ ],
+ [
+ "django",
+ "<1.2.7",
+ "1.2.2",
+ "The verify_exists functionality in the URLField implementation in Django before 1.2.7 and 1.3.x before 1.3.1 originally tests a URL's validity through a HEAD request, but then uses a GET request for the new target URL in the case of a redirect, which might allow remote attackers to trigger arbitrary GET requests with an unintended source IP address via a crafted Location header.",
+ "33065"
diff --git a/tests/test_safety.py b/tests/test_safety.py
index 2bde30f..fdb63df 100644
--- a/tests/test_safety.py
+++ b/tests/test_safety.py
@@ -24,6 +24,8 @@ try:
except ImportError:
from io import StringIO
from safety.util import read_requirements
+from safety.util import read_vulnerabilities
+
class TestSafetyCLI(unittest.TestCase):
@@ -36,6 +38,21 @@ class TestSafetyCLI(unittest.TestCase):
assert help_result.exit_code == 0
assert '--help' in help_result.output
+ def test_review_pass(self):
+ runner = CliRunner()
+ dirname = os.path.dirname(__file__)
+ path_to_report = os.path.join(dirname, "test_db", "example_report.json")
+ result = runner.invoke(cli.cli, ['review', '--bare', '--file', path_to_report])
+ assert result.exit_code == 0
+ assert result.output == u'django\n'
+
+ def test_review_fail(self):
+ runner = CliRunner()
+ dirname = os.path.dirname(__file__)
+ path_to_report = os.path.join(dirname, "test_db", "invalid_example_report.json")
+ result = runner.invoke(cli.cli, ['review', '--bare', '--file', path_to_report])
+ assert result.exit_code == -1
+
class TestFormatter(unittest.TestCase):
@@ -48,7 +65,7 @@ class TestFormatter(unittest.TestCase):
self.fail(e)
def test_report_json(self):
- test_arr = [['libfoo'],['libbar']]
+ test_arr = [['libfoo'], ['libbar']]
json_report = formatter.report(test_arr, full=False, json_report=True)
assert json.loads(json_report) == test_arr
@@ -103,6 +120,14 @@ class TestFormatter(unittest.TestCase):
class TestSafety(unittest.TestCase):
+ def test_review_from_file(self):
+ dirname = os.path.dirname(__file__)
+ path_to_report = os.path.join(dirname, "test_db", "example_report.json")
+ with open(path_to_report) as insecure:
+ input_vulns = read_vulnerabilities(insecure)
+
+ vulns = safety.review(input_vulns)
+ assert(len(vulns), 3)
def test_check_from_file(self):
reqs = StringIO("Django==1.8.1")
@@ -137,6 +162,7 @@ class TestSafety(unittest.TestCase):
proxy={}
)
self.assertEqual(len(vulns), 4)
+
def test_check_live(self):
reqs = StringIO("insecure-package==0.1")
packages = util.read_requirements(reqs)
|
Load and pretty-print previously saved results
* safety version: 1.8.1 (current at the moment)
* Python version: 3.6.3
* Operating System: Debian 8 (Docker container)
### Description
This is a feature suggestion.
It'd be nice to be able to recall the saved results in the tidy way _safety_ displays.
Firstly, a user may run the check and save its result:
```shell
safety check --json > vulns_2018-06-26.json
```
To review the pretty-printed result later, do:
```shell
safety review --stdin < vulns_2018-06-26.json
# Alternatively,
safety review --file=vulns_2018-06-26.json
```
_safety_ reads the input JSON and display its readings:
```
╒══════════════════════════════════════════════════════════════════════════════╕
│ │
│ /$$$$$$ /$$ │
│ /$$__ $$ | $$ │
│ /$$$$$$$ /$$$$$$ | $$ \__//$$$$$$ /$$$$$$ /$$ /$$ │
│ /$$_____/ |____ $$| $$$$ /$$__ $$|_ $$_/ | $$ | $$ │
│ | $$$$$$ /$$$$$$$| $$_/ | $$$$$$$$ | $$ | $$ | $$ │
│ \____ $$ /$$__ $$| $$ | $$_____/ | $$ /$$| $$ | $$ │
│ /$$$$$$$/| $$$$$$$| $$ | $$$$$$$ | $$$$/| $$$$$$$ │
│ |_______/ \_______/|__/ \_______/ \___/ \____ $$ │
│ /$$ | $$ │
│ | $$$$$$/ │
│ by pyup.io \______/ │
│ │
╞══════════════════════════════════════════════════════════════════════════════╡
│ REPORT │
│ checked 144 packages, using default DB │
╞════════════════════════════╤═══════════╤══════════════════════════╤══════════╡
│ package │ installed │ affected │ ID │
╞════════════════════════════╧═══════════╧══════════════════════════╧══════════╡
│ pyjwt │ 1.5.0 │ <1.5.1 │ 35014 │
│ newrelic │ 2.78.0.57 │ >=1.1.0.192,<=2.106.0.87 │ 35805 │
╘══════════════════════════════════════════════════════════════════════════════╛
```
Adding `--bare` and `--full-report` supports would be great, too.
### What I Did
I thought of this idea.
|
0.0
|
0879d6f83bd69c58cc7115098f91e01a15b7bfb0
|
[
"tests/test_safety.py::TestSafetyCLI::test_command_line_interface",
"tests/test_safety.py::TestSafetyCLI::test_review_fail",
"tests/test_safety.py::TestSafetyCLI::test_review_pass",
"tests/test_safety.py::TestFormatter::test_full_report",
"tests/test_safety.py::TestFormatter::test_get_terminal_size",
"tests/test_safety.py::TestFormatter::test_get_used_db",
"tests/test_safety.py::TestFormatter::test_report_json",
"tests/test_safety.py::TestSafety::test_check_from_file",
"tests/test_safety.py::TestSafety::test_check_live",
"tests/test_safety.py::TestSafety::test_check_live_cached",
"tests/test_safety.py::TestSafety::test_multiple_versions",
"tests/test_safety.py::TestSafety::test_review_from_file",
"tests/test_safety.py::ReadRequirementsTestCase::test_unpinned_vcs_requirement"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-11-30 21:41:11+00:00
|
mit
| 5,126 |
|
pyupio__safety-343
|
diff --git a/.gitignore b/.gitignore
index c6372ce..6e1aa8a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -66,7 +66,6 @@ target/
# pyenv python configuration file
.python-version
sandbox.py
-<<<<<<< HEAD
# PyCharm
.idea
@@ -74,4 +73,4 @@ sandbox.py
# Virtual Env
venv/
-.venv/
\ No newline at end of file
+.venv/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index de7b18c..5b7fafd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ The format is partly based on [Keep a Changelog](https://keepachangelog.com/en/1
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and [PEP 440](https://peps.python.org/pep-0440/)
## [Unreleased] 2.4.0.dev
+- Add support for coma separated ignore (--ignore=123,456) on top of existing --ignore=123 --ignore=456
## [2.3.5] - 2022-12-08
- Pinned packaging dependency to a compatible range.
diff --git a/README.md b/README.md
index 1a98563..a26b2b5 100644
--- a/README.md
+++ b/README.md
@@ -466,6 +466,10 @@ safety check -i 1234
safety check --ignore=1234
```
```bash
+safety check -i 1234,4567,89101
+```
+The following is also supported (backward compatibility)
+```bash
safety check -i 1234 -i 4567 -i 89101
```
diff --git a/safety/cli.py b/safety/cli.py
index 149fcba..feed6cf 100644
--- a/safety/cli.py
+++ b/safety/cli.py
@@ -113,7 +113,7 @@ def clean_check_command(f):
mutually_exclusive=["stdin"],
help="Read input from one (or multiple) requirement files. Default: empty")
@click.option("--ignore", "-i", multiple=True, type=str, default=[], callback=transform_ignore,
- help="Ignore one (or multiple) vulnerabilities by ID. Default: empty")
+ help="Ignore one (or multiple) vulnerabilities by ID (coma separated). Default: empty")
@click.option('--json', default=False, cls=MutuallyExclusiveOption, mutually_exclusive=["output", "bare"],
with_values={"output": ['screen', 'text', 'bare', 'json'], "bare": [True, False]}, callback=json_alias,
hidden=True, is_flag=True, show_default=True)
@@ -165,7 +165,6 @@ def check(ctx, key, db, full_report, stdin, files, cache, ignore, output, json,
ignore_severity_rules = None
ignore, ignore_severity_rules, exit_code = get_processed_options(policy_file, ignore,
ignore_severity_rules, exit_code)
-
is_env_scan = not stdin and not files
params = {'stdin': stdin, 'files': files, 'policy_file': policy_file, 'continue_on_error': not exit_code,
'ignore_severity_rules': ignore_severity_rules, 'project': project,
diff --git a/safety/util.py b/safety/util.py
index 95403ba..e124909 100644
--- a/safety/util.py
+++ b/safety/util.py
@@ -354,8 +354,15 @@ class DependentOption(click.Option):
def transform_ignore(ctx, param, value):
+ ignored_default_dict = {'reason': '', 'expires': None}
if isinstance(value, tuple):
- return dict(zip(value, [{'reason': '', 'expires': None} for _ in range(len(value))]))
+ # Following code is required to support the 2 ways of providing 'ignore'
+ # --ignore=1234,567,789
+ # or, the historical way (supported for backward compatibility)
+ # -i 1234 -i 567
+ combined_value = ','.join(value)
+ ignore_ids = {vuln_id.strip() for vuln_id in combined_value.split(',')}
+ return {ignore_id: dict(ignored_default_dict) for ignore_id in ignore_ids}
return {}
|
pyupio/safety
|
87000ca8697d3a2f7ea36822ba45fe9f54881922
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index c4675fc..8f77fc9 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -198,6 +198,28 @@ class TestSafetyCLI(unittest.TestCase):
# TODO: Add test for the screen formatter, this only test that the command doesn't crash
self.assertEqual(result.exit_code, 0)
+ @patch("safety.safety.check")
+ def test_check_ignore_format_backward_compatible(self, check):
+ runner = CliRunner()
+
+ check.return_value = []
+
+ dirname = os.path.dirname(__file__)
+ reqs_path = os.path.join(dirname, "reqs_4.txt")
+
+ _ = runner.invoke(cli.cli, ['check', '--file', reqs_path, '--ignore', "123,456", '--ignore', "789"])
+ try:
+ check_call_kwargs = check.call_args[1] # Python < 3.8
+ except IndexError:
+ check_call_kwargs = check.call_args.kwargs
+
+ ignored_transformed = {
+ '123': {'expires': None, 'reason': ''},
+ '456': {'expires': None, 'reason': ''},
+ '789': {'expires': None, 'reason': ''}
+ }
+ self.assertEqual(check_call_kwargs['ignore_vulns'], ignored_transformed)
+
def test_validate_with_unsupported_argument(self):
result = self.runner.invoke(cli.cli, ['validate', 'safety_ci'])
msg = 'This Safety version only supports "policy_file" validation. "safety_ci" is not supported.\n'
diff --git a/tests/test_safety.py b/tests/test_safety.py
index 28ac318..49d7f2c 100644
--- a/tests/test_safety.py
+++ b/tests/test_safety.py
@@ -60,6 +60,29 @@ class TestSafety(unittest.TestCase):
)
self.assertEqual(len(vulns), 2)
+ def test_check_ignores(self):
+ reqs = StringIO("Django==1.8.1")
+ packages = util.read_requirements(reqs)
+
+ # Second that ignore works
+ ignored_vulns = {'some id': {'expires': None, 'reason': ''}}
+
+ vulns, _ = safety.check(
+ packages=packages,
+ key=None,
+ db_mirror=os.path.join(
+ os.path.dirname(os.path.realpath(__file__)),
+ "test_db"
+ ),
+ cached=0,
+ ignore_vulns=ignored_vulns,
+ ignore_severity_rules=None,
+ proxy={},
+ telemetry=False
+ )
+ self.assertEqual(len(vulns), 1)
+ self.assertEqual(vulns[0].vulnerability_id, "some other id")
+
def test_check_from_file_with_hash_pins(self):
reqs = StringIO(("Django==1.8.1 "
"--hash=sha256:c6c7e7a961e2847d050d214ca96dc3167bb5f2b25cd5c6cb2eea96e1717f4ade"))
diff --git a/tests/test_util.py b/tests/test_util.py
index 43cb3cf..8df8286 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -7,7 +7,7 @@ from unittest.mock import patch, Mock
import click as click
from safety import util
-from safety.util import read_requirements, get_processed_options, SafetyPolicyFile
+from safety.util import read_requirements, get_processed_options, SafetyPolicyFile, transform_ignore
class ReadRequirementsTestCase(unittest.TestCase):
@@ -122,5 +122,16 @@ class ReadRequirementsTestCase(unittest.TestCase):
EXPECTED = not security_pf.get('continue-on-vulnerability-error')
self.assertEqual(exit_code, EXPECTED)
-
-
+ def test_transform_ignore(self):
+ ignored_transformed = {'123': {'expires': None, 'reason': ''}, '456': {'expires': None, 'reason': ''}}
+ self.assertEqual(transform_ignore(None, None, value=("123", "456")), ignored_transformed)
+ self.assertEqual(transform_ignore(None, None, value=("123,456",)), ignored_transformed)
+
+ def test_transform_ignore_mixed_arguments(self):
+ # mix old and new way of providing --ignore
+ ignored_transformed = {
+ '123': {'expires': None, 'reason': ''},
+ '456': {'expires': None, 'reason': ''},
+ '789': {'expires': None, 'reason': ''}
+ }
+ self.assertEqual(transform_ignore(None, None, value=("123,456", "789")), ignored_transformed)
|
Let 'ignore' take a list of coma separated ID
As it is now, in case we want to ignore multiple vulnerabilities, we have to use
`safety check -i 1234 -i 4567 -i 89101`
I'd like to suggest to start supporting coma separated list in a similar fashion as well known similar tools are doing (flake8, pylint, etc)
`safety check -i 1234,4567,89101`
Would you welcome a PR?
|
0.0
|
87000ca8697d3a2f7ea36822ba45fe9f54881922
|
[
"tests/test_cli.py::TestSafetyCLI::test_check_ignore_format_backward_compatible",
"tests/test_util.py::ReadRequirementsTestCase::test_transform_ignore",
"tests/test_util.py::ReadRequirementsTestCase::test_transform_ignore_mixed_arguments"
] |
[
"tests/test_cli.py::TestSafetyCLI::test_announcements_if_is_not_tty",
"tests/test_cli.py::TestSafetyCLI::test_chained_review_pass",
"tests/test_cli.py::TestSafetyCLI::test_check_continue_on_error",
"tests/test_cli.py::TestSafetyCLI::test_check_vulnerabilities_found_default",
"tests/test_cli.py::TestSafetyCLI::test_check_vulnerabilities_found_with_outputs",
"tests/test_cli.py::TestSafetyCLI::test_check_vulnerabilities_not_found_default",
"tests/test_cli.py::TestSafetyCLI::test_check_vulnerabilities_not_found_with_outputs",
"tests/test_cli.py::TestSafetyCLI::test_check_with_fix",
"tests/test_cli.py::TestSafetyCLI::test_check_with_fix_does_verify_api_key",
"tests/test_cli.py::TestSafetyCLI::test_check_with_fix_only_works_with_files",
"tests/test_cli.py::TestSafetyCLI::test_command_line_interface",
"tests/test_cli.py::TestSafetyCLI::test_generate_pass",
"tests/test_cli.py::TestSafetyCLI::test_generate_with_unsupported_argument",
"tests/test_cli.py::TestSafetyCLI::test_generate_with_wrong_path",
"tests/test_cli.py::TestSafetyCLI::test_license_with_file",
"tests/test_cli.py::TestSafetyCLI::test_review_pass",
"tests/test_cli.py::TestSafetyCLI::test_validate_with_basic_policy_file",
"tests/test_cli.py::TestSafetyCLI::test_validate_with_policy_file_using_invalid_keyword",
"tests/test_cli.py::TestSafetyCLI::test_validate_with_policy_file_using_invalid_typo_keyword",
"tests/test_cli.py::TestSafetyCLI::test_validate_with_unsupported_argument",
"tests/test_cli.py::TestSafetyCLI::test_validate_with_wrong_path",
"tests/test_safety.py::TestSafety::test_calculate_remediations",
"tests/test_safety.py::TestSafety::test_check_from_file",
"tests/test_safety.py::TestSafety::test_check_from_file_with_hash_pins",
"tests/test_safety.py::TestSafety::test_check_ignores",
"tests/test_safety.py::TestSafety::test_check_live",
"tests/test_safety.py::TestSafety::test_check_live_cached",
"tests/test_safety.py::TestSafety::test_compute_sec_ver",
"tests/test_safety.py::TestSafety::test_dont_ignore_vulns_by_unknown_severity",
"tests/test_safety.py::TestSafety::test_get_announcements_catch_request_exceptions",
"tests/test_safety.py::TestSafety::test_get_announcements_catch_unhandled_http_codes",
"tests/test_safety.py::TestSafety::test_get_announcements_http_ok",
"tests/test_safety.py::TestSafety::test_get_announcements_wrong_json_response_handling",
"tests/test_safety.py::TestSafety::test_get_cached_packages_licenses",
"tests/test_safety.py::TestSafety::test_get_closest_ver",
"tests/test_safety.py::TestSafety::test_get_packages_licenses",
"tests/test_safety.py::TestSafety::test_get_packages_licenses_db_fetch_error",
"tests/test_safety.py::TestSafety::test_get_packages_licenses_very_often",
"tests/test_safety.py::TestSafety::test_get_packages_licenses_with_invalid_api_key",
"tests/test_safety.py::TestSafety::test_get_packages_licenses_with_invalid_db_file",
"tests/test_safety.py::TestSafety::test_get_packages_licenses_without_api_key",
"tests/test_safety.py::TestSafety::test_ignore_vulns_by_base_score",
"tests/test_safety.py::TestSafety::test_ignore_vulns_by_unknown_severity",
"tests/test_safety.py::TestSafety::test_multiple_versions",
"tests/test_safety.py::TestSafety::test_precompute_remediations",
"tests/test_safety.py::TestSafety::test_read_vulnerabilities",
"tests/test_safety.py::TestSafety::test_read_vulnerabilities_decode_error",
"tests/test_safety.py::TestSafety::test_read_vulnerabilities_type_error",
"tests/test_safety.py::TestSafety::test_report_licenses_bare",
"tests/test_safety.py::TestSafety::test_report_licenses_json",
"tests/test_safety.py::TestSafety::test_report_with_recommended_fix",
"tests/test_safety.py::TestSafety::test_review_without_recommended_fix",
"tests/test_util.py::ReadRequirementsTestCase::test_cli_continue_on_error_overrule_policy_file",
"tests/test_util.py::ReadRequirementsTestCase::test_cli_exit_code_partial_overrule_policy_file",
"tests/test_util.py::ReadRequirementsTestCase::test_cli_ignore_overrule_policy_file",
"tests/test_util.py::ReadRequirementsTestCase::test_cli_ignore_partial_overrule_policy_file",
"tests/test_util.py::ReadRequirementsTestCase::test_log_used_options_with_argv",
"tests/test_util.py::ReadRequirementsTestCase::test_recursive_requirement",
"tests/test_util.py::ReadRequirementsTestCase::test_recursive_requirement_pinned_after_unpinned",
"tests/test_util.py::ReadRequirementsTestCase::test_unpinned_vcs_requirement"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-05-14 19:23:03+00:00
|
mit
| 5,127 |
|
pyvisa__pyvisa-661
|
diff --git a/.gitignore b/.gitignore
index 0d690f7..0b75ed0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,3 +20,5 @@ htmlcov/
.mypy_cache/
pip-wheel-metadata/
.pytest_cache
+.venv/
+venv/
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 0b11493..bc31bd6 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,19 +1,18 @@
repos:
-- repo: https://github.com/pre-commit/mirrors-isort
- rev: v5.5.3
- hooks:
- - id: isort
-- repo: https://github.com/psf/black
- rev: 20.8b1
- hooks:
- - id: black
- language_version: python3.7
-- repo: https://gitlab.com/pycqa/flake8
- rev: 3.8.3
- hooks:
- - id: flake8
-- repo: https://github.com/pre-commit/mirrors-mypy
- rev: v0.782 # Use the sha / tag you want to point at
- hooks:
- - id: mypy
- additional_dependencies: [numpy, typing_extensions]
\ No newline at end of file
+ - repo: https://github.com/pre-commit/mirrors-isort
+ rev: v5.5.3
+ hooks:
+ - id: isort
+ - repo: https://github.com/psf/black
+ rev: 22.3.0
+ hooks:
+ - id: black
+ - repo: https://gitlab.com/pycqa/flake8
+ rev: 3.8.3
+ hooks:
+ - id: flake8
+ - repo: https://github.com/pre-commit/mirrors-mypy
+ rev: v0.782 # Use the sha / tag you want to point at
+ hooks:
+ - id: mypy
+ additional_dependencies: [numpy, typing_extensions]
diff --git a/CHANGES b/CHANGES
index 7e2a919..d3bc016 100644
--- a/CHANGES
+++ b/CHANGES
@@ -15,6 +15,8 @@ PyVISA Changelog
- allow trailing separators in ascii blocks PR #581
Numpy style extraction already handled this case correctly but it was not so
for the builtin parser.
+- adding open_resource attribute check for VisaLibraryBase in order to support
+ custom resource opening #660
- changed constant ControlFlow enum type from IntEnum to IntFlag PR#652
This change also triggers a change in attributes.py to include a new Attribute
class, FlagAttribute where the enum type is declared at IntFlag.
diff --git a/docs/source/advanced/backends.rst b/docs/source/advanced/backends.rst
index 4d60245..cb9a930 100644
--- a/docs/source/advanced/backends.rst
+++ b/docs/source/advanced/backends.rst
@@ -91,6 +91,12 @@ As a **very minimum** set you need:
(you can get the signature below or here :ref:`api_visalibrarybase`)
+.. note::
+
+ A |ResourceManager| attribute check for
+ :class:`pyvisa.highlevel.VisaLibraryBase.open_resource` is implemented
+ in order to support custom opening handling by the new backend implementation.
+
But of course you cannot do anything interesting with just this. In general you
will also need:
diff --git a/pyvisa/constants.py b/pyvisa/constants.py
index da320a4..ecfeea0 100644
--- a/pyvisa/constants.py
+++ b/pyvisa/constants.py
@@ -18,7 +18,7 @@ import sys
from typing_extensions import Literal
-is_64bits = sys.maxsize > 2 ** 32
+is_64bits = sys.maxsize > 2**32
def _to_int(x: int) -> int:
diff --git a/pyvisa/highlevel.py b/pyvisa/highlevel.py
index af43216..720517e 100644
--- a/pyvisa/highlevel.py
+++ b/pyvisa/highlevel.py
@@ -3268,7 +3268,6 @@ class ResourceManager(object):
Subclass of Resource matching the resource.
"""
-
if resource_pyclass is None:
info = self.resource_info(resource_name, extended=True)
@@ -3286,27 +3285,31 @@ class ResourceManager(object):
"There is no class defined for %r. Using Resource",
(info.interface_type, info.resource_class),
)
-
- res = resource_pyclass(self, resource_name)
- for key in kwargs.keys():
- try:
- getattr(res, key)
- present = True
- except AttributeError:
- present = False
- except errors.InvalidSession:
- present = True
-
- if not present:
- raise ValueError(
- "%r is not a valid attribute for type %s"
- % (key, res.__class__.__name__)
- )
-
- res.open(access_mode, open_timeout)
-
- for key, value in kwargs.items():
- setattr(res, key, value)
+ if hasattr(self.visalib, "open_resource"):
+ res = self.visalib.open_resource( # type: ignore
+ resource_name, access_mode, open_timeout, resource_pyclass, **kwargs
+ )
+ else:
+ res = resource_pyclass(self, resource_name)
+ for key in kwargs.keys():
+ try:
+ getattr(res, key)
+ present = True
+ except AttributeError:
+ present = False
+ except errors.InvalidSession:
+ present = True
+
+ if not present:
+ raise ValueError(
+ "%r is not a valid attribute for type %s"
+ % (key, res.__class__.__name__)
+ )
+
+ res.open(access_mode, open_timeout)
+
+ for key, value in kwargs.items():
+ setattr(res, key, value)
self._created_resources.add(res)
diff --git a/pyvisa/shell.py b/pyvisa/shell.py
index 4712921..3e0d6d4 100644
--- a/pyvisa/shell.py
+++ b/pyvisa/shell.py
@@ -328,7 +328,7 @@ class VisaShell(cmd.Cmd):
if not args:
try:
- charmap = {u"\r": "CR", u"\n": "LF", u"\r\n": "CRLF", u"\0": "NUL"}
+ charmap = {"\r": "CR", "\n": "LF", "\r\n": "CRLF", "\0": "NUL"}
chr = self.current.read_termination
if chr in charmap:
chr = charmap[chr]
@@ -349,10 +349,10 @@ class VisaShell(cmd.Cmd):
)
else:
charmap = {
- "CR": u"\r",
- "LF": u"\n",
- "CRLF": u"\r\n",
- "NUL": u"\0",
+ "CR": "\r",
+ "LF": "\n",
+ "CRLF": "\r\n",
+ "NUL": "\0",
"None": None,
}
chr = args[0]
|
pyvisa/pyvisa
|
53a1d410f727e8d16212ceae3229e6219443f9aa
|
diff --git a/pyvisa/testsuite/fake-extensions/pyvisa_test_open.py b/pyvisa/testsuite/fake-extensions/pyvisa_test_open.py
new file mode 100644
index 0000000..6d010db
--- /dev/null
+++ b/pyvisa/testsuite/fake-extensions/pyvisa_test_open.py
@@ -0,0 +1,36 @@
+# -*- coding: utf-8 -*-
+"""
+
+"""
+from pyvisa import constants
+from pyvisa.highlevel import VisaLibraryBase
+from pyvisa.util import LibraryPath
+
+
+class FakeResource:
+ def close(self):
+ pass
+
+
+class FalseVISALib(VisaLibraryBase):
+ pass
+
+ @staticmethod
+ def get_library_paths():
+ return (LibraryPath("unset"),)
+
+ def _init(self):
+ pass
+
+ def open_resource(self, *args, **kwargs):
+ self.open_resource_called = True
+ return FakeResource()
+
+ def open_default_resource_manager(self):
+ return 1, constants.StatusCode.success
+
+ def close(self, session):
+ pass
+
+
+WRAPPER_CLASS = FalseVISALib
diff --git a/pyvisa/testsuite/test_highlevel.py b/pyvisa/testsuite/test_highlevel.py
index 4eb0d58..43974a3 100644
--- a/pyvisa/testsuite/test_highlevel.py
+++ b/pyvisa/testsuite/test_highlevel.py
@@ -5,10 +5,11 @@
import logging
import os
import sys
+from importlib import import_module
import pytest
-from pyvisa import constants, highlevel, resources, rname
+from pyvisa import ResourceManager, constants, highlevel, resources, rname
from pyvisa.ctwrapper import IVIVisaLibrary
from . import BaseTestCase
@@ -247,3 +248,22 @@ class TestHighlevel(BaseTestCase):
def test_base_get_debug_info(self):
"""Test the base class implementation of get_debug_info."""
assert len(highlevel.VisaLibraryBase.get_debug_info()) == 1
+
+ def test_open_resource_attr(self, caplog):
+ """Test handling errors when trying to open a Visa library."""
+ highlevel._WRAPPERS.clear()
+
+ path = os.path.join(os.path.dirname(__file__), "fake-extensions")
+ sys.path.append(path)
+ try:
+ pkg = import_module("pyvisa_test_open")
+ highlevel.get_wrapper_class("test_open")
+ rm = ResourceManager("@test_open")
+ assert rm is not None
+ finally:
+ sys.path.remove(path)
+
+ instr = rm.open_resource("TCPIP::192.168.0.1::INSTR")
+ assert isinstance(instr, pkg.FakeResource)
+ assert rm.visalib.open_resource_called
+ rm.close()
|
[REQUEST] Support for integrating pyvisa-proxy
Hi Pyvisa Devs,
I am currently [developing an extension](https://github.com/casabre/pyvisa-proxy) for pyvisa which should somehow reflect the behavior of the NI remote VISA functionality but without the constraint of running NI-VISA. Due to the fact that there are many VISA flavors out there and NI-VISA is a bloated installer, I want to develop an independent and generic solution based on zmq which are connecting legacy protocols as GPIB or some USB connection. In the end, with mostly and ethernet-based instruments and pyvisa-proxy, distributed, dockerized tests will be feasible like for instance with my corresponding [Docker Image](https://hub.docker.com/r/casabre/rsvisa-python).
The architecture is not thought to then end but I just want to see if the PoC is working. However, after starting, I realized that implementing the client side is pretty hard because I want to forward the attribute calls to the server. Without relying on a specific class implementation, it was almost impossible to get the right attributes for forwarding.
Thus, I am asking if you could support me in order to integrate the logic into pyvisa with either a more monkey-patching approach of `__get_attr__` or an embedded implementation.
Regarding the resource string, I have something similar in mind like the NI-VISA string → `proxy://hostname:port/remote resource`. After parsing, the pyvisa-proxy extension has to be loaded.
If that sounds interesting to you and I believe you have questions, please contact me.
Thanks & best regards
Carsten
|
0.0
|
53a1d410f727e8d16212ceae3229e6219443f9aa
|
[
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_open_resource_attr"
] |
[
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[TCPIP::192.168.0.1::INSTR-values0]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[TCPIP1::192.168.0.1::INSTR-values1]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[TCPIP::192.168.0.1::5000::SOCKET-values2]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[TCPIP2::192.168.0.1::5000::SOCKET-values3]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[GPIB::1::INSTR-values4]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[GPIB::INTFC-values5]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[GPIB2::1::INSTR-values6]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[GPIB3::INTFC-values7]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[USB1::0x1111::0x2222::0x4445::0::RAW-values8]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[USB0::0x1112::0x2223::0x1234::0::INSTR-values9]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[ASRL2::INSTR-values10]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource[ASRL/dev/tty0::INSTR-values11]",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_class_parse_resource_error",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_specifying_path_open_visa_library",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_handling_error_in_opening_library",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_list_backends",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_get_wrapper_class",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_get_default_wrapper",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_register_resource_class",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_register_resource_class_missing_attr",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_get_library_paths",
"pyvisa/testsuite/test_highlevel.py::TestHighlevel::test_base_get_debug_info"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-04-03 21:21:36+00:00
|
mit
| 5,128 |
|
pyvisa__pyvisa-774
|
diff --git a/CHANGES b/CHANGES
index c9976ff..02157de 100644
--- a/CHANGES
+++ b/CHANGES
@@ -15,6 +15,8 @@ PyVISA Changelog
- `p.u.get_shared_library_arch` now returns `p.u.PEMachineType` instead of a string
- `p.u.get_arch` now returns a list of `p.u.ArchitectureType`
- update `Resource` context manager type annotation to preserve derived type PR # 740
+- added support for using custom simulation files when using the `sim` backend
+ with `pyvisa-shell`. PR #774
1.13.0 (22-12-2022)
-------------------
diff --git a/docs/source/introduction/shell.rst b/docs/source/introduction/shell.rst
index cc4d7ed..5cd0662 100644
--- a/docs/source/introduction/shell.rst
+++ b/docs/source/introduction/shell.rst
@@ -158,6 +158,10 @@ You can invoke::
to use python-sim as backend instead of ni backend.
This can be used for example for testing of python-sim configuration.
+You can include a specific file to use for the simulated backend::
+
+ pyvisa-shell -b file.yaml@sim
+
You can invoke::
pyvisa-shell -b py
diff --git a/pyvisa/cmd_line_tools.py b/pyvisa/cmd_line_tools.py
index f8218a4..a31f23b 100644
--- a/pyvisa/cmd_line_tools.py
+++ b/pyvisa/cmd_line_tools.py
@@ -7,6 +7,7 @@ This file is part of PyVISA.
:license: MIT, see LICENSE for more details.
"""
+import argparse
from typing import Optional
@@ -50,13 +51,27 @@ def visa_main(command: Optional[str] = None) -> None:
elif args.command == "shell":
from pyvisa import shell
- shell.main("@" + args.backend if args.backend else "")
+ backend = _create_backend_str(args)
+ shell.main(backend)
else:
raise ValueError(
f"Unknown command {args.command}. Valid values are: info and shell"
)
+def _create_backend_str(args: argparse.Namespace) -> str:
+ """Create the backend string from the CLI arguments."""
+ if not args.backend:
+ return ""
+
+ # User already entered things correctly like "@py" or "file.yaml@sim"
+ if "@" in args.backend:
+ return args.backend
+
+ # Keep the current functionality
+ return "@" + args.backend
+
+
def visa_shell() -> None:
"""Run the VISA shell CLI program."""
visa_main("shell")
|
pyvisa/pyvisa
|
088f591c37d9846821ebf99fe1af0e6c2cd500de
|
diff --git a/pyvisa/testsuite/test_cmd_line_tools.py b/pyvisa/testsuite/test_cmd_line_tools.py
index 349da30..8e490a4 100644
--- a/pyvisa/testsuite/test_cmd_line_tools.py
+++ b/pyvisa/testsuite/test_cmd_line_tools.py
@@ -2,12 +2,13 @@
"""Test the behavior of the command line tools.
"""
+import argparse
import sys
from subprocess import PIPE, Popen, run
import pytest
-from pyvisa import util
+from pyvisa import cmd_line_tools, util
from . import BaseTestCase, require_visa_lib
@@ -41,3 +42,18 @@ class TestCmdLineTools(BaseTestCase):
with Popen(["pyvisa-shell"], stdin=PIPE, stdout=PIPE) as p:
stdout, stderr = p.communicate(b"exit")
assert stdout.count(b"Welcome to the VISA shell") == 1
+
+
[email protected](
+ "args, want",
+ [
+ (argparse.Namespace(backend=None), ""),
+ (argparse.Namespace(backend="py"), "@py"),
+ (argparse.Namespace(backend="foo.yaml@sim"), "foo.yaml@sim"),
+ (argparse.Namespace(backend="/foo/bar/baz.yaml@sim"), "/foo/bar/baz.yaml@sim"),
+ (argparse.Namespace(backend="@sim"), "@sim"),
+ ],
+)
+def test__create_backend_str(args: argparse.Namespace, want: str) -> None:
+ got = cmd_line_tools._create_backend_str(args)
+ assert got == want
|
Add support for custom simulation files to pyvisa-shell
Running `pyvisa-shell --backend sim` does not appear to support custom simulation files.
The fix looks very easy - I'll submit a PR.
### Steps to Reproduce:
1. Create the sim file shown below.
2. Run `pyvisa-shell --backend pyvisa_test.yaml@sim`
3. See Errror
### Expected Result
The custom simulation file is used
### Actual result
The program errors out.
```console
$ pyvisa-shell --backend pyvisa_test.yaml@sim
Traceback (most recent call last):
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/ctwrapper/highlevel.py", line 162, in _init
lib = Library(self.library_path)
File "/opt/python3.10.10/lib/python3.10/ctypes/__init__.py", line 374, in __init__
self._handle = _dlopen(self._name, mode)
OSError: @pyvisa_test.yaml@sim: cannot open shared object file: No such file or directory
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/google/home/dthor/.virtualenvs/pyle/bin/pyvisa-shell", line 8, in <module>
sys.exit(visa_shell())
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/cmd_line_tools.py", line 62, in visa_shell
visa_main("shell")
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/cmd_line_tools.py", line 53, in visa_main
shell.main("@" + args.backend if args.backend else "")
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/shell.py", line 387, in main
VisaShell(library_path).cmdloop()
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/shell.py", line 30, in __init__
self.resource_manager = ResourceManager(library_path)
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/highlevel.py", line 2992, in __new__
visa_library = open_visa_library(visa_library)
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/highlevel.py", line 2904, in open_visa_library
return cls(argument)
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/highlevel.py", line 191, in __new__
obj._init()
File "/usr/local/google/home/dthor/.virtualenvs/pyle/lib/python3.10/site-packages/pyvisa/ctwrapper/highlevel.py", line 164, in _init
raise errors.LibraryError.from_exception(exc, self.library_path)
pyvisa.errors.LibraryError: Error while accessing @pyvisa_test.yaml@sim: @pyvisa_test.yaml@sim: cannot open shared object file: No such file or directory
```
### Sim file
```yaml
# pyvisa_test.yaml
spec: "1.0"
devices:
device 1:
eom:
TCPIP SOCKET:
q: "\n"
r: "\n"
error: ERROR
dialogues:
- q: "*IDN?"
r: "Fake Instr"
resources:
TCPIP0::1.2.3.4::999::SOCKET:
device: device 1
```
---
**Output of `pyvisa-info`**
```console
$ pyvisa-info
Machine Details:
Platform ID: Linux-6.3.11-1rodete2-amd64-x86_64-with-glibc2.37
Processor:
Python:
Implementation: CPython
Executable: /usr/local/google/home/dthor/.virtualenvs/pyle/bin/python3
Version: 3.10.10
Compiler: GCC 10.2.1 20210110
Bits: 64bit
Build: Mar 7 2023 16:45:52 (#main)
Unicode: UCS4
PyVISA Version: 1.13.0
Backends:
ivi:
Version: 1.13.0 (bundled with PyVISA)
Binary library: Not found
py:
Version: 0.6.2
ASRL INSTR: Available via PySerial (3.5)
USB INSTR: Available via PyUSB (1.0.2). Backend: N/A
USB RAW: Available via PyUSB (1.0.2). Backend: N/A
TCPIP INSTR: Available
Resource discovery:
- VXI-11: ok
- hislip: ok
VICP INSTR:
Please install PyVICP to use this resource type.
TCPIP SOCKET: Available
GPIB INSTR:
Please install linux-gpib (Linux) or gpib-ctypes (Windows, Linux) to use this resource type. Note that installing gpib-ctypes will give you access to a broader range of funcionality.
No module named 'gpib'
sim:
Version: 0.5.1
Spec version: 1.1
```
|
0.0
|
088f591c37d9846821ebf99fe1af0e6c2cd500de
|
[
"pyvisa/testsuite/test_cmd_line_tools.py::test__create_backend_str[args0-]",
"pyvisa/testsuite/test_cmd_line_tools.py::test__create_backend_str[args1-@py]",
"pyvisa/testsuite/test_cmd_line_tools.py::test__create_backend_str[args2-foo.yaml@sim]",
"pyvisa/testsuite/test_cmd_line_tools.py::test__create_backend_str[args3-/foo/bar/baz.yaml@sim]",
"pyvisa/testsuite/test_cmd_line_tools.py::test__create_backend_str[args4-@sim]"
] |
[
"pyvisa/testsuite/test_cmd_line_tools.py::TestCmdLineTools::test_visa_main_argument_handling",
"pyvisa/testsuite/test_cmd_line_tools.py::TestCmdLineTools::test_visa_info"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-09-28 19:48:45+00:00
|
mit
| 5,129 |
|
pyvisa__pyvisa-780
|
diff --git a/pyvisa/rname.py b/pyvisa/rname.py
index 3c4ca0a..f383515 100644
--- a/pyvisa/rname.py
+++ b/pyvisa/rname.py
@@ -30,7 +30,7 @@ from . import constants, errors, logger
if TYPE_CHECKING:
from .resources import Resource # noqa # pragma: no cover
-#: Interface types for which a subclass of ResourName exists
+#: Interface types for which a subclass of ResourceName exists
_INTERFACE_TYPES: Set[str] = set()
#: Resource Class for Interface type
@@ -428,12 +428,13 @@ class VICPInstr(ResourceName):
"""VICP INSTR
The syntax is:
- VICP[board]::host address[::INSTR]
+ VICP::host address[::INSTR]
"""
- #: Board to use.
- board: str = "0"
+ #: VICP resource do not support a board index. But it is the only resource
+ #: in this case so we allow parsing one but set a default of ""
+ _unused: None = None
#: Host address of the device (IPv4 or host name)
host_address: str = ""
|
pyvisa/pyvisa
|
a9507e54eba892a968c47c19250771e65f05aab7
|
diff --git a/pyvisa/testsuite/test_rname.py b/pyvisa/testsuite/test_rname.py
index f4a3897..9a9ac85 100644
--- a/pyvisa/testsuite/test_rname.py
+++ b/pyvisa/testsuite/test_rname.py
@@ -300,8 +300,8 @@ class TestParsers(BaseTestCase):
interface_type="VICP",
resource_class="INSTR",
host_address="192.168.134.102",
- board="0",
- canonical_resource_name="VICP0::192.168.134.102::INSTR",
+ _unused=None,
+ canonical_resource_name="VICP::192.168.134.102::INSTR",
)
self._parse_test(
@@ -309,26 +309,26 @@ class TestParsers(BaseTestCase):
interface_type="VICP",
resource_class="INSTR",
host_address="dev.company.com",
- board="0",
- canonical_resource_name="VICP0::dev.company.com::INSTR",
+ _unused=None,
+ canonical_resource_name="VICP::dev.company.com::INSTR",
)
self._parse_test(
- "VICP3::dev.company.com::INSTR",
+ "VICP::dev.company.com::INSTR",
interface_type="VICP",
resource_class="INSTR",
host_address="dev.company.com",
- board="3",
- canonical_resource_name="VICP3::dev.company.com::INSTR",
+ _unused=None,
+ canonical_resource_name="VICP::dev.company.com::INSTR",
)
self._parse_test(
- "VICP3::1.2.3.4::INSTR",
+ "VICP::1.2.3.4::INSTR",
interface_type="VICP",
resource_class="INSTR",
host_address="1.2.3.4",
- board="3",
- canonical_resource_name="VICP3::1.2.3.4::INSTR",
+ _unused=None,
+ canonical_resource_name="VICP::1.2.3.4::INSTR",
)
def test_tcpip_socket(self):
|
VI_ERROR_RSRC_NFOUND while connecting to a LeCroy using VICP
I am trying to connect to a LeCroy Wavesurfer which is connected to my local network. First, I attempted this code:
`import visa`
`rm = visa.ResourceManager()`
`scope = rm.open_resource("VICP::192.168.122.53::INSTR")`
This throws out an error: pyvisa.errors.VisaIOError: VI_ERROR_RSRC_NFOUND (-1073807343): Insufficient location information or the requested device or resource is not present in the system.
I followed the bug report thread #168, but no luck. :( Likewise, I read through other related bug reports, as well as several StackOverflow threads, but nothing helped. I did manage to get other types of errors, but without understanding the problem, I don't really consider that an improvement.
I am using Python 3.5.1 with PyVISA 1.8 running on a Win8.1 computer. If needed, I can provide any other relevant information.
Thanks in advance.
|
0.0
|
a9507e54eba892a968c47c19250771e65f05aab7
|
[
"pyvisa/testsuite/test_rname.py::TestParsers::test_vicp_intr"
] |
[
"pyvisa/testsuite/test_rname.py::TestInvalidResourceName::test_bad_syntax",
"pyvisa/testsuite/test_rname.py::TestInvalidResourceName::test_subclass_notfound",
"pyvisa/testsuite/test_rname.py::TestInvalidResourceName::test_rc_notfound",
"pyvisa/testsuite/test_rname.py::TestRegisteringSubclass::test_handling_duplicate",
"pyvisa/testsuite/test_rname.py::TestRegisteringSubclass::test_handling_duplicate_default",
"pyvisa/testsuite/test_rname.py::TestResourceName::test_creation_from_string",
"pyvisa/testsuite/test_rname.py::TestResourceName::test_creation_from_kwargs",
"pyvisa/testsuite/test_rname.py::TestResourceName::test_accessing_interface_type",
"pyvisa/testsuite/test_rname.py::TestParsers::test_asrl",
"pyvisa/testsuite/test_rname.py::TestParsers::test_gpib_instr",
"pyvisa/testsuite/test_rname.py::TestParsers::test_gpib_intf",
"pyvisa/testsuite/test_rname.py::TestParsers::test_tcpip_intr",
"pyvisa/testsuite/test_rname.py::TestParsers::test_tcpip_socket",
"pyvisa/testsuite/test_rname.py::TestParsers::test_usb_instr",
"pyvisa/testsuite/test_rname.py::TestParsers::test_usb_raw",
"pyvisa/testsuite/test_rname.py::TestFilters::test_filter",
"pyvisa/testsuite/test_rname.py::TestFilters::test_filter2_no_optional_clause",
"pyvisa/testsuite/test_rname.py::TestFilters::test_filter2_optional_clause_no_connection",
"pyvisa/testsuite/test_rname.py::TestFilters::test_bad_filter",
"pyvisa/testsuite/test_rname.py::TestFilters::test_bad_filter2"
] |
{
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-24 06:55:40+00:00
|
mit
| 5,130 |
|
pyvisa__pyvisa-py-389
|
diff --git a/CHANGES b/CHANGES
index 6a454f7..8494603 100644
--- a/CHANGES
+++ b/CHANGES
@@ -7,6 +7,8 @@ PyVISA-py Changelog
- addd URL-support to ASLR devices PR #386
- add support for GPIB secondary addresses
- fix missing sock.close() in rpc _connect()
+- Adjusted how `iter_bytes` works to be more accurate to the VISA spec and removed
+ it from the `serial` module (it can still be found in `common`)
- fix HiSLIP message tracking after read timeout PR #376
- handle read_termination of null in tcipip PR #394
- fix tcpip keepalive PR #396
diff --git a/pyvisa_py/common.py b/pyvisa_py/common.py
index 884ba63..478042a 100644
--- a/pyvisa_py/common.py
+++ b/pyvisa_py/common.py
@@ -6,6 +6,7 @@
"""
import logging
+from typing import Iterator, Optional
from pyvisa import logger
@@ -28,3 +29,75 @@ class NamedObject(object):
int_to_byte = lambda val: val.to_bytes(1, "big")
+
+
+# TODO(anyone): This is copypasta from `pyvisa-sim` project - find a way to
+# reduce duplication, probably in that project instead of here.
+def _create_bitmask(bits: int) -> int:
+ """Create a bitmask for the given number of bits."""
+ mask = (1 << bits) - 1
+ return mask
+
+
+# TODO(anyone): This is copypasta from `pyvisa-sim` project - find a way to
+# reduce duplication, probably in that project instead of here.
+def iter_bytes(
+ data: bytes, data_bits: Optional[int] = None, send_end: Optional[bool] = None
+) -> Iterator[bytes]:
+ """Clip values to the correct number of bits per byte.
+ Serial communication may use from 5 to 8 bits.
+ Parameters
+ ----------
+ data : The data to clip as a byte string.
+ data_bits : How many bits per byte should be sent. Clip to this many bits.
+ For example: data_bits=5: 0xff (0b1111_1111) --> 0x1f (0b0001_1111).
+ Acceptable range is 5 to 8, inclusive. Values above 8 will be clipped to 8.
+ This maps to the VISA attribute VI_ATTR_ASRL_DATA_BITS.
+ send_end :
+ If None (the default), apply the mask that is determined by data_bits.
+ If False, apply the mask and set the highest (post-mask) bit to 0 for
+ all bytes.
+ If True, apply the mask and set the highest (post-mask) bit to 0 for
+ all bytes except for the final byte, which has the highest bit set to 1.
+ References
+ ----------
+ + https://www.ivifoundation.org/downloads/Architecture%20Specifications/vpp43_2022-05-19.pdf,
+ + https://www.ni.com/docs/en-US/bundle/ni-visa/page/ni-visa/vi_attr_asrl_data_bits.html,
+ + https://www.ni.com/docs/en-US/bundle/ni-visa/page/ni-visa/vi_attr_asrl_end_out.html
+
+ """
+ if send_end and data_bits is None:
+ raise ValueError("'send_end' requires a valid 'data_bits' value.")
+
+ if data_bits is None:
+ for d in data:
+ yield bytes([d])
+ else:
+ if data_bits <= 0:
+ raise ValueError("'data_bits' cannot be zero or negative")
+ if data_bits > 8:
+ data_bits = 8
+
+ if send_end is None:
+ # only apply the mask
+ mask = _create_bitmask(data_bits)
+ for d in data:
+ yield bytes([d & mask])
+ elif bool(send_end) is False:
+ # apply the mask and set highest bits to 0
+ # This is effectively the same has reducing the mask by 1 bit.
+ mask = _create_bitmask(data_bits - 1)
+ for d in data:
+ yield bytes([d & mask])
+ elif bool(send_end) is True:
+ # apply the mask and set highest bits to 0
+ # This is effectively the same has reducing the mask by 1 bit.
+ mask = _create_bitmask(data_bits - 1)
+ for d in data[:-1]:
+ yield bytes([d & mask])
+ # except for the last byte which has it's highest bit set to 1.
+ last_byte = data[-1]
+ highest_bit = 1 << (data_bits - 1)
+ yield bytes([(last_byte & mask) | highest_bit])
+ else:
+ raise ValueError(f"Unknown 'send_end' value '{send_end}'")
diff --git a/pyvisa_py/serial.py b/pyvisa_py/serial.py
index f438cf3..3319026 100644
--- a/pyvisa_py/serial.py
+++ b/pyvisa_py/serial.py
@@ -7,7 +7,7 @@
"""
import sys
-from typing import Any, List, Optional, Tuple
+from typing import Any, List, Tuple
from pyvisa import attributes, constants, logger, rname
from pyvisa.constants import (
@@ -34,24 +34,6 @@ except ImportError as e:
IS_WIN = sys.platform == "win32"
-def iter_bytes(data: bytes, mask: Optional[int] = None, send_end: bool = False):
- if send_end and mask is None:
- raise ValueError("send_end requires a valid mask.")
-
- if mask is None:
- for d in data:
- yield bytes([d])
-
- else:
- for d in data[:-1]:
- yield bytes([d & ~mask])
-
- if send_end:
- yield bytes([data[-1] | ~mask])
- else:
- yield bytes([data[-1] & ~mask])
-
-
def to_state(boolean_input: bool) -> constants.LineState:
"""Convert a boolean input into a LineState value."""
if boolean_input:
@@ -184,20 +166,20 @@ class SerialSession(Session):
"""
logger.debug("Serial.write %r" % data)
- end_out, _ = self.get_attribute(ResourceAttribute.asrl_end_out)
send_end, _ = self.get_attribute(ResourceAttribute.send_end_enabled)
+ end_out, _ = self.get_attribute(ResourceAttribute.asrl_end_out)
+ data_bits, _ = self.get_attribute(constants.ResourceAttribute.asrl_data_bits)
- if end_out in (SerialTermination.none, SerialTermination.termination_break):
+ if end_out == SerialTermination.none:
pass
elif end_out == SerialTermination.last_bit:
- last_bit, _ = self.get_attribute(ResourceAttribute.asrl_data_bits)
- mask = 1 << (last_bit - 1)
- data = bytes(iter_bytes(data, mask, send_end))
-
+ data = b"".join(common.iter_bytes(data, data_bits, send_end))
elif end_out == SerialTermination.termination_char:
term_char, _ = self.get_attribute(ResourceAttribute.termchar)
+ data = b"".join(common.iter_bytes(data, data_bits, send_end=None))
data = data + common.int_to_byte(term_char)
-
+ elif end_out == SerialTermination.termination_break:
+ data = b"".join(common.iter_bytes(data, data_bits, send_end=None))
else:
raise ValueError("Unknown value for VI_ATTR_ASRL_END_OUT: %s" % end_out)
|
pyvisa/pyvisa-py
|
ea7fa43edabcca496016c72e3e66209fa442144b
|
diff --git a/pyvisa_py/testsuite/test_common.py b/pyvisa_py/testsuite/test_common.py
new file mode 100644
index 0000000..a1f1b08
--- /dev/null
+++ b/pyvisa_py/testsuite/test_common.py
@@ -0,0 +1,102 @@
+from typing import List, Optional
+
+import pytest
+
+from pyvisa_py import common
+
+
+# TODO(anyone): This is copypasta from `pyvisa-sim` project - find a way to
+# reduce duplication, probably in that project instead of here.
[email protected](
+ "bits, want",
+ [
+ (0, 0b0),
+ (1, 0b1),
+ (5, 0b0001_1111),
+ (7, 0b0111_1111),
+ (8, 0b1111_1111),
+ (11, 0b0111_1111_1111),
+ ],
+)
+def test_create_bitmask(bits, want):
+ got = common._create_bitmask(bits)
+ assert got == want
+
+
+# TODO(anyone): This is copypasta from `pyvisa-sim` project - find a way to
+# reduce duplication, probably in that project instead of here.
[email protected](
+ "data, data_bits, send_end, want",
+ [
+ (b"\x01", None, False, b"\x01"),
+ (b"hello world!", None, False, b"hello world!"),
+ # Only apply the mask
+ (b"\x03", 2, None, b"\x03"), # 0b0000_0011 --> 0b0000_0011
+ (b"\x04", 2, None, b"\x00"), # 0b0000_0100 --> 0b0000_0000
+ (b"\xff", 5, None, b"\x1f"), # 0b1111_1111 --> 0b0001_1111
+ (b"\xfe", 7, None, b"\x7e"), # 0b1111_1110 --> 0b0111_1110
+ (b"\xfe", 8, None, b"\xfe"), # 0b1111_1110 --> 0b1111_1110
+ (b"\xff", 9, None, b"\xff"), # 0b1111_1111 --> 0b1111_1111
+ # Always set highest bit *of data_bits* to 0
+ (b"\x04", 2, False, b"\x00"), # 0b0000_0100 --> 0b0000_0000
+ (b"\x04", 3, False, b"\x00"), # 0b0000_0100 --> 0b0000_0000
+ (b"\x05", 3, False, b"\x01"), # 0b0000_0101 --> 0b0000_0001
+ (b"\xff", 7, False, b"\x3f"), # 0b1111_1111 --> 0b0011_1111
+ (b"\xff", 8, False, b"\x7f"), # 0b1111_1111 --> 0b0111_1111
+ # Always set highest bit *of data_bits* to 1
+ (b"\x04", 2, True, b"\x02"), # 0b0000_0100 --> 0b0000_0010
+ (b"\x04", 3, True, b"\x04"), # 0b0000_0100 --> 0b0000_0100
+ (b"\x01", 3, True, b"\x05"), # 0b0000_0001 --> 0b0000_0101
+ (b"\x9f", 7, True, b"\x5f"), # 0b1001_1111 --> 0b0101_1111
+ (b"\x9f", 8, True, b"\x9f"), # 0b1001_1111 --> 0b1001_1111
+ # data_bits >8 bits act like data_bits=8, as type(data) is "bytes"
+ # which is limited 8 bits per character.
+ (b"\xff", 9, None, b"\xff"),
+ (b"\xff", 9, False, b"\x7f"),
+ (b"\xff", 9, True, b"\xff"),
+ # send_end=None only applies the mask everywhere and doesn't touch the
+ # highest bit
+ # 0x6d: 0b0110_1101 (m) --> 0x0d: 0b0000_1101 (\r)
+ # 0x5e: 0b0101_1110 (^) --> 0x0e: 0b0000_1110
+ # 0x25: 0b0010_0101 (%) --> 0x05: 0b0000_0101
+ # 0x25: 0b0010_0101 (%) --> 0x05: 0b0000_0101
+ (b"\x6d\x5e\x25\x25", 4, None, b"\r\x0e\x05\x05"),
+ # send_end=False sets highest post-mask bit to 0 for all
+ # 0x6d: 0b0110_1101 (m) --> 0x05: 0b0000_0101
+ # 0x5e: 0b0101_1110 (^) --> 0x06: 0b0000_0110
+ # 0x25: 0b0010_0101 (%) --> 0x05: 0b0000_0101
+ # 0x25: 0b0010_0101 (%) --> 0x05: 0b0000_0101
+ (b"\x6d\x5e\x25\x25", 4, False, b"\x05\x06\x05\x05"),
+ # send_end=True sets highest bit to 0 except for final byte
+ # 0x6d: 0b0110_1101 (m) --> 0x05: 0b0000_0101
+ # 0x5e: 0b0101_1110 (^) --> 0x06: 0b0000_0110
+ # 0x25: 0b0010_0101 (%) --> 0x05: 0b0000_0101
+ # 0x25: 0b0010_0101 (%) --> 0x0d: 0b0000_1101
+ (b"\x6d\x5e\x25\x25", 4, True, b"\x05\x06\x05\x0d"),
+ # 0x61: 0b0110_0001 (a) --> 0x21: 0b0010_0001 (!)
+ # 0xb1: 0b1011_0001 (±) --> 0x31: 0b0011_0001 (1)
+ (b"a\xb1", 6, None, b"\x21\x31"),
+ # 0x61: 0b0110_0001 (a) --> 0x01: 0b0000_0001
+ # 0xb1: 0b1011_0001 (±) --> 0x11: 0b0001_0001
+ (b"a\xb1", 6, False, b"\x01\x11"),
+ # 0x61: 0b0110_0001 (a) --> 0x01: 0b0000_0001
+ # 0xb1: 0b1011_0001 (±) --> 0x31: 0b0011_0001 (1)
+ (b"a\xb1", 6, True, b"\x011"),
+ ],
+)
+def test_iter_bytes(
+ data: bytes, data_bits: Optional[int], send_end: bool, want: List[bytes]
+) -> None:
+ got = b"".join(common.iter_bytes(data, data_bits=data_bits, send_end=send_end))
+ assert got == want
+
+
+def test_iter_bytes_with_send_end_requires_data_bits() -> None:
+ with pytest.raises(ValueError):
+ # Need to wrap in list otherwise the iterator is never called.
+ list(common.iter_bytes(b"", data_bits=None, send_end=True))
+
+
+def test_iter_bytes_raises_on_bad_data_bits() -> None:
+ with pytest.raises(ValueError):
+ list(common.iter_bytes(b"", data_bits=0, send_end=None))
|
Port pyvisa-sim `iter_bytes` changes for serial communication
https://github.com/pyvisa/pyvisa-sim/pull/81#issuecomment-1567565412
/assign @dougthor42
|
0.0
|
ea7fa43edabcca496016c72e3e66209fa442144b
|
[
"pyvisa_py/testsuite/test_common.py::test_create_bitmask[0-0]",
"pyvisa_py/testsuite/test_common.py::test_create_bitmask[1-1]",
"pyvisa_py/testsuite/test_common.py::test_create_bitmask[5-31]",
"pyvisa_py/testsuite/test_common.py::test_create_bitmask[7-127]",
"pyvisa_py/testsuite/test_common.py::test_create_bitmask[8-255]",
"pyvisa_py/testsuite/test_common.py::test_create_bitmask[11-2047]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x01-None-False-\\x01]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[hello",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x03-2-None-\\x03]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x04-2-None-\\x00]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xff-5-None-\\x1f]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xfe-7-None-~]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xfe-8-None-\\xfe]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xff-9-None-\\xff0]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x04-2-False-\\x00]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x04-3-False-\\x00]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x05-3-False-\\x01]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xff-7-False-?]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xff-8-False-\\x7f]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x04-2-True-\\x02]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x04-3-True-\\x04]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x01-3-True-\\x05]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x9f-7-True-_]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\x9f-8-True-\\x9f]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xff-9-None-\\xff1]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xff-9-False-\\x7f]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[\\xff-9-True-\\xff]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[m^%%-4-None-\\r\\x0e\\x05\\x05]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[m^%%-4-False-\\x05\\x06\\x05\\x05]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[m^%%-4-True-\\x05\\x06\\x05\\r]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[a\\xb1-6-None-!1]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[a\\xb1-6-False-\\x01\\x11]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes[a\\xb1-6-True-\\x011]",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes_with_send_end_requires_data_bits",
"pyvisa_py/testsuite/test_common.py::test_iter_bytes_raises_on_bad_data_bits"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-06 18:01:30+00:00
|
mit
| 5,131 |
|
qiboteam__qibo-1022
|
diff --git a/src/qibo/backends/numpy.py b/src/qibo/backends/numpy.py
index b540fa487..b0447bd56 100644
--- a/src/qibo/backends/numpy.py
+++ b/src/qibo/backends/numpy.py
@@ -256,9 +256,11 @@ class NumpyBackend(Backend):
return np.reshape(state, 2 * (2**nqubits,))
def apply_channel(self, channel, state, nqubits):
- for coeff, gate in zip(channel.coefficients, channel.gates):
- if self.np.random.random() < coeff:
- state = self.apply_gate(gate, state, nqubits)
+ probabilities = channel.coefficients + (1 - np.sum(channel.coefficients),)
+ index = self.sample_shots(probabilities, 1)[0]
+ if index != len(channel.gates):
+ gate = channel.gates[index]
+ state = self.apply_gate(gate, state, nqubits)
return state
def apply_channel_density_matrix(self, channel, state, nqubits):
|
qiboteam/qibo
|
f00ed7c1c38aa3869f5e2277f2af136e93ac7c8b
|
diff --git a/tests/test_measurements_probabilistic.py b/tests/test_measurements_probabilistic.py
index f15fefc93..2d520516a 100644
--- a/tests/test_measurements_probabilistic.py
+++ b/tests/test_measurements_probabilistic.py
@@ -83,14 +83,15 @@ def test_measurements_with_probabilistic_noise(backend):
backend.set_seed(123)
target_samples = []
+ channel_gates = [gates.Y, gates.Z]
+ probs = [0.2, 0.4, 0.4]
for _ in range(20):
noiseless_c = models.Circuit(5)
noiseless_c.add((gates.RX(i, t) for i, t in enumerate(thetas)))
for i in range(5):
- if backend.np.random.random() < 0.2:
- noiseless_c.add(gates.Y(i))
- if backend.np.random.random() < 0.4:
- noiseless_c.add(gates.Z(i))
+ index = backend.sample_shots(probs, 1)[0]
+ if index != len(channel_gates):
+ noiseless_c.add(channel_gates[index](i))
noiseless_c.add(gates.M(*range(5)))
result = backend.execute_circuit(noiseless_c, nshots=1)
target_samples.append(backend.to_numpy(result.samples()))
diff --git a/tests/test_models_circuit_features.py b/tests/test_models_circuit_features.py
index dc3d5fb1a..9d22f98ce 100644
--- a/tests/test_models_circuit_features.py
+++ b/tests/test_models_circuit_features.py
@@ -277,16 +277,15 @@ def test_repeated_execute_pauli_noise_channel(backend):
backend.set_seed(1234)
target_state = []
+ channel_gates = [gates.X, gates.Y, gates.Z]
+ probs = [0.1, 0.2, 0.3, 0.4]
for _ in range(20):
noiseless_c = Circuit(4)
noiseless_c.add((gates.RY(i, t) for i, t in enumerate(thetas)))
for i in range(4):
- if backend.np.random.random() < 0.1:
- noiseless_c.add(gates.X(i))
- if backend.np.random.random() < 0.2:
- noiseless_c.add(gates.Y(i))
- if backend.np.random.random() < 0.3:
- noiseless_c.add(gates.Z(i))
+ index = backend.sample_shots(probs, 1)[0]
+ if index != len(channel_gates):
+ noiseless_c.add(channel_gates[index](i))
result = backend.execute_circuit(noiseless_c)
target_state.append(result.state(numpy=True))
final_state = [backend.to_numpy(x) for x in final_state]
@@ -304,14 +303,15 @@ def test_repeated_execute_with_pauli_noise(backend):
backend.set_seed(1234)
target_state = []
+ channel_gates = [gates.X, gates.Z]
+ probs = [0.2, 0.1, 0.7]
for _ in range(20):
noiseless_c = Circuit(4)
for i, t in enumerate(thetas):
noiseless_c.add(gates.RY(i, theta=t))
- if backend.np.random.random() < 0.2:
- noiseless_c.add(gates.X(i))
- if backend.np.random.random() < 0.1:
- noiseless_c.add(gates.Z(i))
+ index = backend.sample_shots(probs, 1)[0]
+ if index != len(channel_gates):
+ noiseless_c.add(channel_gates[index](i))
result = backend.execute_circuit(noiseless_c)
target_state.append(result.state(numpy=True))
target_state = np.stack(target_state)
@@ -336,21 +336,20 @@ def test_repeated_execute_probs_and_freqs(backend, nqubits):
# Tensorflow seems to yield different results with same seed
if backend.__class__.__name__ == "TensorflowBackend":
if nqubits == 1:
- test_probabilities = [0.171875, 0.828125]
- test_frequencies = Counter({1: 848, 0: 176})
+ test_probabilities = [0.17578125, 0.82421875]
+ test_frequencies = Counter({1: 844, 0: 180})
else:
- test_probabilities = [0.04101562, 0.12695312, 0.140625, 0.69140625]
- test_frequencies = Counter({11: 708, 10: 144, 1: 130, 0: 42})
+ test_probabilities = [0.04003906, 0.15039062, 0.15136719, 0.65820312]
+ test_frequencies = Counter({11: 674, 10: 155, 1: 154, 0: 41})
else:
if nqubits == 1:
- test_probabilities = [0.20117188, 0.79882812]
- test_frequencies = Counter({"1": 818, "0": 206})
+ test_probabilities = [0.22851562, 0.77148438]
+ test_frequencies = Counter({"1": 790, "0": 234})
else:
- test_probabilities = [0.0390625, 0.16113281, 0.17382812, 0.62597656]
- test_frequencies = Counter({"11": 641, "10": 178, "01": 165, "00": 40})
+ test_probabilities = [0.05078125, 0.18066406, 0.16503906, 0.60351562]
+ test_frequencies = Counter({"11": 618, "10": 169, "01": 185, "00": 52})
test_probabilities = backend.cast(test_probabilities, dtype=float)
-
print(result.probabilities())
backend.assert_allclose(
backend.calculate_norm(result.probabilities() - test_probabilities)
diff --git a/tests/test_models_circuit_noise.py b/tests/test_models_circuit_noise.py
index 1fe77462d..d4fdb96f1 100644
--- a/tests/test_models_circuit_noise.py
+++ b/tests/test_models_circuit_noise.py
@@ -2,8 +2,9 @@
import numpy as np
import pytest
-import qibo
from qibo import Circuit, gates
+from qibo.config import PRECISION_TOL
+from qibo.quantum_info import random_clifford, random_statevector, random_unitary
def test_pauli_noise_channel(backend):
@@ -198,3 +199,38 @@ def test_circuit_add_sampling(backend):
target_samples = np.stack(target_samples)
backend.assert_allclose(samples, target_samples[:, 0])
+
+
[email protected]("nqubits", [2, 4, 6])
+def test_probabilities_repeated_execution(backend, nqubits):
+ probabilities = list(np.random.rand(nqubits + 1)) + [1.0]
+ probabilities /= np.sum(probabilities)
+
+ unitaries = [random_unitary(2**1, backend=backend) for _ in range(nqubits)]
+ unitaries += [random_unitary(2**nqubits, backend=backend)]
+
+ qubits_list = [(q,) for q in range(nqubits)]
+ qubits_list += [tuple(q for q in range(nqubits))]
+
+ circuit = random_clifford(nqubits, return_circuit=True, backend=backend)
+ circuit.add(gates.UnitaryChannel(qubits_list, list(zip(probabilities, unitaries))))
+ circuit.add(gates.M(*range(nqubits)))
+
+ circuit_density_matrix = circuit.copy(deep=True)
+ circuit_density_matrix.density_matrix = True
+
+ statevector = random_statevector(2**nqubits, backend=backend)
+
+ result = backend.execute_circuit_repeated(
+ circuit, initial_state=statevector, nshots=int(1e4)
+ )
+ result = result.probabilities()
+
+ result_density_matrix = backend.execute_circuit(
+ circuit_density_matrix,
+ initial_state=np.outer(statevector, np.conj(statevector)),
+ nshots=int(1e4),
+ )
+ result_density_matrix = result_density_matrix.probabilities()
+
+ backend.assert_allclose(result, result_density_matrix, rtol=2e-2, atol=5e-3)
|
`DepolarizingChannel` gives wrong probabilities when used with state vectors
**Describe the bug**
The `DepolarizingChannel` with `lam=1` on a single qubit should give 0.5 probability for both 0 and 1 but gives 0.6 - 0.4.
The problem does not appear when using density matrices.
**To Reproduce**
```py
from qibo import Circuit, gates
nqubits = 1
qc = Circuit(nqubits)
lam = 1
qc.add(gates.DepolarizingChannel([0,], lam))
qc.add(gates.M(0))
# Execute circuit
result = qc.execute(nshots=10000)
counts = dict(result.frequencies(binary=True))
print(counts)
```
**Expected behavior**
Gives `{'0': 6316, '1': 3684}`.
When using `qc = Circuit(nqubits, density_matrix=True)` it gives `{'0': 5035, '1': 4965}` which is more right.
|
0.0
|
f00ed7c1c38aa3869f5e2277f2af136e93ac7c8b
|
[
"tests/test_measurements_probabilistic.py::test_measurements_with_probabilistic_noise[numpy]",
"tests/test_models_circuit_features.py::test_repeated_execute_pauli_noise_channel[numpy]",
"tests/test_models_circuit_features.py::test_repeated_execute_with_pauli_noise[numpy]",
"tests/test_models_circuit_noise.py::test_probabilities_repeated_execution[numpy-4]"
] |
[
"tests/test_measurements_probabilistic.py::test_probabilistic_measurement[numpy-None-True]",
"tests/test_measurements_probabilistic.py::test_probabilistic_measurement[numpy-None-False]",
"tests/test_measurements_probabilistic.py::test_sample_frequency_agreement[numpy]",
"tests/test_measurements_probabilistic.py::test_unbalanced_probabilistic_measurement[numpy-True]",
"tests/test_measurements_probabilistic.py::test_unbalanced_probabilistic_measurement[numpy-False]",
"tests/test_measurements_probabilistic.py::test_post_measurement_bitflips_on_circuit[numpy-None-0-probs0]",
"tests/test_measurements_probabilistic.py::test_post_measurement_bitflips_on_circuit[numpy-None-1-probs1]",
"tests/test_measurements_probabilistic.py::test_post_measurement_bitflips_on_circuit[numpy-None-2-probs2]",
"tests/test_measurements_probabilistic.py::test_post_measurement_bitflips_on_circuit_result[numpy]",
"tests/test_measurements_probabilistic.py::test_measurementresult_apply_bitflips[numpy-0-0.2-None]",
"tests/test_measurements_probabilistic.py::test_measurementresult_apply_bitflips[numpy-1-0.2-0.1]",
"tests/test_measurements_probabilistic.py::test_measurementresult_apply_bitflips[numpy-2-p02-None]",
"tests/test_measurements_probabilistic.py::test_measurementresult_apply_bitflips[numpy-3-p03-None]",
"tests/test_models_circuit_features.py::test_circuit_unitary[numpy]",
"tests/test_models_circuit_features.py::test_circuit_unitary_bigger[numpy-False]",
"tests/test_models_circuit_features.py::test_circuit_unitary_bigger[numpy-True]",
"tests/test_models_circuit_features.py::test_circuit_vs_gate_execution[numpy-False]",
"tests/test_models_circuit_features.py::test_circuit_vs_gate_execution[numpy-True]",
"tests/test_models_circuit_features.py::test_circuit_addition_execution[numpy-None]",
"tests/test_models_circuit_features.py::test_copied_circuit_execution[numpy-None-False]",
"tests/test_models_circuit_features.py::test_copied_circuit_execution[numpy-None-True]",
"tests/test_models_circuit_features.py::test_inverse_circuit_execution[numpy-None-False]",
"tests/test_models_circuit_features.py::test_inverse_circuit_execution[numpy-None-True]",
"tests/test_models_circuit_features.py::test_circuit_invert_and_addition_execution[numpy-None]",
"tests/test_models_circuit_features.py::test_circuit_on_qubits_execution[numpy-None-False]",
"tests/test_models_circuit_features.py::test_circuit_on_qubits_execution[numpy-None-True]",
"tests/test_models_circuit_features.py::test_circuit_on_qubits_double_execution[numpy-None-False]",
"tests/test_models_circuit_features.py::test_circuit_on_qubits_double_execution[numpy-None-True]",
"tests/test_models_circuit_features.py::test_circuit_on_qubits_controlled_by_execution[numpy-None]",
"tests/test_models_circuit_features.py::test_circuit_decompose_execution[numpy]",
"tests/test_models_circuit_noise.py::test_pauli_noise_channel[numpy]",
"tests/test_models_circuit_noise.py::test_noisy_circuit_reexecution[numpy]",
"tests/test_models_circuit_noise.py::test_circuit_with_pauli_noise_gates",
"tests/test_models_circuit_noise.py::test_circuit_with_pauli_noise_execution[numpy]",
"tests/test_models_circuit_noise.py::test_circuit_with_pauli_noise_measurements[numpy]",
"tests/test_models_circuit_noise.py::test_circuit_with_pauli_noise_noise_map[numpy]",
"tests/test_models_circuit_noise.py::test_circuit_with_pauli_noise_errors",
"tests/test_models_circuit_noise.py::test_density_matrix_circuit_measurement[numpy]",
"tests/test_models_circuit_noise.py::test_circuit_add_sampling[numpy]",
"tests/test_models_circuit_noise.py::test_probabilities_repeated_execution[numpy-2]",
"tests/test_models_circuit_noise.py::test_probabilities_repeated_execution[numpy-6]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-09-28 16:25:43+00:00
|
apache-2.0
| 5,132 |
|
qiboteam__qibo-1038
|
diff --git a/doc/source/appendix/citing-qibo.rst b/doc/source/appendix/citing-qibo.rst
index 179bbcd47..40f8a3b45 100644
--- a/doc/source/appendix/citing-qibo.rst
+++ b/doc/source/appendix/citing-qibo.rst
@@ -73,6 +73,12 @@ Peer-Reviewed Articles
.. _`arXiv:2308.06313`: https://arxiv.org/abs/2308.06313
+* R. Carobene, A. Candido, J. Serrano, A.O-Fuertes, A. Giachero, S. Carrazza,
+ *Qibosoq: an open-source framework for quantum circuit RFSoC programming*
+ (2023), (`arXiv:2310.05851`_)
+
+.. _`arXiv:2310.05851`: https://arxiv.org/abs/2310.05851
+
Software References in Zenodo
-----------------------------
@@ -102,6 +108,11 @@ Software References in Zenodo
.. _`https://doi.org/10.5281/zenodo.7662185`: https://doi.org/10.5281/zenodo.7662185
+* R. Carobene, A. Candido, J. Serrano, S. Carrazza, E. Pedicillo. (2023).
+ qiboteam/qibosoq: Qibosoq. Zenodo. `https://doi.org/10.5281/zenodo.8083285`_.
+
+.. _`https://doi.org/10.5281/zenodo.8083285`: https://doi.org/10.5281/zenodo.8083285
+
Conference Proceedings
diff --git a/src/qibo/gates/gates.py b/src/qibo/gates/gates.py
index ecda9aafc..da72791fe 100644
--- a/src/qibo/gates/gates.py
+++ b/src/qibo/gates/gates.py
@@ -255,7 +255,9 @@ class SX(Gate):
return "sx"
def decompose(self):
- """A global phase difference exists between the definitions of
+ """Decomposition of :math:`\\sqrt{X}` up to global phase.
+
+ A global phase difference exists between the definitions of
:math:`\\sqrt{X}` and :math:`\\text{RX}(\\pi / 2)`, with :math:`\\text{RX}`
being the :class:`qibo.gates.RX` gate. More precisely,
:math:`\\sqrt{X} = e^{i \\pi / 4} \\, \\text{RX}(\\pi / 2)`.
@@ -296,7 +298,9 @@ class SXDG(Gate):
return "sxdg"
def decompose(self):
- """A global phase difference exists between the definitions of
+ """Decomposition of :math:`(\\sqrt{X})^{\\dagger}` up to global phase.
+
+ A global phase difference exists between the definitions of
:math:`\\sqrt{X}` and :math:`\\text{RX}(\\pi / 2)`, with :math:`\\text{RX}`
being the :class:`qibo.gates.RX` gate. More precisely,
:math:`(\\sqrt{X})^{\\dagger} = e^{-i \\pi / 4} \\, \\text{RX}(-\\pi / 2)`.
@@ -864,6 +868,29 @@ class U3(_Un_):
theta, lam, phi = tuple(-x for x in self.parameters) # pylint: disable=E1130
return self.__class__(self.target_qubits[0], theta, phi, lam)
+ def decompose(self) -> List[Gate]:
+ """Decomposition of :math:`U_{3}` up to global phase.
+
+ A global phase difference exists between the definitions of
+ :math:`U3` and this decomposition. More precisely,
+
+ .. math::
+ U_{3}(\\theta, \\phi, \\lambda) = e^{i \\, \\frac{3 \\pi}{2}}
+ \\, \\text{RZ}(\\phi + \\pi) \\, \\sqrt{X} \\, \\text{RZ}(\\theta + \\pi)
+ \\, \\sqrt{X} \\, \\text{RZ}(\\lambda) \\, ,
+
+ where :math:`\\text{RZ}` and :math:`\\sqrt{X}` are, respectively,
+ :class:`qibo.gates.RZ` and :class`qibo.gates.SX`.
+ """
+ q = self.init_args[0]
+ return [
+ RZ(q, self.init_kwargs["lam"]),
+ SX(q),
+ RZ(q, self.init_kwargs["theta"] + math.pi),
+ SX(q),
+ RZ(q, self.init_kwargs["phi"] + math.pi),
+ ]
+
class CNOT(Gate):
"""The Controlled-NOT gate.
@@ -934,6 +961,15 @@ class CZ(Gate):
def qasm_label(self):
return "cz"
+ def decompose(self) -> List[Gate]:
+ """Decomposition of :math:`\\text{CZ}` gate.
+
+ Decompose :math:`\\text{CZ}` gate into :class:`qibo.gates.H` in the target qubit,
+ followed by :class:`qibo.gates.CNOT`, followed by another :class:`qibo.gates.H`
+ in the target qubit"""
+ q0, q1 = self.init_args
+ return [H(q1), CNOT(q0, q1), H(q1)]
+
class CSX(Gate):
"""The Controlled-:math:`\\sqrt{X}` gate.
@@ -1739,7 +1775,9 @@ class RXY(_Rnn_):
self.draw_label = "RXY"
def decompose(self, *free, use_toffolis: bool = True) -> List[Gate]:
- """This decomposition has a global phase difference with respect to the
+ """Decomposition of :math:`\\text{R_{XY}}` up to global phase.
+
+ This decomposition has a global phase difference with respect to the
original gate due to a phase difference in :math:`\\left(\\sqrt{X}\\right)^{\\dagger}`.
"""
q0, q1 = self.target_qubits
|
qiboteam/qibo
|
f6b0c2e51795fa00759279ded42dc14a01bda847
|
diff --git a/tests/test_gates_gates.py b/tests/test_gates_gates.py
index 60db57a4a..08b230c90 100644
--- a/tests/test_gates_gates.py
+++ b/tests/test_gates_gates.py
@@ -394,15 +394,24 @@ def test_u2(backend):
assert gates.U2(0, phi, lam).unitary
-def test_u3(backend):
- theta = 0.1111
- phi = 0.1234
- lam = 0.4321
[email protected]("seed_observable", list(range(1, 10 + 1)))
[email protected]("seed_state", list(range(1, 10 + 1)))
+def test_u3(backend, seed_state, seed_observable):
nqubits = 1
- initial_state = random_statevector(2**nqubits, backend=backend)
+ theta, phi, lam = np.random.rand(3)
+
+ initial_state = random_statevector(2**nqubits, seed=seed_state, backend=backend)
final_state = apply_gates(
backend, [gates.U3(0, theta, phi, lam)], initial_state=initial_state
)
+ # test decomposition
+ final_state_decompose = apply_gates(
+ backend,
+ gates.U3(0, theta, phi, lam).decompose(),
+ nqubits=nqubits,
+ initial_state=initial_state,
+ )
+
cost, sint = np.cos(theta / 2), np.sin(theta / 2)
ep = np.exp(1j * (phi + lam) / 2)
em = np.exp(1j * (phi - lam) / 2)
@@ -414,6 +423,15 @@ def test_u3(backend):
backend.assert_allclose(final_state, target_state)
+ # testing random expectation value due to global phase difference
+ observable = random_hermitian(2**nqubits, seed=seed_observable, backend=backend)
+ backend.assert_allclose(
+ np.transpose(np.conj(final_state_decompose))
+ @ observable
+ @ final_state_decompose,
+ np.transpose(np.conj(target_state)) @ observable @ target_state,
+ )
+
assert gates.U3(0, theta, phi, lam).qasm_label == "u3"
assert not gates.U3(0, theta, phi, lam).clifford
assert gates.U3(0, theta, phi, lam).unitary
@@ -436,15 +454,24 @@ def test_cnot(backend, applyx):
assert gates.CNOT(0, 1).unitary
[email protected]("seed_observable", list(range(1, 10 + 1)))
[email protected]("seed_state", list(range(1, 10 + 1)))
@pytest.mark.parametrize("controlled_by", [False, True])
-def test_cz(backend, controlled_by):
+def test_cz(backend, controlled_by, seed_state, seed_observable):
nqubits = 2
- initial_state = random_statevector(2**nqubits, backend=backend)
+ initial_state = random_statevector(2**nqubits, seed=seed_state, backend=backend)
matrix = np.eye(4)
matrix[3, 3] = -1
matrix = backend.cast(matrix, dtype=matrix.dtype)
target_state = np.dot(matrix, initial_state)
+ # test decomposition
+ final_state_decompose = apply_gates(
+ backend,
+ gates.CZ(0, 1).decompose(),
+ nqubits=nqubits,
+ initial_state=initial_state,
+ )
if controlled_by:
gate = gates.Z(1).controlled_by(0)
@@ -457,6 +484,15 @@ def test_cz(backend, controlled_by):
backend.assert_allclose(final_state, target_state)
+ # testing random expectation value due to global phase difference
+ observable = random_hermitian(2**nqubits, seed=seed_observable, backend=backend)
+ backend.assert_allclose(
+ np.transpose(np.conj(final_state_decompose))
+ @ observable
+ @ final_state_decompose,
+ np.transpose(np.conj(target_state)) @ observable @ target_state,
+ )
+
assert gates.CZ(0, 1).qasm_label == "cz"
assert gates.CZ(0, 1).clifford
assert gates.CZ(0, 1).unitary
|
Add reference to qibosoq paper
https://arxiv.org/abs/2310.05851
|
0.0
|
f6b0c2e51795fa00759279ded42dc14a01bda847
|
[
"tests/test_gates_gates.py::test_rx[numpy-0.6726026656995493]",
"tests/test_gates_gates.py::test_ry[numpy-0.032248563926263296]",
"tests/test_gates_gates.py::test_rz[numpy-0.5034176364236059-True]",
"tests/test_gates_gates.py::test_rz[numpy-0.5034176364236059-False]"
] |
[
"tests/test_gates_gates.py::test_h[numpy]",
"tests/test_gates_gates.py::test_x[numpy]",
"tests/test_gates_gates.py::test_y[numpy]",
"tests/test_gates_gates.py::test_z[numpy]",
"tests/test_gates_gates.py::test_sx[numpy]",
"tests/test_gates_gates.py::test_sxdg[numpy]",
"tests/test_gates_gates.py::test_s[numpy]",
"tests/test_gates_gates.py::test_sdg[numpy]",
"tests/test_gates_gates.py::test_t[numpy]",
"tests/test_gates_gates.py::test_tdg[numpy]",
"tests/test_gates_gates.py::test_identity[numpy]",
"tests/test_gates_gates.py::test_align[numpy]",
"tests/test_gates_gates.py::test_rx[numpy-1.5707963267948966]",
"tests/test_gates_gates.py::test_rx[numpy--1.5707963267948966]",
"tests/test_gates_gates.py::test_rx[numpy-3.141592653589793]",
"tests/test_gates_gates.py::test_ry[numpy-1.5707963267948966]",
"tests/test_gates_gates.py::test_ry[numpy--1.5707963267948966]",
"tests/test_gates_gates.py::test_ry[numpy-3.141592653589793]",
"tests/test_gates_gates.py::test_rz[numpy-1.5707963267948966-True]",
"tests/test_gates_gates.py::test_rz[numpy-1.5707963267948966-False]",
"tests/test_gates_gates.py::test_rz[numpy--1.5707963267948966-True]",
"tests/test_gates_gates.py::test_rz[numpy--1.5707963267948966-False]",
"tests/test_gates_gates.py::test_rz[numpy-3.141592653589793-True]",
"tests/test_gates_gates.py::test_rz[numpy-3.141592653589793-False]",
"tests/test_gates_gates.py::test_gpi[numpy]",
"tests/test_gates_gates.py::test_gpi2[numpy]",
"tests/test_gates_gates.py::test_u1[numpy]",
"tests/test_gates_gates.py::test_u2[numpy]",
"tests/test_gates_gates.py::test_u3[numpy-1-1]",
"tests/test_gates_gates.py::test_u3[numpy-1-2]",
"tests/test_gates_gates.py::test_u3[numpy-1-3]",
"tests/test_gates_gates.py::test_u3[numpy-1-4]",
"tests/test_gates_gates.py::test_u3[numpy-1-5]",
"tests/test_gates_gates.py::test_u3[numpy-1-6]",
"tests/test_gates_gates.py::test_u3[numpy-1-7]",
"tests/test_gates_gates.py::test_u3[numpy-1-8]",
"tests/test_gates_gates.py::test_u3[numpy-1-9]",
"tests/test_gates_gates.py::test_u3[numpy-1-10]",
"tests/test_gates_gates.py::test_u3[numpy-2-1]",
"tests/test_gates_gates.py::test_u3[numpy-2-2]",
"tests/test_gates_gates.py::test_u3[numpy-2-3]",
"tests/test_gates_gates.py::test_u3[numpy-2-4]",
"tests/test_gates_gates.py::test_u3[numpy-2-5]",
"tests/test_gates_gates.py::test_u3[numpy-2-6]",
"tests/test_gates_gates.py::test_u3[numpy-2-7]",
"tests/test_gates_gates.py::test_u3[numpy-2-8]",
"tests/test_gates_gates.py::test_u3[numpy-2-9]",
"tests/test_gates_gates.py::test_u3[numpy-2-10]",
"tests/test_gates_gates.py::test_u3[numpy-3-1]",
"tests/test_gates_gates.py::test_u3[numpy-3-2]",
"tests/test_gates_gates.py::test_u3[numpy-3-3]",
"tests/test_gates_gates.py::test_u3[numpy-3-4]",
"tests/test_gates_gates.py::test_u3[numpy-3-5]",
"tests/test_gates_gates.py::test_u3[numpy-3-6]",
"tests/test_gates_gates.py::test_u3[numpy-3-7]",
"tests/test_gates_gates.py::test_u3[numpy-3-8]",
"tests/test_gates_gates.py::test_u3[numpy-3-9]",
"tests/test_gates_gates.py::test_u3[numpy-3-10]",
"tests/test_gates_gates.py::test_u3[numpy-4-1]",
"tests/test_gates_gates.py::test_u3[numpy-4-2]",
"tests/test_gates_gates.py::test_u3[numpy-4-3]",
"tests/test_gates_gates.py::test_u3[numpy-4-4]",
"tests/test_gates_gates.py::test_u3[numpy-4-5]",
"tests/test_gates_gates.py::test_u3[numpy-4-6]",
"tests/test_gates_gates.py::test_u3[numpy-4-7]",
"tests/test_gates_gates.py::test_u3[numpy-4-8]",
"tests/test_gates_gates.py::test_u3[numpy-4-9]",
"tests/test_gates_gates.py::test_u3[numpy-4-10]",
"tests/test_gates_gates.py::test_u3[numpy-5-1]",
"tests/test_gates_gates.py::test_u3[numpy-5-2]",
"tests/test_gates_gates.py::test_u3[numpy-5-3]",
"tests/test_gates_gates.py::test_u3[numpy-5-4]",
"tests/test_gates_gates.py::test_u3[numpy-5-5]",
"tests/test_gates_gates.py::test_u3[numpy-5-6]",
"tests/test_gates_gates.py::test_u3[numpy-5-7]",
"tests/test_gates_gates.py::test_u3[numpy-5-8]",
"tests/test_gates_gates.py::test_u3[numpy-5-9]",
"tests/test_gates_gates.py::test_u3[numpy-5-10]",
"tests/test_gates_gates.py::test_u3[numpy-6-1]",
"tests/test_gates_gates.py::test_u3[numpy-6-2]",
"tests/test_gates_gates.py::test_u3[numpy-6-3]",
"tests/test_gates_gates.py::test_u3[numpy-6-4]",
"tests/test_gates_gates.py::test_u3[numpy-6-5]",
"tests/test_gates_gates.py::test_u3[numpy-6-6]",
"tests/test_gates_gates.py::test_u3[numpy-6-7]",
"tests/test_gates_gates.py::test_u3[numpy-6-8]",
"tests/test_gates_gates.py::test_u3[numpy-6-9]",
"tests/test_gates_gates.py::test_u3[numpy-6-10]",
"tests/test_gates_gates.py::test_u3[numpy-7-1]",
"tests/test_gates_gates.py::test_u3[numpy-7-2]",
"tests/test_gates_gates.py::test_u3[numpy-7-3]",
"tests/test_gates_gates.py::test_u3[numpy-7-4]",
"tests/test_gates_gates.py::test_u3[numpy-7-5]",
"tests/test_gates_gates.py::test_u3[numpy-7-6]",
"tests/test_gates_gates.py::test_u3[numpy-7-7]",
"tests/test_gates_gates.py::test_u3[numpy-7-8]",
"tests/test_gates_gates.py::test_u3[numpy-7-9]",
"tests/test_gates_gates.py::test_u3[numpy-7-10]",
"tests/test_gates_gates.py::test_u3[numpy-8-1]",
"tests/test_gates_gates.py::test_u3[numpy-8-2]",
"tests/test_gates_gates.py::test_u3[numpy-8-3]",
"tests/test_gates_gates.py::test_u3[numpy-8-4]",
"tests/test_gates_gates.py::test_u3[numpy-8-5]",
"tests/test_gates_gates.py::test_u3[numpy-8-6]",
"tests/test_gates_gates.py::test_u3[numpy-8-7]",
"tests/test_gates_gates.py::test_u3[numpy-8-8]",
"tests/test_gates_gates.py::test_u3[numpy-8-9]",
"tests/test_gates_gates.py::test_u3[numpy-8-10]",
"tests/test_gates_gates.py::test_u3[numpy-9-1]",
"tests/test_gates_gates.py::test_u3[numpy-9-2]",
"tests/test_gates_gates.py::test_u3[numpy-9-3]",
"tests/test_gates_gates.py::test_u3[numpy-9-4]",
"tests/test_gates_gates.py::test_u3[numpy-9-5]",
"tests/test_gates_gates.py::test_u3[numpy-9-6]",
"tests/test_gates_gates.py::test_u3[numpy-9-7]",
"tests/test_gates_gates.py::test_u3[numpy-9-8]",
"tests/test_gates_gates.py::test_u3[numpy-9-9]",
"tests/test_gates_gates.py::test_u3[numpy-9-10]",
"tests/test_gates_gates.py::test_u3[numpy-10-1]",
"tests/test_gates_gates.py::test_u3[numpy-10-2]",
"tests/test_gates_gates.py::test_u3[numpy-10-3]",
"tests/test_gates_gates.py::test_u3[numpy-10-4]",
"tests/test_gates_gates.py::test_u3[numpy-10-5]",
"tests/test_gates_gates.py::test_u3[numpy-10-6]",
"tests/test_gates_gates.py::test_u3[numpy-10-7]",
"tests/test_gates_gates.py::test_u3[numpy-10-8]",
"tests/test_gates_gates.py::test_u3[numpy-10-9]",
"tests/test_gates_gates.py::test_u3[numpy-10-10]",
"tests/test_gates_gates.py::test_cnot[numpy-False]",
"tests/test_gates_gates.py::test_cnot[numpy-True]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-1-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-2-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-3-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-4-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-5-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-6-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-7-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-8-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-9-10]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-1]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-2]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-3]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-4]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-5]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-6]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-7]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-8]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-9]",
"tests/test_gates_gates.py::test_cz[numpy-False-10-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-1-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-2-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-3-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-4-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-5-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-6-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-7-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-8-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-9-10]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-1]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-2]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-3]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-4]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-5]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-6]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-7]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-8]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-9]",
"tests/test_gates_gates.py::test_cz[numpy-True-10-10]",
"tests/test_gates_gates.py::test_csx[numpy]",
"tests/test_gates_gates.py::test_csxdg[numpy]",
"tests/test_gates_gates.py::test_cun[numpy-CRX-params0]",
"tests/test_gates_gates.py::test_cun[numpy-CRX-params1]",
"tests/test_gates_gates.py::test_cun[numpy-CRY-params2]",
"tests/test_gates_gates.py::test_cun[numpy-CRY-params3]",
"tests/test_gates_gates.py::test_cun[numpy-CRZ-params4]",
"tests/test_gates_gates.py::test_cun[numpy-CRZ-params5]",
"tests/test_gates_gates.py::test_cun[numpy-CU1-params6]",
"tests/test_gates_gates.py::test_cun[numpy-CU2-params7]",
"tests/test_gates_gates.py::test_cun[numpy-CU3-params8]",
"tests/test_gates_gates.py::test_swap[numpy]",
"tests/test_gates_gates.py::test_iswap[numpy]",
"tests/test_gates_gates.py::test_fswap[numpy]",
"tests/test_gates_gates.py::test_multiple_swap[numpy]",
"tests/test_gates_gates.py::test_fsim[numpy]",
"tests/test_gates_gates.py::test_sycamore[numpy]",
"tests/test_gates_gates.py::test_generalized_fsim[numpy]",
"tests/test_gates_gates.py::test_generalized_fsim_parameter_setter[numpy]",
"tests/test_gates_gates.py::test_rxx[numpy]",
"tests/test_gates_gates.py::test_ryy[numpy]",
"tests/test_gates_gates.py::test_rzz[numpy]",
"tests/test_gates_gates.py::test_rzx[numpy]",
"tests/test_gates_gates.py::test_rxy[numpy]",
"tests/test_gates_gates.py::test_ms[numpy]",
"tests/test_gates_gates.py::test_givens[numpy]",
"tests/test_gates_gates.py::test_rbs[numpy]",
"tests/test_gates_gates.py::test_ecr[numpy]",
"tests/test_gates_gates.py::test_toffoli[numpy-False]",
"tests/test_gates_gates.py::test_toffoli[numpy-True]",
"tests/test_gates_gates.py::test_deutsch[numpy]",
"tests/test_gates_gates.py::test_unitary_initialization[numpy]",
"tests/test_gates_gates.py::test_controlled_x[numpy]",
"tests/test_gates_gates.py::test_controlled_x_vs_cnot[numpy]",
"tests/test_gates_gates.py::test_controlled_x_vs_toffoli[numpy]",
"tests/test_gates_gates.py::test_controlled_rx[numpy-False]",
"tests/test_gates_gates.py::test_controlled_rx[numpy-True]",
"tests/test_gates_gates.py::test_controlled_u1[numpy]",
"tests/test_gates_gates.py::test_controlled_u2[numpy]",
"tests/test_gates_gates.py::test_controlled_u3[numpy]",
"tests/test_gates_gates.py::test_controlled_swap[numpy-False-False]",
"tests/test_gates_gates.py::test_controlled_swap[numpy-False-True]",
"tests/test_gates_gates.py::test_controlled_swap[numpy-True-False]",
"tests/test_gates_gates.py::test_controlled_swap[numpy-True-True]",
"tests/test_gates_gates.py::test_controlled_swap_double[numpy-False]",
"tests/test_gates_gates.py::test_controlled_swap_double[numpy-True]",
"tests/test_gates_gates.py::test_controlled_fsim[numpy]",
"tests/test_gates_gates.py::test_dagger[numpy-H-args0]",
"tests/test_gates_gates.py::test_dagger[numpy-X-args1]",
"tests/test_gates_gates.py::test_dagger[numpy-Y-args2]",
"tests/test_gates_gates.py::test_dagger[numpy-Z-args3]",
"tests/test_gates_gates.py::test_dagger[numpy-SX-args4]",
"tests/test_gates_gates.py::test_dagger[numpy-SXDG-args5]",
"tests/test_gates_gates.py::test_dagger[numpy-S-args6]",
"tests/test_gates_gates.py::test_dagger[numpy-SDG-args7]",
"tests/test_gates_gates.py::test_dagger[numpy-T-args8]",
"tests/test_gates_gates.py::test_dagger[numpy-TDG-args9]",
"tests/test_gates_gates.py::test_dagger[numpy-RX-args10]",
"tests/test_gates_gates.py::test_dagger[numpy-RY-args11]",
"tests/test_gates_gates.py::test_dagger[numpy-RZ-args12]",
"tests/test_gates_gates.py::test_dagger[numpy-GPI-args13]",
"tests/test_gates_gates.py::test_dagger[numpy-GPI2-args14]",
"tests/test_gates_gates.py::test_dagger[numpy-U1-args15]",
"tests/test_gates_gates.py::test_dagger[numpy-U2-args16]",
"tests/test_gates_gates.py::test_dagger[numpy-U3-args17]",
"tests/test_gates_gates.py::test_dagger[numpy-CNOT-args18]",
"tests/test_gates_gates.py::test_dagger[numpy-CZ-args19]",
"tests/test_gates_gates.py::test_dagger[numpy-CSX-args20]",
"tests/test_gates_gates.py::test_dagger[numpy-CSXDG-args21]",
"tests/test_gates_gates.py::test_dagger[numpy-CRX-args22]",
"tests/test_gates_gates.py::test_dagger[numpy-CRZ-args23]",
"tests/test_gates_gates.py::test_dagger[numpy-CU1-args24]",
"tests/test_gates_gates.py::test_dagger[numpy-CU2-args25]",
"tests/test_gates_gates.py::test_dagger[numpy-CU3-args26]",
"tests/test_gates_gates.py::test_dagger[numpy-fSim-args27]",
"tests/test_gates_gates.py::test_dagger[numpy-SYC-args28]",
"tests/test_gates_gates.py::test_dagger[numpy-RXX-args29]",
"tests/test_gates_gates.py::test_dagger[numpy-RYY-args30]",
"tests/test_gates_gates.py::test_dagger[numpy-RZZ-args31]",
"tests/test_gates_gates.py::test_dagger[numpy-RZX-args32]",
"tests/test_gates_gates.py::test_dagger[numpy-RXY-args33]",
"tests/test_gates_gates.py::test_dagger[numpy-MS-args34]",
"tests/test_gates_gates.py::test_dagger[numpy-GIVENS-args35]",
"tests/test_gates_gates.py::test_dagger[numpy-RBS-args36]",
"tests/test_gates_gates.py::test_dagger[numpy-ECR-args37]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-H-args0]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-X-args1]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-Y-args2]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-S-args3]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-SDG-args4]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-T-args5]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-TDG-args6]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-RX-args7]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-U1-args8]",
"tests/test_gates_gates.py::test_controlled_dagger[numpy-U3-args9]",
"tests/test_gates_gates.py::test_dagger_consistency[numpy-0-S-SDG]",
"tests/test_gates_gates.py::test_dagger_consistency[numpy-0-T-TDG]",
"tests/test_gates_gates.py::test_dagger_consistency[numpy-2-S-SDG]",
"tests/test_gates_gates.py::test_dagger_consistency[numpy-2-T-TDG]",
"tests/test_gates_gates.py::test_dagger_consistency[numpy-4-S-SDG]",
"tests/test_gates_gates.py::test_dagger_consistency[numpy-4-T-TDG]",
"tests/test_gates_gates.py::test_controlled_unitary_dagger[numpy]",
"tests/test_gates_gates.py::test_generalizedfsim_dagger[numpy]",
"tests/test_gates_gates.py::test_gate_basis_rotation[numpy]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-0-controls0-free0]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-2-controls1-free1]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-3-controls2-free2]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-7-controls3-free3]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-5-controls4-free4]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-8-controls5-free5]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-0-controls0-free0]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-2-controls1-free1]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-3-controls2-free2]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-7-controls3-free3]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-5-controls4-free4]",
"tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-8-controls5-free5]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-10 12:03:20+00:00
|
apache-2.0
| 5,133 |
|
qiboteam__qibo-1218
|
diff --git a/doc/source/api-reference/qibo.rst b/doc/source/api-reference/qibo.rst
index 3457ad0c0..4fcd781a9 100644
--- a/doc/source/api-reference/qibo.rst
+++ b/doc/source/api-reference/qibo.rst
@@ -2269,6 +2269,12 @@ Hellinger fidelity
.. autofunction:: qibo.quantum_info.hellinger_fidelity
+Hellinger shot error
+""""""""""""""""""""
+
+.. autofunction:: qibo.quantum_info.hellinger_fidelity
+
+
Haar integral
"""""""""""""
diff --git a/src/qibo/noise_model.py b/src/qibo/noise_model.py
index 44311c266..b3be7e84b 100644
--- a/src/qibo/noise_model.py
+++ b/src/qibo/noise_model.py
@@ -1,7 +1,7 @@
import numpy as np
from qibo import gates, models
-from qibo.quantum_info import hellinger_fidelity
+from qibo.quantum_info.utils import hellinger_fidelity, hellinger_shot_error
def noisy_circuit(circuit, params):
@@ -200,28 +200,6 @@ def freq_to_prob(freq):
return prob
-def hellinger_shot_error(p, q, nshots):
- """Hellinger fidelity error caused by using two probability distributions estimated using a finite number of shots.
- It is calculated propagating the probability error of each state of the system. The complete formula is:
- :math:`(1 - H^{2}(p, q))/\\sqrt{nshots} * \\sum_{i=1}^{n}(\\sqrt{p_i(1-q_i)}+\\sqrt{q_i(1-p_i)})`
- where the sum is made all over the possible states and :math:`H(p, q)` is the Hellinger distance.
-
- Args:
- p (numpy.ndarray): (discrete) probability distribution :math:`p`.
- q (numpy.ndarray): (discrete) probability distribution :math:`q`.
- nshots (int): the number of shots we used to run the circuit to obtain :math:`p` and :math:`q`.
-
- Returns:
- (float): The Hellinger fidelity error.
-
- """
- hellinger_fid = hellinger_fidelity(p, q)
- hellinger_fid_e = np.sqrt(hellinger_fid / nshots) * np.sum(
- np.sqrt(q * (1 - p)) + np.sqrt(p * (1 - q))
- )
- return hellinger_fid_e
-
-
def loss(parameters, *args):
"""The loss function used to be maximized in the fit method of the :class:`qibo.noise_model.CompositeNoiseModel`.
It is the hellinger fidelity calculated between the probability distribution of the noise model and the experimental target distribution using the :func:`qibo.quantum_info.hellinger_fidelity`.
diff --git a/src/qibo/quantum_info/utils.py b/src/qibo/quantum_info/utils.py
index ec772168e..a162561fd 100644
--- a/src/qibo/quantum_info/utils.py
+++ b/src/qibo/quantum_info/utils.py
@@ -258,14 +258,13 @@ def hellinger_fidelity(prob_dist_p, prob_dist_q, validate: bool = False, backend
.. math::
(1 - H^{2}(p, q))^{2} \\, ,
- where :math:`H(p, q)` is the Hellinger distance
- (:func:`qibo.quantum_info.utils.hellinger_distance`).
+ where :math:`H(p, q)` is the :func:`qibo.quantum_info.utils.hellinger_distance`.
Args:
prob_dist_p (ndarray or list): discrete probability distribution :math:`p`.
prob_dist_q (ndarray or list): discrete probability distribution :math:`q`.
- validate (bool, optional): if True, checks if :math:`p` and :math:`q` are proper
- probability distributions. Default: False.
+ validate (bool, optional): if ``True``, checks if :math:`p` and :math:`q` are proper
+ probability distributions. Defaults to ``False``.
backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be
used in the execution. If ``None``, it uses
:class:`qibo.backends.GlobalBackend`. Defaults to ``None``.
@@ -274,11 +273,62 @@ def hellinger_fidelity(prob_dist_p, prob_dist_q, validate: bool = False, backend
(float): Hellinger fidelity.
"""
+ backend = _check_backend(backend)
+
distance = hellinger_distance(prob_dist_p, prob_dist_q, validate, backend=backend)
return (1 - distance**2) ** 2
+def hellinger_shot_error(
+ prob_dist_p, prob_dist_q, nshots: int, validate: bool = False, backend=None
+):
+ """Calculates the Hellinger fidelity error between two discrete probability distributions estimated from finite statistics.
+
+ It is calculated propagating the probability error of each state of the system.
+ The complete formula is:
+
+ .. math::
+ \\frac{1 - H^{2}(p, q)}{\\sqrt{nshots}} \\, \\sum_{k} \\,
+ \\left(\\sqrt{p_{k} \\, (1 - q_{k})} + \\sqrt{q_{k} \\, (1 - p_{k})}\\right)
+
+ where :math:`H(p, q)` is the :func:`qibo.quantum_info.utils.hellinger_distance`,
+ and :math:`1 - H^{2}(p, q)` is the square root of the
+ :func:`qibo.quantum_info.utils.hellinger_fidelity`.
+
+ Args:
+ prob_dist_p (ndarray or list): discrete probability distribution :math:`p`.
+ prob_dist_q (ndarray or list): discrete probability distribution :math:`q`.
+ nshots (int): number of shots we used to run the circuit to obtain :math:`p` and :math:`q`.
+ validate (bool, optional): if ``True``, checks if :math:`p` and :math:`q` are proper
+ probability distributions. Defaults to ``False``.
+ backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be
+ used in the execution. If ``None``, it uses
+ :class:`qibo.backends.GlobalBackend`. Defaults to ``None``.
+
+ Returns:
+ (float): Hellinger fidelity error.
+
+ """
+ backend = _check_backend(backend)
+
+ if isinstance(prob_dist_p, list):
+ prob_dist_p = backend.cast(prob_dist_p, dtype=np.float64)
+
+ if isinstance(prob_dist_q, list):
+ prob_dist_q = backend.cast(prob_dist_q, dtype=np.float64)
+
+ hellinger_error = hellinger_fidelity(
+ prob_dist_p, prob_dist_q, validate=validate, backend=backend
+ )
+ hellinger_error = np.sqrt(hellinger_error / nshots) * np.sum(
+ np.sqrt(prob_dist_q * (1 - prob_dist_p))
+ + np.sqrt(prob_dist_p * (1 - prob_dist_q))
+ )
+
+ return hellinger_error
+
+
def haar_integral(
nqubits: int,
power_t: int,
|
qiboteam/qibo
|
1eac4039e11cfabfd51cd5b8f8f8b7146cde66ca
|
diff --git a/tests/test_quantum_info_utils.py b/tests/test_quantum_info_utils.py
index 049f80027..0d845cf2f 100644
--- a/tests/test_quantum_info_utils.py
+++ b/tests/test_quantum_info_utils.py
@@ -4,9 +4,10 @@ from re import finditer
import numpy as np
import pytest
-from qibo import Circuit, matrices
+from qibo import Circuit, gates, matrices
from qibo.config import PRECISION_TOL
from qibo.quantum_info.metrics import fidelity
+from qibo.quantum_info.random_ensembles import random_clifford
from qibo.quantum_info.utils import (
haar_integral,
hadamard_transform,
@@ -14,6 +15,7 @@ from qibo.quantum_info.utils import (
hamming_weight,
hellinger_distance,
hellinger_fidelity,
+ hellinger_shot_error,
pqc_integral,
)
@@ -175,6 +177,34 @@ def test_hellinger(backend, validate, kind):
assert fidelity == (1 - target**2) ** 2
[email protected]("kind", [None, list])
[email protected]("validate", [False, True])
+def test_hellinger_shot_error(backend, validate, kind):
+ nqubits, nshots = 5, 1000
+
+ circuit = random_clifford(nqubits, seed=1, backend=backend)
+ circuit.add(gates.M(qubit) for qubit in range(nqubits))
+
+ circuit_2 = random_clifford(nqubits, seed=2, backend=backend)
+ circuit_2.add(gates.M(qubit) for qubit in range(nqubits))
+
+ prob_dist_p = backend.execute_circuit(circuit, nshots=nshots).probabilities()
+ prob_dist_q = backend.execute_circuit(circuit_2, nshots=nshots).probabilities()
+
+ if kind is not None:
+ prob_dist_p = kind(prob_dist_p)
+ prob_dist_q = kind(prob_dist_q)
+
+ hellinger_error = hellinger_shot_error(
+ prob_dist_p, prob_dist_q, nshots, validate=validate, backend=backend
+ )
+ hellinger_fid = hellinger_fidelity(
+ prob_dist_p, prob_dist_q, validate=validate, backend=backend
+ )
+
+ assert 2 * hellinger_error < hellinger_fid
+
+
def test_haar_integral_errors(backend):
with pytest.raises(TypeError):
nqubits, power_t, samples = 0.5, 2, 10
|
Move `noise_model.hellinger_shot_error` to `quantum_info.utils`
|
0.0
|
1eac4039e11cfabfd51cd5b8f8f8b7146cde66ca
|
[
"tests/test_quantum_info_utils.py::test_hamming_weight[str-0]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-1]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-2]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-3]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-4]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-5]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-6]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-7]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-8]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-9]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-10]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-11]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-12]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-13]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-14]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-15]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-16]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-17]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-18]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-19]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-20]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-21]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-22]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-23]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-24]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-25]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-26]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-27]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-28]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-29]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-30]",
"tests/test_quantum_info_utils.py::test_hamming_weight[str-31]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-0]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-1]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-2]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-3]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-4]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-5]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-6]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-7]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-8]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-9]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-10]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-11]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-12]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-13]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-14]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-15]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-16]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-17]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-18]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-19]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-20]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-21]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-22]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-23]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-24]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-25]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-26]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-27]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-28]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-29]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-30]",
"tests/test_quantum_info_utils.py::test_hamming_weight[list-31]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-0]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-1]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-2]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-3]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-4]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-5]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-6]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-7]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-8]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-9]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-10]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-11]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-12]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-13]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-14]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-15]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-16]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-17]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-18]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-19]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-20]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-21]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-22]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-23]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-24]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-25]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-26]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-27]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-28]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-29]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-30]",
"tests/test_quantum_info_utils.py::test_hamming_weight[tuple-31]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-0]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-1]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-2]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-3]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-4]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-5]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-6]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-7]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-8]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-9]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-10]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-11]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-12]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-13]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-14]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-15]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-16]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-17]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-18]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-19]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-20]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-21]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-22]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-23]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-24]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-25]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-26]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-27]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-28]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-29]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-30]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>0-31]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-0]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-1]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-2]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-3]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-4]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-5]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-6]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-7]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-8]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-9]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-10]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-11]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-12]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-13]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-14]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-15]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-16]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-17]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-18]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-19]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-20]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-21]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-22]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-23]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-24]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-25]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-26]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-27]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-28]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-29]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-30]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>1-31]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-0]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-1]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-2]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-3]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-4]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-5]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-6]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-7]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-8]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-9]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-10]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-11]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-12]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-13]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-14]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-15]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-16]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-17]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-18]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-19]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-20]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-21]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-22]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-23]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-24]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-25]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-26]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-27]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-28]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-29]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-30]",
"tests/test_quantum_info_utils.py::test_hamming_weight[<lambda>2-31]",
"tests/test_quantum_info_utils.py::test_hamming_distance[11111-10101]",
"tests/test_quantum_info_utils.py::test_hamming_distance[31-21]",
"tests/test_quantum_info_utils.py::test_hamming_distance[bitstring_12-bitstring_22]",
"tests/test_quantum_info_utils.py::test_hamming_distance[bitstring_13-bitstring_23]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-3-fast-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-3-fast-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-3-regular-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-3-regular-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-4-fast-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-4-fast-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-4-regular-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-4-regular-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-5-fast-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-5-fast-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-5-regular-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[numpy-5-regular-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-3-fast-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-3-fast-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-3-regular-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-3-regular-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-4-fast-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-4-fast-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-4-regular-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-4-regular-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-5-fast-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-5-fast-True]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-5-regular-False]",
"tests/test_quantum_info_utils.py::test_hadamard_transform[tensorflow-5-regular-True]",
"tests/test_quantum_info_utils.py::test_hellinger[numpy-False-None]",
"tests/test_quantum_info_utils.py::test_hellinger[numpy-False-list]",
"tests/test_quantum_info_utils.py::test_hellinger[numpy-True-None]",
"tests/test_quantum_info_utils.py::test_hellinger[numpy-True-list]",
"tests/test_quantum_info_utils.py::test_hellinger[tensorflow-False-None]",
"tests/test_quantum_info_utils.py::test_hellinger[tensorflow-False-list]",
"tests/test_quantum_info_utils.py::test_hellinger[tensorflow-True-None]",
"tests/test_quantum_info_utils.py::test_hellinger[tensorflow-True-list]",
"tests/test_quantum_info_utils.py::test_hellinger_shot_error[numpy-False-None]",
"tests/test_quantum_info_utils.py::test_hellinger_shot_error[numpy-False-list]",
"tests/test_quantum_info_utils.py::test_hellinger_shot_error[numpy-True-None]",
"tests/test_quantum_info_utils.py::test_hellinger_shot_error[numpy-True-list]",
"tests/test_quantum_info_utils.py::test_hellinger_shot_error[tensorflow-False-None]",
"tests/test_quantum_info_utils.py::test_hellinger_shot_error[tensorflow-False-list]",
"tests/test_quantum_info_utils.py::test_hellinger_shot_error[tensorflow-True-None]",
"tests/test_quantum_info_utils.py::test_hellinger_shot_error[tensorflow-True-list]",
"tests/test_quantum_info_utils.py::test_haar_integral_errors[numpy]",
"tests/test_quantum_info_utils.py::test_haar_integral_errors[tensorflow]",
"tests/test_quantum_info_utils.py::test_haar_integral[numpy-2-1]",
"tests/test_quantum_info_utils.py::test_haar_integral[numpy-2-2]",
"tests/test_quantum_info_utils.py::test_haar_integral[numpy-3-1]",
"tests/test_quantum_info_utils.py::test_haar_integral[numpy-3-2]",
"tests/test_quantum_info_utils.py::test_haar_integral[tensorflow-2-1]",
"tests/test_quantum_info_utils.py::test_haar_integral[tensorflow-2-2]",
"tests/test_quantum_info_utils.py::test_haar_integral[tensorflow-3-1]",
"tests/test_quantum_info_utils.py::test_haar_integral[tensorflow-3-2]",
"tests/test_quantum_info_utils.py::test_pqc_integral[numpy]",
"tests/test_quantum_info_utils.py::test_pqc_integral[tensorflow]"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-02-14 05:19:21+00:00
|
apache-2.0
| 5,134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.